From e493ce20aeca294a4abbb502e88697565a9ef395 Mon Sep 17 00:00:00 2001 From: SamG-Coder <13449963+SamG-Coder@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:53:35 +1100 Subject: [PATCH 1/3] Bring back from Aussie Outback 4x4 what it added to the engine: four-wheel drive, ruts, blows, shared scenes The game is built on the engine in a fork, and changed the engine's crates as it went. This is everything in them that is not the game's own, on main as it is now. Vehicles: a transfer case with low range and lockers, a driveline solved as one, seven more surfaces with how far a tyre sinks and digs in each and what rain does, tyres aired down, a payload, a tray that things lie in, and ground that keeps the ruts pressed into it (solstice-vehicle's rut.rs), which the wheels behind ride in. Game: a driver who gets out and walks, loose things as bodies, blows measured (impact.rs), a map of what the ground is made of (ground.rs) with a `surfaces FILE` line in a scene's text to name one, a time to beat worked out from a track (par.rs), and parts of a car's model taken off and put back. Rendering: ruts drawn by relief mapping from the cells the wheels read, mud that lies wet and cracks at its rim, glass seen through, headlamps, a coat of paint, rust, dust and mud on whatever is driven, and pages and materials written while a game is played. Scenes: an actor whose model is in a file shared with other scenes (`shared`), a scene that lends its meshes and textures to those baked beside it (`lends`), the join that makes one scene of two, and packs of pieces read one at a time (`bake --kit`). The viewer reads a scene with the file it shares, whole or streamed, and draws ruts round whatever is driven. Nothing else of the game's viewer is here, nor its world generator. The tests' trucks are fixtures beside gt.vehicle. docs/ruts.md says how ruts are built; docs/gameplay.md says how scenes share. Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 22 + apps/bake/src/kit.rs | 114 +++ apps/bake/src/main.rs | 79 ++ apps/viewer/src/lib.rs | 2 + apps/viewer/src/main.rs | 52 +- apps/viewer/src/play.rs | 48 +- apps/viewer/src/shared.rs | 219 +++++ crates/solstice-asset/src/join.rs | 426 ++++++++ crates/solstice-asset/src/lib.rs | 2 + crates/solstice-asset/src/pack.rs | 114 +++ crates/solstice-asset/src/scene.rs | 15 + crates/solstice-bake/Cargo.toml | 2 + crates/solstice-bake/src/lend.rs | 350 +++++++ crates/solstice-bake/src/lib.rs | 1 + crates/solstice-bake/src/project.rs | 8 + crates/solstice-bake/src/scene_file.rs | 161 ++- crates/solstice-builder/src/dag.rs | 8 +- crates/solstice-builder/tests/join.rs | 165 ++++ crates/solstice-game/src/actor.rs | 25 + crates/solstice-game/src/drive.rs | 301 +++++- crates/solstice-game/src/ground.rs | 220 +++++ crates/solstice-game/src/impact.rs | 378 +++++++ crates/solstice-game/src/input.rs | 44 + crates/solstice-game/src/lib.rs | 10 +- crates/solstice-game/src/par.rs | 292 ++++++ crates/solstice-game/src/play.rs | 681 ++++++++++++- crates/solstice-game/src/race.rs | 26 +- crates/solstice-game/src/scene.rs | 32 +- crates/solstice-game/src/track.rs | 2 +- crates/solstice-game/tests/blows.rs | 230 +++++ crates/solstice-game/tests/things.rs | 241 +++++ crates/solstice-import/src/lib.rs | 7 + crates/solstice-import/src/material.rs | 44 +- crates/solstice-import/src/streamed.rs | 22 +- crates/solstice-import/src/tests.rs | 17 +- crates/solstice-physics/src/car.rs | 317 +++++- crates/solstice-physics/src/lib.rs | 113 ++- crates/solstice-physics/tests/walking.rs | 8 +- crates/solstice-procgen/src/bush.rs | 563 +++++++++++ crates/solstice-procgen/src/foliage/bark.rs | 128 ++- crates/solstice-procgen/src/foliage/leaf.rs | 98 +- crates/solstice-procgen/src/foliage/tree.rs | 4 +- crates/solstice-procgen/src/lib.rs | 2 + crates/solstice-procgen/src/surfaces.rs | 5 +- .../solstice-render/shaders/common/frame.wgsl | 46 + .../solstice-render/shaders/common/scene.wgsl | 6 + .../solstice-render/shaders/gi/voxelize.wgsl | 4 +- .../solstice-render/shaders/ground/ruts.wgsl | 407 ++++++++ .../shaders/lighting/deferred.wgsl | 27 + .../shaders/vg/cover_mask.wgsl | 8 +- .../shaders/vg/cover_none.wgsl | 2 +- crates/solstice-render/shaders/vg/mask.wgsl | 20 + .../shaders/vg/raster_hw_masked.wgsl | 16 +- .../shaders/vg/raster_sw_body.wgsl | 2 +- .../solstice-render/shaders/vg/resolve.wgsl | 220 ++++- crates/solstice-render/src/frame.rs | 108 +- crates/solstice-render/src/lib.rs | 4 +- crates/solstice-render/src/motion.rs | 10 +- crates/solstice-render/src/renderer.rs | 158 +++ crates/solstice-render/src/ruts.rs | 259 +++++ crates/solstice-render/src/scene.rs | 5 +- crates/solstice-render/src/shaders.rs | 3 +- crates/solstice-render/src/streaming/mod.rs | 60 ++ .../solstice-render/src/vg/raster_stress.rs | 2 +- crates/solstice-render/src/vg/resolve.rs | 5 + crates/solstice-script/src/api.rs | 7 +- crates/solstice-vehicle/src/driver.rs | 47 +- crates/solstice-vehicle/src/drivetrain.rs | 388 ++++++++ crates/solstice-vehicle/src/lib.rs | 8 +- crates/solstice-vehicle/src/rut.rs | 921 ++++++++++++++++++ crates/solstice-vehicle/src/spec.rs | 269 ++++- crates/solstice-vehicle/src/surface.rs | 317 +++++- crates/solstice-vehicle/src/tyre.rs | 11 + crates/solstice-vehicle/src/vehicle.rs | 618 +++++++++++- crates/solstice-vehicle/tests/ruts.rs | 318 ++++++ crates/solstice-vehicle/tests/truck.rs | 361 +++++++ crates/solstice-vehicle/tests/truck.vehicle | 60 ++ crates/solstice-vehicle/tests/wagon.vehicle | 45 + crates/solstice-world/src/input.rs | 6 + crates/solstice-world/src/lib.rs | 2 +- crates/solstice-world/src/transform.rs | 3 +- docs/gameplay.md | 42 + docs/ruts.md | 225 +++++ 83 files changed, 10342 insertions(+), 276 deletions(-) create mode 100644 apps/bake/src/kit.rs create mode 100644 apps/viewer/src/shared.rs create mode 100644 crates/solstice-asset/src/join.rs create mode 100644 crates/solstice-asset/src/pack.rs create mode 100644 crates/solstice-bake/src/lend.rs create mode 100644 crates/solstice-builder/tests/join.rs create mode 100644 crates/solstice-game/src/ground.rs create mode 100644 crates/solstice-game/src/impact.rs create mode 100644 crates/solstice-game/src/par.rs create mode 100644 crates/solstice-game/tests/blows.rs create mode 100644 crates/solstice-game/tests/things.rs create mode 100644 crates/solstice-procgen/src/bush.rs create mode 100644 crates/solstice-render/shaders/ground/ruts.wgsl create mode 100644 crates/solstice-render/src/ruts.rs create mode 100644 crates/solstice-vehicle/src/rut.rs create mode 100644 crates/solstice-vehicle/tests/ruts.rs create mode 100644 crates/solstice-vehicle/tests/truck.rs create mode 100644 crates/solstice-vehicle/tests/truck.vehicle create mode 100644 crates/solstice-vehicle/tests/wagon.vehicle create mode 100644 docs/ruts.md diff --git a/Cargo.lock b/Cargo.lock index 1d9e770..9302239 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -624,6 +624,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + [[package]] name = "crc" version = "3.4.0" @@ -3085,6 +3094,17 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -3202,9 +3222,11 @@ dependencies = [ name = "solstice-bake" version = "0.2.0" dependencies = [ + "bytemuck", "glam 0.33.12", "rayon", "rustc-hash 2.1.3", + "sha2", "solstice-anim", "solstice-asset", "solstice-builder", diff --git a/apps/bake/src/kit.rs b/apps/bake/src/kit.rs new file mode 100644 index 0000000..76b4d0c --- /dev/null +++ b/apps/bake/src/kit.rs @@ -0,0 +1,114 @@ +//! Packs a truck that is built of pieces: `bake --kit TRUCK.actor --output TRUCK.truck`. +//! +//! The truck's model has every piece of it, each a named object: the bare truck, and every +//! thing that can be fitted to it. Baked into a scene, all +//! of it would be read whenever the truck was. Packed, each piece is a small scene of its +//! own in one file (`solstice_asset::pack`), beside the texts that say what the truck is: +//! its actor file, its numbers and its kit. The game reads the texts, and then only the +//! pieces the truck is wearing (`solstice_asset::pack::read`). + +use solstice_asset::{pack, SceneAsset}; +use solstice_game::{resolve, ActorFile}; +use solstice_import::{import_gltf, ImportOptions}; +use std::collections::HashMap; +use std::path::Path; + +pub fn bake_kit(actor_path: &Path, output: &Path) -> Result<(), String> { + let read = |path: &Path| { + std::fs::read_to_string(path).map_err(|error| format!("{}: {error}", path.display())) + }; + let file_name = |path: &Path| { + let name = path.file_name().ok_or("the actor file has no name")?; + Ok::(name.to_string_lossy().into_owned()) + }; + let actor_name = file_name(actor_path)?; + let actor_text = read(actor_path)?; + let actor = ActorFile::parse(&actor_text).map_err(|error| format!("{actor_name}: {error}"))?; + let folder = actor_path.parent().unwrap_or(Path::new(".")); + let mesh = actor.mesh.as_ref().ok_or("the actor has no mesh")?; + let (Some(vehicle), Some(kit)) = (&actor.vehicle, &actor.kit) else { + return Err( + "the actor is not a truck with a kit: it needs `vehicle` and `kit` lines".into(), + ); + }; + // Its texts, by the names its actor file knows them by. + let mut texts = vec![(actor_name.clone(), actor_text.clone())]; + for named in [&vehicle.path, kit] { + texts.push((resolve(&actor_name, named), read(&folder.join(named))?)); + } + + let model = folder.join(&mesh.path); + let imported = import_gltf(&model, &ImportOptions::default()) + .map_err(|error| format!("{}: {error}", model.display()))?; + let whole = imported.scene; + // Each piece is the instances of one named object, with the meshes and the materials + // they use and no others. + let mut order: Vec<&str> = Vec::new(); + for name in imported.names.iter().filter(|name| !name.is_empty()) { + if !order.contains(&name.as_str()) { + order.push(name); + } + } + let mut pieces = Vec::new(); + let (mut triangles, mut unpinned) = (0, 0); + for name in order { + let mut piece = SceneAsset::default(); + let (mut meshes, mut materials) = (HashMap::new(), HashMap::new()); + for (instance, _) in whole + .instances + .iter() + .zip(&imported.names) + .filter(|(_, of)| of.as_str() == name) + { + let mesh = *meshes.entry(instance.mesh).or_insert_with(|| { + piece + .meshes + .push(whole.meshes[instance.mesh as usize].clone()); + piece.meshes.len() as u32 - 1 + }); + let material = *materials.entry(instance.material).or_insert_with(|| { + piece + .materials + .push(whole.materials[instance.material as usize]); + piece.materials.len() as u32 - 1 + }); + piece.instances.push(solstice_asset::Instance { + mesh, + material, + transform: instance.transform, + }); + } + triangles += piece.total_source_triangles(); + let mut loaded = solstice_builder::paginate(&piece); + // A truck bumps into things with its own box, not with its pieces. + loaded.collision = None; + unpinned += usize::from(!loaded.pages.is_empty()); + pieces.push((name, solstice_asset::file::encode(&loaded))); + } + + let mut things: Vec<(&str, &str, &[u8])> = Vec::new(); + for (name, text) in &texts { + things.push(("text", name, text.as_bytes())); + } + for (name, bytes) in &pieces { + things.push(("piece", name, bytes)); + } + let file = pack::write(&things); + if let Some(parent) = output.parent() { + std::fs::create_dir_all(parent) + .map_err(|error| format!("{}: {error}", parent.display()))?; + } + std::fs::write(output, &file).map_err(|error| format!("{}: {error}", output.display()))?; + println!( + "wrote {}: {} pieces, {triangles} triangles, {:.1} MB{}", + output.display(), + pieces.len(), + file.len() as f64 / 1e6, + if unpinned > 0 { + format!(" ({unpinned} pieces have pages that are not always loaded)") + } else { + String::new() + } + ); + Ok(()) +} diff --git a/apps/bake/src/main.rs b/apps/bake/src/main.rs index 19729c8..4f392f9 100644 --- a/apps/bake/src/main.rs +++ b/apps/bake/src/main.rs @@ -37,6 +37,7 @@ mod collision_view; mod forest; mod gallery; +mod kit; mod plants; mod scene; @@ -86,6 +87,8 @@ struct Options { /// A character to check, and its rig's role file. check_character: Option, roles: Option, + /// A truck built of pieces to pack: its actor file (`kit.rs`). + kit: Option, } /// Writes the file a browser reads for a scene too large for its memory: the manifest without @@ -164,6 +167,7 @@ fn parse_args() -> Result { large: Default::default(), check_character: None, roles: None, + kit: None, }; let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { @@ -182,6 +186,7 @@ fn parse_args() -> Result { options.output_given = true; } "--scene" => options.scene_file = Some(PathBuf::from(value()?)), + "--kit" => options.kit = Some(PathBuf::from(value()?)), "--project" => options.project_scene = Some(PathBuf::from(value()?)), "--convert" => options.convert = Some(PathBuf::from(value()?)), "--check-character" => options.check_character = Some(PathBuf::from(value()?)), @@ -365,6 +370,52 @@ fn write_surfaces(folder: &Path, size: u32) -> Result<(), String> { Ok(()) } +/// The file of what a game's scenes share, beside theirs (the viewer's `shared.rs`). +const SHARED_FILE: &str = "shared.solstice"; + +/// Whether a scene has actors whose models are in the shared file: it is read with it. +fn reads_shared(scene: &solstice_asset::SceneAsset) -> bool { + scene + .gameplay + .iter() + .filter(|file| file.name == solstice_game::GAME_FILE) + .flat_map(|file| file.text.lines()) + .any(|line| { + let words: Vec<&str> = line.split_whitespace().collect(); + match words.split_first() { + Some((&"actor", rest)) => { + solstice_game::scene::ActorLine::parse(rest).is_ok_and(|actor| actor.shared) + } + _ => false, + } + }) +} + +/// What a baked scene lends, as the text of its list: nothing, if it has no list. +fn lender(path: &Path) -> Result { + use solstice_asset::file; + use std::io::{Read, Seek, SeekFrom}; + let failed = |error: std::io::Error| error.to_string(); + let mut scene = std::fs::File::open(path).map_err(failed)?; + let mut head = [0; file::HEADER_BYTES]; + scene.read_exact(&mut head).map_err(failed)?; + let header = file::decode_header(&head).map_err(|error| error.to_string())?; + scene + .seek(SeekFrom::Start(header.manifest_offset)) + .map_err(failed)?; + let mut packed = vec![0; header.manifest_bytes as usize]; + scene.read_exact(&mut packed).map_err(failed)?; + let manifest = file::inflate(&packed).map_err(|error| error.to_string())?; + let scene = file::decode_manifest(&manifest, header.manifest_offset + header.manifest_bytes) + .map_err(|error| error.to_string())?; + Ok(scene + .gameplay + .into_iter() + .find(|file| file.name == solstice_asset::join::LENDS) + .map(|file| file.text) + .unwrap_or_default()) +} + fn main() -> Result<(), String> { let mut options = parse_args()?; if options.scene_file.is_some() && options.project_scene.is_some() { @@ -388,6 +439,10 @@ fn main() -> Result<(), String> { if let Some(path) = &options.check_character { return check_character(path, options.roles.as_ref()); } + // A truck built of pieces is packed, each piece to be read alone (`kit.rs`). + if let Some(actor) = &options.kit { + return kit::bake_kit(actor, &options.output); + } let start = Instant::now(); if let Some(path) = &options.web_split { return web_split(path, &options.output).map_err(|e| e.to_string()); @@ -399,6 +454,30 @@ fn main() -> Result<(), String> { if options.show_collision { scene = collision_view::collision_scene(&scene)?; } + // A scene read with the file of what its game's maps share leaves out of its own what + // that file lends: the file is beside where this one is written. + if std::env::var_os("SOLSTICE_WHOLE").is_none() && reads_shared(&scene) { + let beside = options.output.with_file_name(SHARED_FILE); + let lends = lender(&beside).map_err(|error| { + format!( + "{}: {error}: this scene is read with it, so bake it first", + beside.display() + ) + })?; + let left = solstice_bake::lend::borrow(&mut scene, &lends); + println!( + "left to {}: {} meshes, {} texture layers", + beside.display(), + left.meshes, + left.textures + ); + if left.meshes + left.textures > 0 { + scene.gameplay.push(solstice_asset::GameFile { + name: solstice_asset::join::BORROWS.to_owned(), + text: left.text, + }); + } + } if !options.raw_textures { println!("compressing {} texture layers...", scene.textures.len()); solstice_builder::compress_textures(&mut scene); diff --git a/apps/viewer/src/lib.rs b/apps/viewer/src/lib.rs index 184287d..661a760 100644 --- a/apps/viewer/src/lib.rs +++ b/apps/viewer/src/lib.rs @@ -5,6 +5,8 @@ pub mod bob; pub mod camera_path; #[cfg(feature = "gameplay")] pub mod play; +#[cfg(feature = "gameplay")] +pub mod shared; #[cfg(target_arch = "wasm32")] mod web; diff --git a/apps/viewer/src/main.rs b/apps/viewer/src/main.rs index 436766c..fdd9830 100644 --- a/apps/viewer/src/main.rs +++ b/apps/viewer/src/main.rs @@ -118,7 +118,16 @@ mod native { request: &StreamRequest, ) -> Result, Box> { let mut file = std::fs::File::open(path)?; - file.seek(SeekFrom::Start(request.start))?; + // A scene joined with the file it shares with others is two files, whose bytes are + // numbered straight on from one to the other: past the end of the scene's is the + // shared one (`read_source`). + let length = file.metadata()?.len(); + if request.start >= length { + file = std::fs::File::open(path.with_file_name(solstice_viewer::shared::FILE))?; + file.seek(SeekFrom::Start(request.start - length))?; + } else { + file.seek(SeekFrom::Start(request.start))?; + } let mut bytes = vec![0; (request.end - request.start) as usize]; file.read_exact(&mut bytes)?; if request.deflated { @@ -792,17 +801,48 @@ mod native { Ok(scene) } + /// Reads a scene: all of it, or what says where the rest of it is. One whose game has + /// actors that are in the file it shares with other scenes is read with that file, which + /// is beside it, and the two are one scene (`solstice_viewer::shared`). + fn read_source(options: &Options) -> Result> { + let path = &options.scene; + let beside = path.with_file_name(solstice_viewer::shared::FILE); + let missing = |error: Box| { + format!( + "{}, which this scene is read with, could not be read: {error}", + beside.display() + ) + }; + Ok(if options.stream { + let mut scene = read_manifest(path)?; + if solstice_viewer::shared::wanted(&scene.gameplay) { + let shared = read_manifest(&beside).map_err(missing)?; + let files = shared.gameplay.clone(); + // The shared file's bytes are numbered on from the end of the scene's. + let after = std::fs::metadata(path)?.len(); + let joined = solstice_asset::join::join(&mut scene, shared, after)?; + solstice_viewer::shared::adopt(&mut scene, &files, joined)?; + } + Source::Streamed(scene) + } else { + let mut scene = load_scene(path)?; + if solstice_viewer::shared::wanted(&scene.scene.gameplay) { + let shared = load_scene(&beside).map_err(missing)?; + let files = shared.scene.gameplay.clone(); + let joined = scene.join(shared)?; + solstice_viewer::shared::adopt(&mut scene.scene, &files, joined)?; + } + Source::Loaded(scene) + }) + } + pub fn run() -> Result<(), Box> { env_logger::Builder::from_env( env_logger::Env::default().default_filter_or("info,wgpu_core=warn,wgpu_hal=warn"), ) .init(); let options = parse_args()?; - let scene = if options.stream { - Source::Streamed(read_manifest(&options.scene)?) - } else { - Source::Loaded(load_scene(&options.scene)?) - }; + let scene = read_source(&options)?; if let Some(near) = options.instances_near { scene.list_instances(near); return Ok(()); diff --git a/apps/viewer/src/play.rs b/apps/viewer/src/play.rs index bd19b29..dd29b8b 100644 --- a/apps/viewer/src/play.rs +++ b/apps/viewer/src/play.rs @@ -4,9 +4,51 @@ use solstice_asset::{Collision, GameFile}; use solstice_game::animation::AnimationAssets; +use solstice_game::rut::{self, Ruts}; pub use solstice_game::Message; use solstice_game::{Devices, Play}; -use solstice_render::{Camera, Renderer}; +use solstice_render::{Camera, Renderer, RutSource}; + +// The map of ruts is copied to the renderer a square at a time, as it is kept: both must agree +// on what a square is. +const _: () = assert!( + rut::TILE == solstice_render::ruts::TILE as usize + && rut::LEVELS == solstice_render::ruts::LEVELS as usize +); + +/// The map of ruts, as the renderer asks for it. +struct Kept<'a>(&'a Ruts); + +impl RutSource for Kept<'_> { + fn cell(&self) -> f32 { + rut::CELL + } + + fn is_empty(&self) -> bool { + self.0.is_empty() + } + + fn version(&self, tile: (i32, i32)) -> u32 { + self.0.version(tile) + } + + fn levels(&self, tile: (i32, i32), layer: usize) -> Option>> { + let mut levels = vec![self.0.layer(tile, layer)?.to_vec()]; + levels.extend(self.0.smaller(tile, layer)?); + Some(levels) + } +} + +/// Brings the ruts the renderer draws up to date with the ones the game keeps (docs/ruts.md), +/// round `centre`: the car, or wherever is looked at. Nothing is done on ground nobody has +/// driven on. +fn draw_ruts(renderer: &mut Renderer, play: &Play, centre: glam::Vec3) { + play.ruts(|ruts| { + // Nobody else keeps a list of what changed: each square's own count says. + ruts.take_changed(); + renderer.sync_ruts(glam::Vec2::new(centre.x, centre.z), &Kept(ruts)); + }); +} /// A scene's game, running in a viewer. pub struct PlayMode { @@ -59,6 +101,10 @@ impl PlayMode { camera.yaw = view.yaw; camera.pitch = view.pitch; } + // What the car's tyres have pressed into soft ground is drawn round the car. + let driven = self.play.hud().filter(|hud| !hud.afoot); + let looked_at = driven.map_or(camera.position, |hud| hud.origin); + draw_ruts(renderer, &self.play, looked_at); self.play.take_messages() } } diff --git a/apps/viewer/src/shared.rs b/apps/viewer/src/shared.rs new file mode 100644 index 0000000..81ff739 --- /dev/null +++ b/apps/viewer/src/shared.rs @@ -0,0 +1,219 @@ +//! What several scenes share: actors whose models are in a file of their own. +//! +//! A game's maps have things in common that are no part of any of them: its car, what its +//! player carries. They are not in a map's file. They are in one file beside the maps, +//! [`FILE`], baked from a scene of its own, and whichever map is played is joined with it as +//! it is read (`solstice_asset::join`). A map's text says which of its actors are there +//! rather than in it: `actor cove/car.actor X Y Z YAW shared`. The shared file has an actor +//! of the same file, with the instances that draw it; joined, the map's actor is given those +//! instances, and they are put where the map puts the actor ([`adopt`]). +//! +//! A map that is read with the shared file also leaves out of its own whatever else that +//! file lends: meshes and textures the two both have. They are put back as the two are +//! joined (`solstice_asset::join::fill`, docs/gameplay.md). +use glam::{Mat4, Quat}; +use solstice_asset::join::Joined; +use solstice_asset::{GameFile, PagedScene}; +use solstice_game::scene::ActorLine; +use solstice_game::GAME_FILE; + +/// The file of what is shared, beside the scenes'. +pub const FILE: &str = "shared.solstice"; + +/// The actors of a scene's game, each with the line it is on. +fn actors(files: &[GameFile]) -> Vec<(usize, ActorLine)> { + let Some(game) = files.iter().find(|file| file.name == GAME_FILE) else { + return Vec::new(); + }; + game.text + .lines() + .enumerate() + .filter_map(|(index, line)| { + let words: Vec<&str> = line.split_whitespace().collect(); + match words.split_first() { + Some((&"actor", rest)) => ActorLine::parse(rest).ok().map(|actor| (index, actor)), + _ => None, + } + }) + .collect() +} + +/// What a game is played by is the same on every map: its actors' files, their scripts, a +/// car's numbers and the input's actions. A map has copies of them, from when it was baked; +/// the shared file's take their place as the two are joined, and any it has that the map has +/// not are added. So what they do is changed by baking the shared file alone. +/// +/// (What a map lists of its own is its own: its actors and where they stand, its track.) +pub fn share_code(files: &mut Vec, shared: &[GameFile]) { + let code = |name: &str| { + [".actor", ".star", ".input", ".vehicle"] + .iter() + .any(|kind| name.ends_with(kind)) + }; + for theirs in shared.iter().filter(|file| code(&file.name)) { + match files.iter_mut().find(|own| own.name == theirs.name) { + Some(own) => own.text.clone_from(&theirs.text), + None => files.push(theirs.clone()), + } + } +} + +/// Whether a scene's game has actors that are in the shared file. +pub fn wanted(files: &[GameFile]) -> bool { + actors(files).iter().any(|(_, actor)| actor.shared) +} + +/// A scene has been joined with the shared file, whose gameplay files `shared` are: gives +/// each of the scene's shared actors the instances that draw it, and puts them where the +/// scene puts the actor. +pub fn adopt(scene: &mut PagedScene, shared: &[GameFile], joined: Joined) -> Result<(), String> { + share_code(&mut scene.gameplay, shared); + let there = actors(shared); + let mut changed = Vec::new(); + for (line, mut actor) in actors(&scene.gameplay) { + if !actor.shared { + continue; + } + let (_, theirs) = there + .iter() + .find(|(_, theirs)| theirs.file == actor.file) + .ok_or_else(|| format!("{} is not in {FILE}", actor.file))?; + let Some(instances) = theirs.instances.clone() else { + // It has no model: nothing draws it, there or here. + actor.shared = false; + changed.push((line, actor)); + continue; + }; + let instances = instances.start + joined.instances..instances.end + joined.instances; + // The shared file has it where it was baked; the scene has it where it starts. + let place = |actor: &ActorLine| { + Mat4::from_rotation_translation( + Quat::from_rotation_y(actor.yaw_degrees.to_radians()), + actor.position, + ) + }; + let moved = place(&actor) * place(theirs).inverse(); + for id in instances.clone() { + let instance = scene + .instances + .get_mut(id as usize) + .ok_or_else(|| format!("{FILE} has no instance {id} for {}", actor.file))?; + instance.transform = moved * instance.transform; + } + // If it is a kit, the list of its pieces comes with it: it counts from the actor's + // first instance, wherever that now is. + let pieces = solstice_game::actor::pieces_file(&actor.file); + if let Some(file) = shared.iter().find(|file| file.name == pieces) { + if !scene.gameplay.iter().any(|f| f.name == pieces) { + scene.gameplay.push(file.clone()); + } + } + actor.instances = Some(instances); + actor.shared = false; + changed.push((line, actor)); + } + if let Some(game) = scene + .gameplay + .iter_mut() + .find(|file| file.name == GAME_FILE) + { + let mut lines: Vec = game.text.lines().map(str::to_owned).collect(); + for (line, actor) in changed { + lines[line] = actor.to_text(); + } + game.text = lines.join("\n") + "\n"; + } + // And what the scene left out because the shared file has it: its meshes and textures. + let text = |files: &[GameFile], name: &str| { + files + .iter() + .find(|file| file.name == name) + .map(|file| file.text.clone()) + }; + if let Some(borrows) = text(&scene.gameplay, solstice_asset::join::BORROWS) { + let lends = text(shared, solstice_asset::join::LENDS).unwrap_or_default(); + solstice_asset::join::fill(scene, &borrows, &lends, joined) + .map_err(|error| error.to_string())?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn file(name: &str, text: &str) -> GameFile { + GameFile { + name: name.to_owned(), + text: text.to_owned(), + } + } + + #[test] + fn the_shared_files_code_takes_the_place_of_a_scenes_copy_of_it() { + let mut scene = vec![ + file(GAME_FILE, "actor cove/player.actor 1 2 3 0\n"), + file("cove/player.star", "old\n"), + ]; + let shared = [ + file(GAME_FILE, "actor cove/player.actor 0 0 0 0\n"), + file("cove/player.star", "new\n"), + file("cove/play.input", "sprint gamepad l3\n"), + file("circuit.track", "elsewhere\n"), + ]; + share_code(&mut scene, &shared); + let text = |name: &str| { + let found = scene.iter().find(|file| file.name == name); + found.map(|file| file.text.as_str()) + }; + // Its script is the shared one, and the actions it had none of are there. + assert_eq!(text("cove/player.star"), Some("new\n")); + assert_eq!(text("cove/play.input"), Some("sprint gamepad l3\n")); + // Where its actors stand is its own, and it is given nothing else of the other's. + assert_eq!(text(GAME_FILE), Some("actor cove/player.actor 1 2 3 0\n")); + assert_eq!(text("circuit.track"), None); + } + + #[test] + fn a_shared_actor_is_given_the_other_files_instances_where_the_scene_puts_it() { + use glam::Vec3; + use solstice_asset::Instance; + let at = |x: f32| Instance { + mesh: 0, + material: 0, + transform: Mat4::from_translation(Vec3::new(x, 0.0, 0.0)), + }; + // A scene of two instances, joined with a shared file whose car is its second and + // third: they are now the scene's fourth and fifth. + let mut scene = PagedScene { + instances: vec![at(0.0), at(0.0), at(0.0), at(1.0), at(2.0)], + gameplay: vec![file( + GAME_FILE, + "input keys.input\nactor car.actor 10 0 5 0 shared\n", + )], + ..Default::default() + }; + assert!(wanted(&scene.gameplay)); + let shared = [file(GAME_FILE, "actor car.actor 1 0 0 0 instances=1+2\n")]; + let joined = Joined { + instances: 2, + ..Default::default() + }; + adopt(&mut scene, &shared, joined).expect("the car is in the shared file"); + let game = &scene.gameplay[0].text; + assert!(game.contains("instances=3+2"), "{game}"); + assert!(!wanted(&scene.gameplay), "{game}"); + // Baked at x = 1 and put at x = 10, z = 5: each of its instances has moved as far. + let places: Vec = scene.instances[3..] + .iter() + .map(|instance| instance.transform.w_axis.truncate()) + .collect(); + assert_eq!( + places, + [Vec3::new(10.0, 0.0, 5.0), Vec3::new(11.0, 0.0, 5.0)] + ); + // An actor the shared file has none of is said, and not drawn from nowhere. + scene.gameplay[0].text = "actor boat.actor 0 0 0 0 shared\n".to_owned(); + assert!(adopt(&mut scene, &shared, joined).is_err()); + } +} diff --git a/crates/solstice-asset/src/join.rs b/crates/solstice-asset/src/join.rs new file mode 100644 index 0000000..2f3abe1 --- /dev/null +++ b/crates/solstice-asset/src/join.rs @@ -0,0 +1,426 @@ +//! Joins two scenes into one: a map, and what every map shares. +//! +//! A game's maps have things in common that are no part of any of them: the truck, what its +//! driver carries. Baked into every map, they are in every map's file. Kept in a file of their +//! own instead, they are read once beside whichever map is being played, and the two are joined +//! here into one scene, which is drawn as any scene is. +//! +//! Joining is renumbering. A scene's tables point into one another by index: an instance at +//! its mesh and its material, a mesh at its nodes, a node at its children or its clusters, a +//! set of clusters at its page. The second scene's tables go after the first's, and everything +//! in them that is an index has added to it how long the first's table was. The first scene's +//! own numbers do not change, so what its gameplay files say of it stays true; [`Joined`] says +//! what was added to the second's, for whoever reads the second's. +//! +//! Pages are the one thing that cannot simply follow. A scene's pinned pages, which are always +//! loaded, are its first; the rest run from coarse to fine, each needing only pages before it. +//! So the joined scene's pages are the first's pinned, the second's pinned, and then the rest +//! of both dealt together, coarse to fine: every page still follows what it needs, and the +//! coarse pages of both, which are wanted first, come first. Sets are kept in the order of +//! their pages, and move with them. +//! +//! A scene that is read from its file as it is drawn asks for ranges of bytes of the file. Of +//! a joined scene there are two files, so the second's are numbered on from the end of the +//! first's: a range at or past `second_at` is that far into the second file. +//! +//! **What the first leaves out.** Maps have more in common than their truck: the same trees, +//! the same grass and stone, the same textures under them. A map's own instances are of +//! these, so they cannot simply be the second scene's. Instead the second scene *lends*: it +//! carries a list ([`LENDS`]) of every mesh and texture it has, each with a key, which is a +//! hash of what it is. A map baked beside it leaves out of its own file whatever has a key on +//! that list, and carries a list of what it left ([`BORROWS`]): which of its meshes is an +//! empty place for which key, and which of its materials wants the texture of which key. Once +//! the two are joined, [`fill`] puts the lender's mesh in each empty place and gives each such +//! material the lender's layer. The map's instances and materials keep their own numbers, and +//! are of the lender's geometry and textures. +use crate::paged::{LoadedScene, PagedScene}; +use crate::scene::Material; +use crate::skeleton::NO_POSE; + +/// What was added to each of the second scene's numbers when it was joined to the first. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Joined { + pub instances: u32, + pub meshes: u32, + pub materials: u32, + pub poses: u32, + /// And to its texture layers. + pub layers: u32, +} + +/// The gameplay file in which a scene says what it lends: a line each, `mesh INDEX KEY` for +/// one of its meshes and `texture LAYER KEY` for one of its texture layers. +pub const LENDS: &str = "shared.lends"; +/// The gameplay file in which a scene says what it left out for a lender to fill: a line each, +/// `mesh INDEX KEY` for a mesh of its own that is an empty place, and `texture MATERIAL KEY` +/// for a material of its own that wants the texture. +pub const BORROWS: &str = "shared.borrows"; + +/// What is lent or borrowed, a line of a [`LENDS`] or [`BORROWS`] file each. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Lent { + Mesh, + Texture, +} + +impl Lent { + pub fn word(self) -> &'static str { + match self { + Self::Mesh => "mesh", + Self::Texture => "texture", + } + } +} + +/// The lines of a [`LENDS`] or [`BORROWS`] file: what, its number, and its key. Lines that +/// say nothing, or anything else, are passed over. +pub fn lent(text: &str) -> impl Iterator { + text.lines().filter_map(|line| { + let mut words = line.split_whitespace(); + let what = match words.next()? { + "mesh" => Lent::Mesh, + "texture" => Lent::Texture, + _ => return None, + }; + Some((what, words.next()?.parse().ok()?, words.next()?)) + }) +} + +/// Fills what a scene left out for its lender, once the lender has been joined onto it: +/// `borrows` is the scene's own list, `lends` the lender's, and `joined` what the join added +/// to the lender's numbers. +pub fn fill( + scene: &mut PagedScene, + borrows: &str, + lends: &str, + joined: Joined, +) -> Result<(), JoinError> { + let there: std::collections::HashMap<(Lent, &str), u32> = lent(lends) + .map(|(what, index, key)| ((what, key), index)) + .collect(); + let stale = || { + JoinError( + "the first was baked beside another file of what is shared than this one: bake both again, or fetch both" + .to_owned(), + ) + }; + for (what, index, key) in lent(borrows) { + let theirs = *there.get(&(what, key)).ok_or_else(stale)?; + match what { + Lent::Mesh => { + let mesh = *scene + .meshes + .get((joined.meshes + theirs) as usize) + .ok_or_else(stale)?; + *scene.meshes.get_mut(index as usize).ok_or_else(stale)? = mesh; + } + Lent::Texture => { + if (joined.layers + theirs) as usize >= scene.base_textures.len() { + return Err(stale()); + } + scene + .materials + .get_mut(index as usize) + .ok_or_else(stale)? + .texture_layer = (joined.layers + theirs) as i32; + } + } + } + Ok(()) +} + +/// Why two scenes could not be joined. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct JoinError(pub String); + +impl std::fmt::Display for JoinError { + fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(out, "the scenes cannot be joined: {}", self.0) + } +} + +impl std::error::Error for JoinError {} + +fn refuse(why: &str) -> Result { + Err(JoinError(why.to_owned())) +} + +/// Joins `second` onto `first`, table by table. `second_at` is where the second's file begins +/// in the numbering of both files' bytes: the length of the first's file. Returns what was added +/// to the second's numbers. +pub fn join( + first: &mut PagedScene, + second: PagedScene, + second_at: u64, +) -> Result { + join_pages(first, second, second_at).map(|(joined, _)| joined) +} + +/// As [`join`], and says as well where each page that is not pinned came from, in the order +/// they now are: whether from the second scene, and which of its own it was. +fn join_pages( + first: &mut PagedScene, + mut second: PagedScene, + second_at: u64, +) -> Result<(Joined, Vec<(bool, usize)>), JoinError> { + if first.external.is_some() || second.external.is_some() { + return refuse("one of them is split up for a browser"); + } + let textured = |scene: &PagedScene| !scene.base_textures.is_empty(); + if textured(first) && textured(&second) { + if first.texture_size != second.texture_size { + return refuse("their textures are not the same size"); + } + if first.texture_encoding != second.texture_encoding { + return refuse("their textures are not stored the same way"); + } + } + let glows = |scene: &PagedScene| !scene.glow.layers.is_empty(); + if glows(first) && glows(&second) && first.glow.edge != second.glow.edge { + return refuse("their glow maps are not the same size"); + } + if !second.cards.cards.is_empty() { + return refuse("the second has glowing cards, which are not joined yet"); + } + // What is shared is what moves, with colliders of its own: a table that says nothing + // of it collides is as good as none. + let collides = second.collision.as_ref().is_some_and(|collision| { + collision.heightfield.is_some() + || collision + .instance_shapes + .iter() + .any(|shape| *shape != crate::collision::NO_SHAPE) + }); + if collides { + return refuse("the second has collision shapes, which are not joined yet"); + } + + let added = |count: usize| count as u32; + let (clusters, nodes, generated) = ( + added(first.clusters.len()), + added(first.nodes.len()), + added(first.generated.len()), + ); + let joined = Joined { + instances: added(first.instances.len()), + meshes: added(first.meshes.len()), + materials: added(first.materials.len()), + poses: added(first.poses.len()), + layers: added(first.base_textures.len()), + }; + let (layers, glow_layers, skeletons, bones) = ( + first.base_textures.len() as i32, + added(first.glow.layers.len()), + added(first.skeletons.len()), + first.cluster_bones.len() as i32, + ); + // Where the second's bytes are, measured as the first's are, from the first's data area. + let moved = (second_at + second.data_offset) as i128 - first.data_offset as i128; + let rebase = |offset: u64| (offset as i128 + moved) as u64; + + // ---- Clusters, and the trees over them. + first.clusters.append(&mut second.clusters); + first + .nodes + .extend(second.nodes.iter().map(|node| crate::PackedNode { + first: node.first + if node.is_leaf != 0 { clusters } else { nodes }, + ..*node + })); + first + .generated + .extend(second.generated.iter().map(|cluster| cluster + clusters)); + first + .meshes + .extend(second.meshes.iter().map(|mesh| crate::paged::MeshInfo { + root_node: mesh.root_node.map(|node| node + nodes), + bone_lists: mesh.bone_lists.map(|list| list + bones - clusters as i32), + ..*mesh + })); + first.cluster_bones.append(&mut second.cluster_bones); + + // ---- Pages, and the sets in them: the pinned of both, then the rest of both, coarse + // to fine. A page holds sets of one round of coarsening, and the rounds count down as + // the detail gets finer: the two scenes' pages are dealt together by their rounds, each + // scene's in the order they were in, so that a page still follows every page it needs, + // and what is read first of either is what is seen from furthest off. + let (pinned_a, pinned_b) = (first.pinned_pages as usize, second.pinned_pages as usize); + let round = |scene: &PagedScene, page: usize| { + let info = &scene.pages[page]; + scene + .sets + .get(info.first_set as usize) + .map_or(0, |set| set.round) + }; + let mut order: Vec<(bool, usize)> = (0..pinned_a).map(|page| (false, page)).collect(); + order.extend((0..pinned_b).map(|page| (true, page))); + let (mut next_a, mut next_b) = (pinned_a, pinned_b); + while next_a < first.pages.len() || next_b < second.pages.len() { + let takes_b = next_a >= first.pages.len() + || (next_b < second.pages.len() && round(&second, next_b) > round(first, next_a)); + if takes_b { + order.push((true, next_b)); + next_b += 1; + } else { + order.push((false, next_a)); + next_a += 1; + } + } + let mut pages = Vec::with_capacity(order.len()); + let mut sets = Vec::with_capacity(first.sets.len() + second.sets.len()); + for (new, &(of_second, old)) in order.iter().enumerate() { + let scene: &PagedScene = if of_second { &second } else { first }; + let info = scene.pages[old]; + let first_set = sets.len() as u32; + for set in &scene.sets[info.first_set as usize..(info.first_set + info.set_count) as usize] + { + sets.push(if of_second { + crate::paged::ClusterSet { + first_cluster: set.first_cluster + clusters, + first_generated: set.first_generated + generated, + leaf_node: set.leaf_node + nodes, + page: new as u32, + ..*set + } + } else { + crate::paged::ClusterSet { + page: new as u32, + ..*set + } + }); + } + pages.push(crate::paged::PageInfo { + first_set, + // A pinned page is in the manifest, and has no place in a file. + offset: if of_second && old >= pinned_b { + rebase(info.offset) + } else { + info.offset + }, + ..info + }); + } + // A leaf of a mesh's tree says which page its clusters are in, so that a view that + // wants them and finds them not yet read can ask for the page: by its new number. + for set in &sets { + let node = &mut first.nodes[set.leaf_node as usize]; + node.is_leaf = (node.is_leaf & !crate::gpu::NODE_PAGE_MASK) | set.page; + } + first.sets = sets; + first.pages = pages; + first.pinned_pages = (pinned_a + pinned_b) as u32; + first.pinned_data.append(&mut second.pinned_data); + // Which pages that are not pinned came from where, in their new order. + let rest: Vec<(bool, usize)> = order[pinned_a + pinned_b..] + .iter() + .map(|&(of_second, old)| (of_second, old - if of_second { pinned_b } else { pinned_a })) + .collect(); + + // ---- What is drawn with them. + first + .materials + .extend(second.materials.iter().map(|material| { + let mut material = *material; + if material.texture_layer >= 0 { + material.texture_layer += layers; + } + if let Some(layer) = material.glow_layer() { + let below = material.flags & ((1 << Material::GLOW_SHIFT) - 1); + material.flags = below | ((layer + glow_layers + 1) << Material::GLOW_SHIFT); + } + material + })); + if !textured(first) { + first.texture_size = second.texture_size; + first.texture_encoding = second.texture_encoding; + } + first.base_textures.append(&mut second.base_textures); + first.upper_mip_offsets.extend( + second + .upper_mip_offsets + .iter() + .map(|offset| rebase(*offset)), + ); + if !glows(first) { + first.glow.edge = second.glow.edge; + } + first.glow.layers.append(&mut second.glow.layers); + + // ---- Instances, and the bones of those that have them. + let count_b = second.instances.len(); + if !first.instance_poses.is_empty() || !second.instance_poses.is_empty() { + first + .instance_poses + .resize(joined.instances as usize, NO_POSE); + second.instance_poses.resize(count_b, NO_POSE); + first + .instance_poses + .extend(second.instance_poses.iter().map(|pose| match *pose { + NO_POSE => NO_POSE, + pose => pose + joined.poses, + })); + } + first + .instances + .extend(second.instances.iter().map(|instance| crate::Instance { + mesh: instance.mesh + joined.meshes, + material: instance.material + joined.materials, + ..*instance + })); + first + .poses + .extend(second.poses.iter().map(|skeleton| skeleton + skeletons)); + first.skeletons.append(&mut second.skeletons); + first.clips.extend(second.clips.drain(..).map(|mut clip| { + clip.skeleton += skeletons; + clip + })); + first + .sources + .extend(second.sources.drain(..).map(|mut source| { + source.instances = + source.instances.start + joined.instances..source.instances.end + joined.instances; + source + })); + // Nothing of the second's collides: it is what moves, and has colliders of its own. + if let Some(collision) = &mut first.collision { + collision + .instance_shapes + .resize(first.instances.len(), crate::collision::NO_SHAPE); + } + first.lights.append(&mut second.lights); + first.hierarchy_depth = first.hierarchy_depth.max(second.hierarchy_depth); + first.source_triangles += second.source_triangles; + first.unique_triangles += second.unique_triangles; + Ok((joined, rest)) +} + +impl LoadedScene { + /// Joins a scene that is all in memory onto this one, which is too. See [`join`]. + pub fn join(&mut self, mut second: LoadedScene) -> Result { + let mut theirs: Vec>> = std::mem::take(&mut second.pages) + .into_iter() + .map(Some) + .collect(); + let upper = std::mem::take(&mut second.upper_textures); + let (joined, rest) = join_pages(&mut self.scene, second.scene, 0)?; + // The pages that are not pinned are kept in the order they now have. + let mut mine: Vec>> = std::mem::take(&mut self.pages) + .into_iter() + .map(Some) + .collect(); + self.pages = rest + .into_iter() + .map(|(of_second, old)| { + let from = if of_second { &mut theirs } else { &mut mine }; + from[old].take().expect("each page is placed once") + }) + .collect(); + self.upper_textures.extend(upper); + if let Some(collision) = &mut self.collision { + collision + .instance_shapes + .resize(self.scene.instances.len(), crate::collision::NO_SHAPE); + } + Ok(joined) + } +} diff --git a/crates/solstice-asset/src/lib.rs b/crates/solstice-asset/src/lib.rs index ce60c5f..1457412 100644 --- a/crates/solstice-asset/src/lib.rs +++ b/crates/solstice-asset/src/lib.rs @@ -8,6 +8,8 @@ pub mod collision; pub mod file; pub mod gpu; +pub mod join; +pub mod pack; pub mod paged; pub mod scene; pub mod skeleton; diff --git a/crates/solstice-asset/src/pack.rs b/crates/solstice-asset/src/pack.rs new file mode 100644 index 0000000..ad753bf --- /dev/null +++ b/crates/solstice-asset/src/pack.rs @@ -0,0 +1,114 @@ +//! A pack: several things in one file, each of which can be read without the rest. +//! +//! A truck built of pieces is one (`bake --kit`, `apps/bake/src/kit.rs`): each of its pieces +//! is a small scene of its own, and with them are the texts that say what the truck is. The +//! game reads the list of what is in the pack, and then only the pieces that are fitted to +//! the truck: what is not on it is never read. +//! +//! The file is eight bytes that say what it is, the length of its list in four more, the +//! list, and then each thing's bytes, one after another in the list's order. The list is +//! text, a line a thing: `KIND NAME LENGTH`. + +use std::io::{self, Read, Seek, SeekFrom}; + +/// What a pack's file begins with. +pub const MAGIC: &[u8; 8] = b"SOLPACK1"; + +/// One thing in a pack: what kind of thing it is, what it is called, and where its bytes +/// are in the file. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Entry { + pub kind: String, + pub name: String, + pub start: u64, + pub length: u64, +} + +/// A pack of these things, each its kind, its name and its bytes, as the bytes of a file. +/// A kind and a name are single words. +pub fn write(things: &[(&str, &str, &[u8])]) -> Vec { + let list: String = things + .iter() + .map(|(kind, name, bytes)| format!("{kind} {name} {}\n", bytes.len())) + .collect(); + let mut file = Vec::from(*MAGIC); + file.extend((list.len() as u32).to_le_bytes()); + file.extend(list.as_bytes()); + for (_, _, bytes) in things { + file.extend(*bytes); + } + file +} + +fn wrong(what: &str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, what.to_owned()) +} + +/// Reads the list of what is in a pack, from its beginning. +pub fn read_list(file: &mut (impl Read + Seek)) -> io::Result> { + file.seek(SeekFrom::Start(0))?; + let mut head = [0; 12]; + file.read_exact(&mut head)?; + if head[..8] != MAGIC[..] { + return Err(wrong("it is not a pack")); + } + let length = u32::from_le_bytes([head[8], head[9], head[10], head[11]]); + let mut list = vec![0; length as usize]; + file.read_exact(&mut list)?; + let list = String::from_utf8(list).map_err(|_| wrong("its list is not text"))?; + let mut start = 12 + u64::from(length); + let mut entries = Vec::new(); + for line in list.lines() { + let words: Vec<&str> = line.split_whitespace().collect(); + let [kind, name, length] = words[..] else { + return Err(wrong("a line of its list is not `KIND NAME LENGTH`")); + }; + let length: u64 = length + .parse() + .map_err(|_| wrong("a length in its list is not a number"))?; + entries.push(Entry { + kind: kind.to_owned(), + name: name.to_owned(), + start, + length, + }); + start += length; + } + Ok(entries) +} + +/// Reads one thing out of a pack. +pub fn read(file: &mut (impl Read + Seek), entry: &Entry) -> io::Result> { + file.seek(SeekFrom::Start(entry.start))?; + let mut bytes = vec![0; entry.length as usize]; + file.read_exact(&mut bytes)?; + Ok(bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn each_thing_in_a_pack_is_read_alone() { + let file = write(&[ + ("text", "truck.kit", b"base cab\n"), + ("piece", "cab", &[1, 2, 3, 4, 5]), + ("piece", "bonnet", &[]), + ("piece", "door_FL", &[9, 8]), + ]); + let mut file = Cursor::new(file); + let list = read_list(&mut file).unwrap(); + let names: Vec<&str> = list.iter().map(|entry| entry.name.as_str()).collect(); + assert_eq!(names, ["truck.kit", "cab", "bonnet", "door_FL"]); + assert_eq!(list[0].kind, "text"); + // The last, without the others; and the first after it. + assert_eq!(read(&mut file, &list[3]).unwrap(), [9, 8]); + assert_eq!(read(&mut file, &list[0]).unwrap(), b"base cab\n"); + assert_eq!(read(&mut file, &list[2]).unwrap(), [0u8; 0]); + assert_eq!(read(&mut file, &list[1]).unwrap(), [1, 2, 3, 4, 5]); + // What is not a pack is refused. + assert!(read_list(&mut Cursor::new(b"not a pack at all".to_vec())).is_err()); + } +} diff --git a/crates/solstice-asset/src/scene.rs b/crates/solstice-asset/src/scene.rs index d52b62b..5ab6060 100644 --- a/crates/solstice-asset/src/scene.rs +++ b/crates/solstice-asset/src/scene.rs @@ -94,6 +94,21 @@ impl Material { /// texture layers come right after this one's. The mesh's texture coordinates hold how much /// of the second and the third there is, and every texture is laid by the world's x and z. pub const BLENDS: u32 = 32; + /// The paint of something driven: the game can give it another colour, and it is what + /// rusts (`Coat` in `solstice-render`). An importer marks a material whose name begins + /// `paint`. + pub const PAINT: u32 = 64; + /// Inside something driven, out of the weather: its cab, its engine bay. It takes no + /// dust or mud. An importer marks a material whose name begins `inside`. + pub const INSIDE: u32 = 128; + /// Glass, seen through: of the pixels it covers it is drawn in a share, its colour's + /// alpha, and what is behind it shows in the rest, a different share each frame so that + /// the two blend (`vg/mask.wgsl`). An importer marks a material whose alpha is blended. + pub const GLASS: u32 = 256; + /// Mud: where ground blended of three kinds ([`Material::BLENDS`]) is this kind, it is + /// drawn as mud lies, wet at its heart and dried to a cracked crust at its rim + /// (`ground/ruts.wgsl`, `docs/ruts.md`). Older files' mud is drawn as any ground is. + pub const MUD: u32 = 512; /// `flags` above this bit hold one more than the material's layer in [`GlowMaps`], or zero /// for a material whose emissive colour is even all over. pub const GLOW_SHIFT: u32 = 16; diff --git a/crates/solstice-bake/Cargo.toml b/crates/solstice-bake/Cargo.toml index 169a0f5..5b03c2b 100644 --- a/crates/solstice-bake/Cargo.toml +++ b/crates/solstice-bake/Cargo.toml @@ -17,6 +17,8 @@ solstice-procgen.workspace = true glam.workspace = true rayon.workspace = true rustc-hash.workspace = true +bytemuck.workspace = true +sha2 = "0.10" [dev-dependencies] solstice-physics.workspace = true diff --git a/crates/solstice-bake/src/lend.rs b/crates/solstice-bake/src/lend.rs new file mode 100644 index 0000000..f6dc39d --- /dev/null +++ b/crates/solstice-bake/src/lend.rs @@ -0,0 +1,350 @@ +//! What a scene lends to others, and what one leaves out because another lends it. +//! +//! A game's maps are made of much the same things: the same trees, grass and stone, the same +//! textures under them. Baked into each, they are in every map's file. Instead one scene, the +//! one whose file every map is read with, *lends* them: it carries a list of every mesh and +//! texture it has, each with a key, which is a hash of what it is ([`lends`]). A map baked +//! beside that file leaves out whatever of its own has a key on the list ([`borrow`]): the +//! mesh becomes an empty place, the texture is dropped, and the map carries a list of what it +//! left. Read together, the two are joined and the places are filled +//! (`solstice_asset::join::fill`). +//! +//! Nothing has to be told which things are shared. Whatever the two scenes both have, bit for +//! bit, is left out, and whatever differs by anything is kept: a map can never be given the +//! wrong tree. So what is to be shared has to be made the same way in both, wherever it is +//! used. +//! +//! Keys are of a scene as it is built, before its textures are compressed: both the lender +//! and the borrower are hashed at that point. +use sha2::{Digest, Sha256}; +use solstice_asset::join::Lent; +use solstice_asset::{SceneAsset, TextureLayer, VirtualMesh}; +use std::collections::HashMap; +use std::fmt::Write as _; + +/// A key: the start of a SHA-256, in hex. Sixteen bytes of it are plenty to tell apart the +/// few hundred things a game has. +fn key(hash: Sha256) -> String { + hash.finalize()[..16] + .iter() + .fold(String::new(), |mut text, byte| { + let _ = write!(text, "{byte:02x}"); + text + }) +} + +/// A mesh's key: everything of it that is drawn, and how it is read. +fn mesh_key(mesh: &VirtualMesh) -> String { + let mut hash = Sha256::new(); + let mut part = |bytes: &[u8]| { + hash.update((bytes.len() as u64).to_le_bytes()); + hash.update(bytes); + }; + part(bytemuck::cast_slice(&mesh.clusters)); + part(bytemuck::cast_slice(&mesh.nodes)); + part(bytemuck::cast_slice(&mesh.vertices)); + part(bytemuck::cast_slice(&mesh.triangles)); + part(bytemuck::cast_slice(&mesh.sets)); + part(bytemuck::cast_slice(&mesh.generated)); + part(bytemuck::cast_slice(&mesh.cluster_bones)); + part(bytemuck::cast_slice(&[ + mesh.root_node, + mesh.hierarchy_depth, + ])); + part(bytemuck::cast_slice(&mesh.quant_origin.to_array())); + part(bytemuck::cast_slice(&[mesh.quant_step])); + part(bytemuck::cast_slice(&mesh.uv_origin)); + part(bytemuck::cast_slice(&mesh.uv_step)); + key(hash) +} + +/// A texture layer's key: every level of its three maps, at the size it is. +fn texture_key(layer: &TextureLayer, size: u32) -> String { + let mut hash = Sha256::new(); + hash.update(size.to_le_bytes()); + for maps in [&layer.color_mips, &layer.normal_mips, &layer.material_mips] { + hash.update((maps.len() as u64).to_le_bytes()); + for level in maps { + hash.update((level.len() as u64).to_le_bytes()); + hash.update(level); + } + } + key(hash) +} + +/// The list of what a scene lends, as the text of its `solstice_asset::join::LENDS` file: +/// every mesh that has anything in it, and every texture layer. +pub fn lends(scene: &SceneAsset) -> String { + let mut text = String::from( + "# What this scene lends to those read with it: what, its number here, its key.\n", + ); + for (index, mesh) in scene.meshes.iter().enumerate() { + if !mesh.clusters.is_empty() { + let _ = writeln!(text, "{} {index} {}", Lent::Mesh.word(), mesh_key(mesh)); + } + } + for (layer, texture) in scene.textures.iter().enumerate() { + let _ = writeln!( + text, + "{} {layer} {}", + Lent::Texture.word(), + texture_key(texture, scene.texture_size) + ); + } + text +} + +/// What a scene left out. +pub struct Borrowed { + /// The list of it, as the text of the scene's `solstice_asset::join::BORROWS` file. + pub text: String, + pub meshes: usize, + pub textures: usize, +} + +/// Leaves out of a scene whatever a lender's list has: `lends` is the text of that list. +/// Each such mesh is left an empty place, which keeps its number, and each such texture is +/// dropped, the layers after it moving down. Returns the list of what was left, for whoever +/// joins the two to fill. +pub fn borrow(scene: &mut SceneAsset, lends: &str) -> Borrowed { + let there: HashMap<(Lent, &str), u32> = solstice_asset::join::lent(lends) + .map(|(what, index, key)| ((what, key), index)) + .collect(); + let mut text = String::from( + "# What this scene leaves to the file it is read with: a mesh of its own that is an empty\n# place, or a material of its own that wants a texture, and the key of what goes there.\n", + ); + let mut meshes = 0; + for (index, mesh) in scene.meshes.iter_mut().enumerate() { + if mesh.clusters.is_empty() { + continue; + } + let key = mesh_key(mesh); + if there.contains_key(&(Lent::Mesh, key.as_str())) { + let _ = writeln!(text, "{} {index} {key}", Lent::Mesh.word()); + // What is said of the whole of it stays, for whoever counts or measures. + *mesh = VirtualMesh { + quant_origin: mesh.quant_origin, + quant_step: mesh.quant_step, + uv_origin: mesh.uv_origin, + uv_step: mesh.uv_step, + bounds_center: mesh.bounds_center, + bounds_radius: mesh.bounds_radius, + source_triangles: mesh.source_triangles, + ..Default::default() + }; + meshes += 1; + } + } + // Each layer's key if it is lent, and where it is among those that are kept if it is not. + let mut kept = Vec::new(); + let mut now: Vec> = Vec::new(); + for texture in std::mem::take(&mut scene.textures) { + let key = texture_key(&texture, scene.texture_size); + if there.contains_key(&(Lent::Texture, key.as_str())) { + now.push(Err(key)); + } else { + now.push(Ok(kept.len() as i32)); + kept.push(texture); + } + } + scene.textures = kept; + let textures = now.iter().filter(|layer| layer.is_err()).count(); + for (index, material) in scene.materials.iter_mut().enumerate() { + let Some(layer) = usize::try_from(material.texture_layer) + .ok() + .and_then(|layer| now.get(layer)) + else { + continue; + }; + match layer { + Ok(layer) => material.texture_layer = *layer, + Err(key) => { + let _ = writeln!(text, "{} {index} {key}", Lent::Texture.word()); + material.texture_layer = -1; + } + } + } + Borrowed { + text, + meshes, + textures, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use glam::{Mat4, Vec2, Vec3}; + use solstice_asset::join::{BORROWS, LENDS}; + use solstice_asset::{GameFile, Instance, Material}; + use solstice_builder::{build_virtual_mesh, paginate, BuildOptions, Mesh, Vertex}; + + /// A bumpy sheet, which `lift` makes one thing or another. + fn sheet(across: u32, lift: f32) -> VirtualMesh { + let mut mesh = Mesh::default(); + for row in 0..=across { + for column in 0..=across { + let (x, z) = (column as f32 * 0.2, row as f32 * 0.2); + mesh.vertices.push(Vertex { + position: Vec3::new(x, lift * (x * 3.1).sin() * (z * 2.3).cos(), z), + normal: Vec3::Y, + uv: Vec2::new(x, z), + }); + } + } + let wide = across + 1; + for row in 0..across { + for column in 0..across { + let at = row * wide + column; + mesh.indices + .extend([at, at + wide, at + 1, at + 1, at + wide, at + wide + 1]); + } + } + build_virtual_mesh(&mesh, &BuildOptions::default()) + } + + /// A texture of one shade, with all its levels. + fn texture(size: u32, shade: u8) -> TextureLayer { + let levels = |bytes: usize| -> Vec> { + (0..=size.trailing_zeros()) + .map(|level| vec![shade; ((size >> level) as usize).pow(2) * bytes]) + .collect() + }; + TextureLayer { + color_mips: levels(4), + normal_mips: levels(2), + material_mips: levels(2), + } + } + + #[test] + fn a_map_leaves_out_what_its_lender_has_and_is_whole_again_joined() { + const SIZE: u32 = 128; + let (tree, rock, land) = (sheet(60, 0.4), sheet(40, 0.2), sheet(80, 0.1)); + // The lender: a tree and a rock, and their textures, placed nowhere; and one thing + // of its own that is. + let mut lender = SceneAsset { + texture_size: SIZE, + meshes: vec![sheet(30, 0.7), tree.clone(), rock.clone()], + textures: vec![texture(SIZE, 10), texture(SIZE, 20), texture(SIZE, 30)], + materials: vec![Material { + texture_layer: 0, + ..Default::default() + }], + instances: vec![Instance { + mesh: 0, + material: 0, + transform: Mat4::IDENTITY, + }], + ..Default::default() + }; + lender.gameplay.push(GameFile { + name: LENDS.to_owned(), + text: lends(&lender), + }); + + // The map: its own land under its own texture, and the tree and the rock, each + // under a texture the lender has. + let whole = SceneAsset { + texture_size: SIZE, + meshes: vec![land, rock, tree], + textures: vec![texture(SIZE, 30), texture(SIZE, 77), texture(SIZE, 20)], + materials: (0..3) + .map(|layer| Material { + texture_layer: layer, + roughness: 0.1 * layer as f32, + ..Default::default() + }) + .collect(), + instances: (0..3) + .map(|index| Instance { + mesh: index, + material: index, + transform: Mat4::from_translation(Vec3::X * 40.0 * index as f32), + }) + .collect(), + ..Default::default() + }; + let mut map = whole.clone(); + let left = borrow(&mut map, &lender.gameplay[0].text); + assert_eq!((left.meshes, left.textures), (2, 2)); + assert!(!map.meshes[0].clusters.is_empty(), "its own land is kept"); + assert!(map.meshes[1].clusters.is_empty() && map.meshes[2].clusters.is_empty()); + assert_eq!(map.textures.len(), 1); + assert_eq!( + map.materials + .iter() + .map(|material| material.texture_layer) + .collect::>(), + [-1, 0, -1] + ); + map.gameplay.push(GameFile { + name: BORROWS.to_owned(), + text: left.text.clone(), + }); + + // Joined and filled, it draws what the whole map drew. + let mut joined = paginate(&map); + let lender = paginate(&lender); + let lent = lender.scene.gameplay[0].text.clone(); + let added = joined.join(lender).expect("they join"); + solstice_asset::join::fill(&mut joined.scene, &left.text, &lent, added) + .expect("it is filled"); + let alone = paginate(&whole); + for (index, (now, was)) in joined + .scene + .instances + .iter() + .zip(&alone.scene.instances) + .enumerate() + { + assert_eq!((now.mesh, now.material), (was.mesh, was.material)); + let (mine, theirs) = ( + joined.scene.meshes[now.mesh as usize], + alone.scene.meshes[was.mesh as usize], + ); + assert_eq!( + mine.root_node.is_some(), + theirs.root_node.is_some(), + "instance {index}" + ); + assert_eq!( + (mine.quant_origin, mine.quant_step), + (theirs.quant_origin, theirs.quant_step) + ); + // The same tree under each: as many clusters at its root's leaf, of the same size. + let root = |scene: &solstice_asset::PagedScene, + mesh: &solstice_asset::paged::MeshInfo| { + let node = scene.nodes[mesh.root_node.expect("it has geometry") as usize]; + (node.count, node.center, node.radius) + }; + assert_eq!( + root(&joined.scene, &mine), + root(&alone.scene, &theirs), + "instance {index}" + ); + // And the same texture: its coarsest level is the shade it was. + let shade = |scene: &solstice_asset::PagedScene, material: u32| { + let layer = scene.materials[material as usize].texture_layer; + scene.base_textures[layer as usize] + .color_mips + .last() + .expect("levels")[0] + }; + assert_eq!( + shade(&joined.scene, now.material), + shade(&alone.scene, was.material), + "instance {index}" + ); + } + assert_eq!( + joined.scene.materials[2].roughness, + alone.scene.materials[2].roughness + ); + + // A lender that has changed since is noticed, not drawn wrongly. + let other = lent.replace(lent.lines().nth(2).expect("a line"), "mesh 1 0000"); + let mut again = paginate(&map); + assert!(solstice_asset::join::fill(&mut again.scene, &left.text, &other, added).is_err()); + } +} diff --git a/crates/solstice-bake/src/lib.rs b/crates/solstice-bake/src/lib.rs index f7b5d6a..a9f231c 100644 --- a/crates/solstice-bake/src/lib.rs +++ b/crates/solstice-bake/src/lib.rs @@ -5,6 +5,7 @@ pub mod circuit; pub mod foliage; pub mod land; +pub mod lend; pub mod meshes; pub mod project; pub mod scene_file; diff --git a/crates/solstice-bake/src/project.rs b/crates/solstice-bake/src/project.rs index e9dada0..01d0301 100644 --- a/crates/solstice-bake/src/project.rs +++ b/crates/solstice-bake/src/project.rs @@ -466,6 +466,14 @@ fn to_entity(scene: &mut Scene, command: Command, id: String) -> Result { + return Err( + "a project has no map of its ground yet: bake the scene's text instead".into(), + ); + } + Command::Lends => { + return Err("a project lends nothing yet: bake the scene's text instead".into()); + } Command::Model { path, position, diff --git a/crates/solstice-bake/src/scene_file.rs b/crates/solstice-bake/src/scene_file.rs index 0bccf41..80f8c3f 100644 --- a/crates/solstice-bake/src/scene_file.rs +++ b/crates/solstice-bake/src/scene_file.rs @@ -20,6 +20,9 @@ //! input cove/play.input # the input actions, if not the built-in ones //! track circuit/circuit.track # a circuit: its centre line, and what lies beside it //! circuit 1900 # the land, road and planting round that track, this wide +//! surfaces cove/ground.surfaces # what the ground is made of, place by place, off a track +//! actor cove/car.actor 0 0 0 0 shared # an actor whose model is in the file read with this one +//! lends # this scene lends all it has to those read with it (`lend.rs`) //! land 10 6 # the terrain in bands: sand this far in, then dirt, then grass //! path 22 0 60 -30 3 # a dirt path: from x z, to x z, width //! yard -21 -21 21 21 # a dirt yard: opposite corners x z @@ -128,6 +131,11 @@ pub(crate) enum Command { Track(String), /// The land round the scene's track, this many metres across. Circuit(f32), + /// The map of what the ground is made of, place by place (`solstice_game::SurfaceMap`). + Surfaces(String), + /// This scene lends every mesh and texture it has to the scenes read with it + /// (`crate::lend`). + Lends, } pub(crate) fn parse_line(line: &str) -> Result, String> { @@ -337,6 +345,14 @@ pub(crate) fn parse_line(line: &str) -> Result, String> { expect(1)?; Command::Track(values[0].to_string()) } + "surfaces" => { + expect(1)?; + Command::Surfaces(values[0].to_string()) + } + "lends" => { + expect(0)?; + Command::Lends + } "circuit" => { expect(1)?; let size = number(0)?; @@ -622,7 +638,28 @@ struct Gameplay { /// For each actor with a mesh: which actor, which model, and which of its placements. meshes: Vec<(usize, PathBuf, Placed)>, /// Whether an actor has a camera already: only one can. - has_player: bool, + has_player: [bool; 2], + /// The actors whose meshes are kits: the pieces of each are listed for the game. + kits: Vec, +} + +/// Which of an actor's instances draw each named piece of its mesh, as text: a line a piece, +/// `NAME FIRST COUNT`, counted from the actor's first instance. A piece of several materials +/// is several instances, one after another. +fn pieces_text(names: &[String]) -> String { + let mut text = String::new(); + let mut first = 0; + while first < names.len() { + let count = names[first..] + .iter() + .take_while(|name| **name == names[first]) + .count(); + if !names[first].is_empty() { + text.push_str(&format!("{} {first} {count}\n", names[first])); + } + first += count; + } + text } impl Gameplay { @@ -655,13 +692,15 @@ impl Gameplay { return Err(format!("{} has no script, so no properties", line.file)); } if actor.camera.is_some() { - if self.has_player { + // One actor is played; or two, a car and whoever drives it, who gets out. + let car = usize::from(actor.vehicle.is_some()); + if self.has_player[car] { return Err(format!( - "{} has a camera, and another actor already does: only one can", + "{} has a camera, and another actor already does: only one can, or a car and its driver", line.file )); } - self.has_player = true; + self.has_player[car] = true; } for (name, value) in &line.settings { let property = actor @@ -697,7 +736,18 @@ impl Gameplay { solstice_game::VehicleSpec::parse(self.read(base, &name)?) .map_err(|e| format!("{name}: {e}"))?; } - let mesh = actor.mesh.as_ref().map(|mesh| { + if let Some(kit) = &actor.kit { + // The game reads it: here it is only brought along. + let name = resolve(&line.file, kit); + self.read(base, &name)?; + self.kits.push(self.game.actors.len()); + } + // Its model may be in the file every map shares, and not in this one. Baked whole, + // to be looked at on its own, it is in this one after all. + if std::env::var_os("SOLSTICE_WHOLE").is_some() { + line.shared = false; + } + let mesh = actor.mesh.as_ref().filter(|_| !line.shared).map(|mesh| { ( resolve(&line.file, &mesh.path), mesh.scale, @@ -730,12 +780,26 @@ impl Gameplay { Ok(()) } + /// The map of what the ground is made of, which each tyre reads the square it is on of: + /// for land that is not a circuit, whose track says what lies beside its road. + fn set_surfaces(&mut self, base: &Path, name: &str) -> Result<(), String> { + if self.game.surfaces.is_some() { + return Err("`surfaces` is given twice".to_owned()); + } + let name = resolve(GAME_FILE, name); + solstice_game::SurfaceMap::parse(self.read(base, &name)?) + .map_err(|e| format!("{name}: {e}"))?; + self.game.surfaces = Some(name); + Ok(()) + } + /// The scene's gameplay files, with the list of its actors first, or none if it has none. fn finish(mut self) -> Vec { if self.game.actors.is_empty() && self.game.blockers.is_empty() && self.game.input.is_none() && self.game.track.is_none() + && self.game.surfaces.is_none() { return Vec::new(); } @@ -892,6 +956,7 @@ pub(crate) fn build_commands( let mut land_plan = crate::land::Plan::default(); let mut water = None; let mut circuit = None; + let mut lends = false; // Whether there has been a circuit, and a line of land, to refuse the two together. let (mut has_land, mut has_circuit) = (false, false); // Grouped by file, keeping first-seen order, so that each model is imported only once. @@ -1087,7 +1152,9 @@ pub(crate) fn build_commands( Some(Command::Blocker(blocker)) => gameplay.game.blockers.push(blocker), Some(Command::Input(input)) => gameplay.set_input(base, &input).map_err(at)?, Some(Command::Track(track)) => gameplay.set_track(base, &track).map_err(at)?, + Some(Command::Surfaces(file)) => gameplay.set_surfaces(base, &file).map_err(at)?, Some(Command::Circuit(size)) => circuit = Some(size), + Some(Command::Lends) => lends = true, } } @@ -1134,6 +1201,8 @@ pub(crate) fn build_commands( placed.whole_owners.push(owner.clone()); } } + let names = imported.names.clone(); + let mut kit_pieces: Vec = Vec::new(); let ranges = append_model(&mut scene, imported, &models[model]) .map_err(|e| format!("{}: {e}", model.display()))?; for (_, graph_file) in animations.iter().filter(|(m, _)| m == model) { @@ -1163,6 +1232,18 @@ pub(crate) fn build_commands( Placed::Part(i) => whole_count + i, }; gameplay.game.actors[*actor].instances = Some(ranges[index].clone()); + // A kit's pieces are listed, for the game to show some and not others. + if gameplay.kits.contains(actor) && matches!(placed, Placed::Whole(_)) { + kit_pieces.push(GameFile { + name: solstice_game::actor::pieces_file(&gameplay.game.actors[*actor].file), + text: pieces_text(&names), + }); + } + } + for file in kit_pieces.drain(..) { + if !gameplay.files.iter().any(|f| f.name == file.name) { + gameplay.files.push(file); + } } let collide = collides.remove(model).unwrap_or_default(); scene.collide.resize(scene.instances.len(), Collide::Auto); @@ -1254,6 +1335,13 @@ pub(crate) fn build_commands( } } scene.sources.sort_by_key(|source| source.instances.start); + // A scene that lends says what it has, for those baked beside it to leave out. + if lends { + scene.gameplay.push(GameFile { + name: solstice_asset::join::LENDS.to_owned(), + text: crate::lend::lends(&scene), + }); + } Ok((scene, warnings)) } @@ -1756,6 +1844,69 @@ wood 0 0 40 9 assert!(error.contains(":3: `wood` with `circuit`"), "{error}"); } + #[test] + fn a_scene_names_the_map_of_its_ground_and_one_that_lends_lists_what_it_has() { + let (gltf, bin) = two_triangles(); + let folder = Folder::with(&[ + ( + "scene.txt", + b"model tri.gltf 0 0 0 0 1 +surfaces ground.surfaces +lends +", + ), + ("tri.gltf", &gltf), + ("tri.bin", &bin), + // Four squares of mud and four of rock. + ( + "ground.surfaces", + b"surfaces -2 -1 1 4 2 +4g +4j +", + ), + ]); + let (scene, _) = build(&folder.0.join("scene.txt"), None).unwrap(); + let file = |name: &str| { + let found = scene.gameplay.iter().find(|file| file.name == name); + found.map(|file| file.text.as_str()) + }; + // The game is told of the map, which is brought along as it was written. + let game = SceneGame::parse(file(GAME_FILE).expect("the scene has a game")).unwrap(); + assert_eq!(game.surfaces.as_deref(), Some("ground.surfaces")); + let map = solstice_game::SurfaceMap::parse(file("ground.surfaces").unwrap()).unwrap(); + let at = |z: f32| map.at(Vec3::new(0.0, 0.0, z)); + assert_eq!( + (at(-0.5), at(0.5)), + (solstice_game::Surface::Mud, solstice_game::Surface::Rock) + ); + // And it lists every mesh it has, each with its key, for scenes baked beside it. + let lends = file(solstice_asset::join::LENDS).expect("it lends"); + let meshes = lends + .lines() + .filter(|line| line.starts_with("mesh ")) + .count(); + assert_eq!(meshes, scene.meshes.len()); + assert!(meshes > 0); + + // A map that cannot be read is found while baking, with its line. + let folder = Folder::with(&[ + ( + "scene.txt", + b"surfaces ground.surfaces +", + ), + ( + "ground.surfaces", + b"4g +", + ), + ]); + let error = build(&folder.0.join("scene.txt"), None).unwrap_err(); + assert!(error.contains("ground.surfaces"), "{error}"); + assert!(error.contains("expected `surfaces"), "{error}"); + } + #[test] fn a_scene_without_actors_has_no_gameplay() { let (gltf, bin) = two_triangles(); diff --git a/crates/solstice-builder/src/dag.rs b/crates/solstice-builder/src/dag.rs index a11432c..faf3c25 100644 --- a/crates/solstice-builder/src/dag.rs +++ b/crates/solstice-builder/src/dag.rs @@ -30,6 +30,11 @@ pub struct BuildOptions { pub min_reduction: f32, /// Fraction of triangles a group tries to keep per level. pub target_ratio: f32, + /// Leaves the mesh as its finest clusters alone, with nothing coarser made from them: all + /// of it is drawn however far off it is. For a small mesh whose points are to be written + /// over as it is drawn (a thing made as the game is played), which anything simplified + /// from them would not follow. + pub flat: bool, } impl Default for BuildOptions { @@ -39,6 +44,7 @@ impl Default for BuildOptions { max_cluster_vertices: MAX_CLUSTER_VERTICES, min_reduction: 0.85, target_ratio: 0.5, + flat: false, } } } @@ -141,7 +147,7 @@ fn build(mesh: &Mesh, skins: Option<&[PackedSkin]>, options: &BuildOptions) -> V let mut active: Vec = (0..clusters.len() as u32).collect(); let mut level = 0; - while active.len() > 1 { + while active.len() > 1 && !options.flat { level += 1; active = build_level( &mut welded, diff --git a/crates/solstice-builder/tests/join.rs b/crates/solstice-builder/tests/join.rs new file mode 100644 index 0000000..e6dbf60 --- /dev/null +++ b/crates/solstice-builder/tests/join.rs @@ -0,0 +1,165 @@ +//! Two scenes joined are one sound scene: every index in it lands inside its table, pages +//! still follow what they need, and nothing of either is lost. +use glam::{Mat4, Vec2, Vec3}; +use solstice_asset::{Instance, Material, SceneAsset}; +use solstice_builder::{build_virtual_mesh, paginate, BuildOptions, Mesh, Vertex}; + +/// A bumpy sheet `across` squares on a side: enough triangles for several rounds of detail. +fn sheet(across: u32, lift: f32) -> Mesh { + let mut mesh = Mesh::default(); + for row in 0..=across { + for column in 0..=across { + let (x, z) = (column as f32 * 0.2, row as f32 * 0.2); + mesh.vertices.push(Vertex { + position: Vec3::new(x, lift * (x * 3.1).sin() * (z * 2.3).cos(), z), + normal: Vec3::Y, + uv: Vec2::new(x, z), + }); + } + } + let wide = across + 1; + for row in 0..across { + for column in 0..across { + let at = row * wide + column; + mesh.indices + .extend([at, at + wide, at + 1, at + 1, at + wide, at + wide + 1]); + } + } + mesh +} + +fn scene(sheets: &[(u32, f32)], copies: usize) -> SceneAsset { + let mut scene = SceneAsset::default(); + for (index, &(across, lift)) in sheets.iter().enumerate() { + scene.meshes.push(build_virtual_mesh( + &sheet(across, lift), + &BuildOptions::default(), + )); + scene.materials.push(Material::default()); + for copy in 0..copies { + scene.instances.push(Instance { + mesh: index as u32, + material: index as u32, + transform: Mat4::from_translation(Vec3::new( + copy as f32 * 30.0, + 0.0, + index as f32 * 30.0, + )), + }); + } + } + scene +} + +#[test] +fn two_scenes_joined_are_one_sound_scene() { + let map = scene(&[(90, 0.4), (40, 0.1)], 3); + let shared = scene(&[(70, 0.3)], 2); + let (mut joined, second) = (paginate(&map), paginate(&shared)); + let (first_alone, second_alone) = (joined.scene.clone(), second.scene.clone()); + let added = joined.join(second).expect("they join"); + let both = &joined.scene; + + // Nothing is lost, and the first scene's own numbers are as they were. + assert_eq!( + both.clusters.len(), + first_alone.clusters.len() + second_alone.clusters.len() + ); + assert_eq!( + both.nodes.len(), + first_alone.nodes.len() + second_alone.nodes.len() + ); + assert_eq!( + both.sets.len(), + first_alone.sets.len() + second_alone.sets.len() + ); + assert_eq!( + both.pages.len(), + first_alone.pages.len() + second_alone.pages.len() + ); + assert_eq!( + both.pinned_pages, + first_alone.pinned_pages + second_alone.pinned_pages + ); + assert_eq!(added.instances, 6); + assert_eq!((added.meshes, added.materials), (2, 2)); + for (now, was) in both.instances.iter().zip(&first_alone.instances) { + assert_eq!( + (now.mesh, now.material, now.transform), + (was.mesh, was.material, was.transform) + ); + } + assert_eq!(both.instances[6].mesh, 2); + assert_eq!( + both.source_triangles, + first_alone.source_triangles + second_alone.source_triangles + ); + assert_eq!( + joined.pages.len(), + both.pages.len() - both.pinned_pages as usize + ); + + // Every index lands in its table. + for instance in &both.instances { + assert!((instance.mesh as usize) < both.meshes.len()); + assert!((instance.material as usize) < both.materials.len()); + } + for mesh in &both.meshes { + assert!(mesh + .root_node + .is_some_and(|node| (node as usize) < both.nodes.len())); + } + for node in &both.nodes { + let table = if node.is_leaf != 0 { + both.clusters.len() + } else { + both.nodes.len() + }; + assert!((node.first + node.count) as usize <= table); + } + assert!(both + .generated + .iter() + .all(|&cluster| (cluster as usize) < both.clusters.len())); + // Sets are in the order of their pages, and each page's sets are the ones it says. + assert!(both + .sets + .windows(2) + .all(|pair| pair[0].page <= pair[1].page)); + for (page, info) in both.pages.iter().enumerate() { + let sets = &both.sets[info.first_set as usize..(info.first_set + info.set_count) as usize]; + assert!( + sets.iter().all(|set| set.page == page as u32), + "page {page}" + ); + } + for set in &both.sets { + assert!((set.first_cluster + set.cluster_count) as usize <= both.clusters.len()); + assert!((set.first_generated + set.generated_count) as usize <= both.generated.len()); + assert!((set.leaf_node as usize) < both.nodes.len()); + // The leaf says which page its clusters are in: a view asks for that page by it. + let leaf = both.nodes[set.leaf_node as usize].is_leaf; + assert_ne!(leaf & solstice_asset::gpu::NODE_LEAF, 0); + assert_eq!(leaf & solstice_asset::gpu::NODE_PAGE_MASK, set.page); + } + // A page needs only pages before it, as it did before the two were joined. + for (page, needs) in both.page_dependencies().iter().enumerate() { + assert!( + needs.iter().all(|&needed| (needed as usize) < page), + "page {page} needs {needs:?}" + ); + } + // The pinned pages' contents are where their sizes say, one after another. + let pinned: usize = both.pages[..both.pinned_pages as usize] + .iter() + .map(|page| page.raw_bytes()) + .sum(); + assert_eq!(both.pinned_data.len(), pinned); + // And each page that is not pinned is the size its entry says. + for (index, page) in joined.pages.iter().enumerate() { + assert_eq!( + page.len(), + both.pages[both.pinned_pages as usize + index].raw_bytes() + ); + } +} diff --git a/crates/solstice-game/src/actor.rs b/crates/solstice-game/src/actor.rs index 7117a07..ea64da4 100644 --- a/crates/solstice-game/src/actor.rs +++ b/crates/solstice-game/src/actor.rs @@ -162,6 +162,20 @@ pub struct ActorFile { pub animation: Option, /// Makes it a car: its `.vehicle` file, relative to the actor file. pub vehicle: Option, + /// It is carried by a car's driver: with them, at their feet and turned as they are, + /// while they are out of the car, and put away while they are in it. + pub carried: bool, + /// Its mesh is a kit: a bare thing and what can be fitted to it, each a named piece. + /// This file, relative to the actor file, says which pieces are which (`kit PATH`); the + /// bake writes beside it which instances draw each piece ([`pieces_file`]). + pub kit: Option, +} + +/// The name of the gameplay file that says which of an actor's instances draw each named +/// piece of its mesh: a line a piece, `NAME FIRST COUNT`, counted from the actor's first +/// instance. The bake writes it for an actor with a `kit`. +pub fn pieces_file(actor_file: &str) -> String { + format!("{actor_file}.pieces") } /// A car's numbers, and who changes gear. @@ -236,6 +250,8 @@ impl ActorFile { character: None, animation: None, vehicle: None, + carried: false, + kit: None, }; for (line, words) in lines(text) { let error = |message: String| FileError { line, message }; @@ -343,6 +359,15 @@ impl ActorFile { once(actor.collider.is_some())?; actor.collider = Some(parse_collider(values).map_err(error)?); } + "carried" => { + count(0..=0, "nothing after it")?; + actor.carried = true; + } + "kit" => { + count(1..=1, "PATH")?; + once(actor.kit.is_some())?; + actor.kit = Some(values[0].to_owned()); + } "character" => { count(2..=2, "RADIUS HEIGHT")?; once(actor.character.is_some())?; diff --git a/crates/solstice-game/src/drive.rs b/crates/solstice-game/src/drive.rs index 9070448..b02f096 100644 --- a/crates/solstice-game/src/drive.rs +++ b/crates/solstice-game/src/drive.rs @@ -103,11 +103,65 @@ pub fn asked(input: &Input) -> Asked { } } -/// How hard the car that drives itself corners and brakes, in metres a second squared: within -/// what a racing car on slicks does, with room to spare. -const SELF_CORNERING: f32 = 13.0; -const SELF_BRAKING: f32 = 12.0; -const SELF_TOP_SPEED: f32 = 80.0; +/// What is wrong with a car, as its driver feels it: what damage has done to how it drives. +/// Whoever keeps the car's damage says ([`crate::Play::set_handicap`]); a sound car has none. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Handicap { + /// How far its steering pulls to one side, as a share of full lock: above zero to the + /// right. A bent wheel or a buckled arm does this, and it is held against. + pub pull: f32, + /// The share of its engine's pull it still has, from 0 to 1: an engine that has lost + /// its cooling is nursed. + pub power: f32, +} + +impl Default for Handicap { + fn default() -> Self { + Self { + pull: 0.0, + power: 1.0, + } + } +} + +impl Handicap { + /// What the car is asked for, with this wrong with it. + pub fn apply(&self, mut asked: Asked) -> Asked { + asked.steer = (asked.steer + self.pull).clamp(-1.0, 1.0); + asked.throttle *= self.power.clamp(0.0, 1.0); + asked + } +} + +/// How hard a car that drives itself corners and brakes, in metres a second squared, and how +/// fast it will go, in metres a second. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pace { + pub cornering: f32, + pub braking: f32, + pub top_speed: f32, + /// How far ahead along the track it steers for, in metres: so far, and so much more for + /// each metre a second it is going. + pub looks: (f32, f32), +} + +impl Pace { + /// Round a circuit: within what a racing car on slicks does, with room to spare. + pub const RACING: Self = Self { + cornering: 13.0, + braking: 12.0, + top_speed: 80.0, + looks: (7.0, 0.55), + }; + /// Along a bush track: what loose clay lets a truck do, at a pace to see the country by. + pub const TOURING: Self = Self { + cornering: 2.4, + braking: 2.8, + top_speed: 11.0, + // A track a car's width wide is followed closely, or its bends are cut through trees. + looks: (3.6, 0.42), + }; +} /// What a car driving itself round a track asks for, for showing a circuit off and for trying /// one: it steers for the middle of the road a way ahead, further the faster it goes, and @@ -120,28 +174,50 @@ pub fn autopilot( forward: Vec3, speed: f32, hint: Option, + pace: &Pace, + caution: Option<&dyn Fn(Vec3) -> f32>, ) -> (Asked, usize) { let place = track.locate(position, hint); let flat = |v: Vec3| Vec3::new(v.x, 0.0, v.z); - let (target, _, _) = track.place(place.along + 7.0 + speed.abs() * 0.55); + let (target, _, _) = track.place(place.along + pace.looks.0 + speed.abs() * pace.looks.1); let to = flat(target - position).normalize_or_zero(); // Above zero when the target is to the right, which is the way steering above zero turns. let turn = -flat(forward).normalize_or_zero().cross(to).y; // How fast each stretch of road ahead can be taken, and so how fast the car may be going // now and still slow for it in the distance there is. - let mut limit = SELF_TOP_SPEED; + let mut limit = pace.top_speed; let mut ahead = 0.0_f32; while ahead < 260.0 { let at = |d: f32| flat(track.place(place.along + ahead + d).0); let (a, b, c) = (at(-6.0), at(0.0), at(6.0)); let bend = 2.0 * (b - a).cross(c - b).length() / ((b - a).length() * (c - b).length() * (c - a).length()).max(1.0e-6); - let through = (SELF_CORNERING / bend.max(1.0e-4)).sqrt(); + let through = (pace.cornering / bend.max(1.0e-4)).sqrt(); let room = (ahead - 10.0).max(0.0); - limit = limit.min((through * through + 2.0 * SELF_BRAKING * room).sqrt()); + limit = limit.min((through * through + 2.0 * pace.braking * room).sqrt()); ahead += 8.0; } + // And for what the ground ahead is: `caution` says how fast a place may be crossed, a ford + // or a bog at a crawl, and a track that drops away and comes back, as at a washout, is + // crossed at one too. + if let Some(caution) = caution { + let mut ahead = 0.0_f32; + while ahead <= 24.0 { + let at = |d: f32| track.place(place.along + ahead + d).0; + let (before, here, after) = (at(-3.0), at(0.0), at(3.0)); + let dip = (before.y + after.y - 2.0 * here.y).abs(); + let mut slow = caution(here); + if dip > 0.22 { + slow = slow.min(2.2); + } else if dip > 0.1 { + slow = slow.min(4.0); + } + let room = (ahead - 5.0).max(0.0); + limit = limit.min((slow * slow + 2.0 * pace.braking * room).sqrt()); + ahead += 3.0; + } + } let asked = Asked { throttle: ((limit - speed) * 0.6).clamp(0.0, 1.0), brake: ((speed - limit) * 0.35).clamp(0.0, 1.0), @@ -158,11 +234,23 @@ pub const FALLEN: f32 = 14.0; /// Puts a car back on the track: on the centre line nearest where it is, a little back, facing /// the way the lap runs, at rest. pub fn put_back(world: &mut World, entity: Entity, track: &Track) { + // On a lap, in the section of it that is being driven: at its start, if the nearest of + // the track is in another, so that a section is not got out of by being put back. + let section = world + .entities + .get::<&Lap>(entity) + .ok() + .filter(|lap| lap.current.is_some()) + .map(|lap| lap.section(track)); let Ok(mut transform) = world.entities.get::<&mut Transform>(entity) else { return; }; let place = track.locate(transform.translation, None); - let (centre, forward, left) = track.place(place.along - 8.0); + let along = match section { + Some((from, to)) if !(from..to).contains(&place.along) => from + 11.0, + _ => place.along, + }; + let (centre, forward, left) = track.place(along - 8.0); let up = forward.cross(left).normalize_or(Vec3::Y); // The car's -Z along the track, its +X to the track's right, and standing on its slope. transform.rotation = Quat::from_mat3(&glam::Mat3::from_cols(-left, up, -forward)).normalize(); @@ -177,6 +265,24 @@ pub fn put_back(world: &mut World, entity: Entity, track: &Track) { } } +/// Puts a car somewhere, facing a way (a yaw in degrees: zero looks along -z), at rest: where +/// it was when a game was last left. +pub fn put_at(world: &mut World, entity: Entity, position: Vec3, yaw_degrees: f32) { + let Ok(mut transform) = world.entities.get::<&mut Transform>(entity) else { + return; + }; + transform.rotation = Quat::from_rotation_y(yaw_degrees.to_radians()); + transform.translation = position + Vec3::Y * 0.08; + drop(transform); + if let Ok(mut car) = world.entities.get::<&mut Car>(entity) { + car.vehicle.settle(); + car.asked = Asked::default(); + } + if let Ok(mut lap) = world.entities.get::<&mut Lap>(entity) { + lap.interrupt(); + } +} + /// The views of a car the `camera` action steps through: from close behind it out to high /// above, then from on the car itself. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -231,6 +337,10 @@ pub struct Look { pub around: f32, /// Over it: at 1 the camera is tipped up high above the car, at -1 down low behind it. pub over: f32, + /// How far the mouse or the stick has swung the view round the car this frame, in radians, + /// above zero to the left, and how far it has tipped it up over the car. + pub orbit: f32, + pub orbit_up: f32, } /// How far round the car a stick held right over looks, in radians, and how far up and down @@ -254,6 +364,18 @@ pub struct Chase { around: f32, over: f32, started: bool, + /// Where the mouse or the stick has swung the view to, round the car and over it, in + /// radians: it stays there until it is swung again. + orbit: f32, + tilt: f32, + /// How far the camera is lifted to keep the land out of the way, in metres, eased. + lift: f32, + /// How much bigger than a racing car what it follows is: a truck is followed from further + /// back and higher. Zero stands for one. + pub reach: f32, + /// Where the driver's eyes are, and the front of the car, from its origin, if they are + /// not a racing car's: for the views from on the car. + pub eyes: Option<[Vec3; 2]>, } /// Where a camera is, and the way it looks. @@ -272,7 +394,17 @@ fn turn(from: f32, to: f32) -> f32 { impl Chase { /// The camera for a frame `seconds` long, for a car drawn at `car`, going at `speed` metres /// a second, with the player looking as `look` says. - pub fn frame(&mut self, car: Mat4, speed: f32, look: Look, seconds: f32) -> Shot { + /// + /// `land` gives the land's height under a place, if it is known: the camera is kept above + /// it, and lifted as far as it takes to see the car over a rise between them. + pub fn frame( + &mut self, + car: Mat4, + speed: f32, + look: Look, + seconds: f32, + land: Option<&dyn Fn(Vec3) -> Option>, + ) -> Shot { let (_, rotation, origin) = car.to_scale_rotation_translation(); let forward = rotation * Vec3::NEG_Z; let heading = (-forward.x).atan2(-forward.z); @@ -286,12 +418,22 @@ impl Chase { let follow = 1.0 - (-seconds / LOOK_EASE).exp(); self.around += (around - self.around) * follow; self.over += (over - self.over) * follow; + // The mouse and the stick swing the view freely: all the way round, and from low + // behind the car to high over it. It stays where it is put. + if look.orbit != 0.0 || look.orbit_up != 0.0 { + self.orbit = turn(0.0, self.orbit + look.orbit); + self.tilt = (self.tilt + look.orbit_up).clamp(-0.3, 1.05); + } + let reach = if self.reach > 0.0 { self.reach } else { 1.0 }; let Some((back, up, ease)) = self.view.following() else { self.started = false; + let eyes = self + .eyes + .unwrap_or([Vec3::new(0.0, 1.02, -0.45), Vec3::new(0.0, 0.52, -2.05)]); let eye = if self.view == CameraView::Bonnet { - Vec3::new(0.0, 1.02, -0.45) + eyes[0] } else { - Vec3::new(0.0, 0.52, -2.05) + eyes[1] }; // From on the car, the stick turns the driver's head: to the side, and no further. let head = self.around.clamp(-1.9, 1.9); @@ -312,15 +454,30 @@ impl Chase { self.yaw += turn(self.yaw, heading) * follow; self.height += (origin.y - self.height) * (1.0 - (-seconds / 0.09).exp()); // Looking to the right is from over the car's left shoulder. - let round = self.yaw + behind - self.around; + let round = self.yaw + behind - self.around + self.orbit; let away = Vec3::new(round.sin(), 0.0, round.cos()); + let (back, up) = (back * reach, up * reach); let back = back + (speed.abs() / 85.0).min(1.0) * 0.9; // Tipped up over the car, or down behind it: the camera's arm swings about the car. - let (sin, cos) = self.over.sin_cos(); + let (sin, cos) = (self.over + self.tilt).sin_cos(); let (back, up) = (back * cos - up * sin, (up * cos + back * sin).max(0.35)); - let position = Vec3::new(origin.x, self.height, origin.z) + away * back + Vec3::Y * up; + let mut position = Vec3::new(origin.x, self.height, origin.z) + away * back + Vec3::Y * up; // Looking at a point above the car and a little ahead of it. - let target = origin + Vec3::Y * 0.85 - away * 1.2; + let target = origin + Vec3::Y * (0.85 * reach) - away * 1.2; + // The land comes first: the camera is never under it, and where a rise stands + // between it and the car it climbs until it sees over. Up quickly, down slowly. + if let Some(land) = land { + let mut needed = 0.0_f32; + for (share, clear) in [(0.35, 0.25), (0.6, 0.3), (0.82, 0.4), (1.0, 0.7)] { + let at = target.lerp(position, share); + if let Some(ground) = land(at + Vec3::Y * 40.0) { + needed = needed.max((ground + clear - at.y) / share); + } + } + let pace = if needed > self.lift { 0.07 } else { 0.6 }; + self.lift += (needed - self.lift) * (1.0 - (-seconds / pace).exp()); + position.y += self.lift.max(0.0); + } let to = target - position; Shot { position, @@ -333,6 +490,18 @@ impl Chase { /// The player's car's instruments, for a viewer to show. #[derive(Clone, Debug, Default, PartialEq)] pub struct Hud { + /// Whether the driver has got out and is walking, and where they are: the car's + /// instruments are then as it was left. + pub afoot: bool, + pub walker: Vec3, + /// The way the driver faces, on foot: a yaw in radians (zero looks along -z). + pub walker_yaw: f32, + /// Where the car is and how it is turned: what is carried in it goes with it. + pub origin: Vec3, + pub rotation: Quat, + /// Its tray, if it has one, in its own space: its size inside, across, deep and long, + /// and the middle of its floor. + pub tray: Option<(Vec3, Vec3)>, pub telemetry: Telemetry, /// Where the engine's limiter is, in rpm. pub limit: f32, @@ -343,6 +512,41 @@ pub struct Hud { pub lap: Option, pub track: String, pub view: CameraView, + /// Each wheel, where it meets the ground: for what it throws up. + pub wheels: [HudWheel; 4], + /// The way the car points, and how fast it is going, in the world. + pub forward: Vec3, + pub velocity: Vec3, + /// Whether the car has a transfer case: only then is its setting shown. + pub four_wheel_drive: bool, + /// How far its nose is up, and how far it leans to its right, in degrees. + pub pitch: f32, + pub roll: f32, +} + +/// One wheel of the player's car, where it meets the ground. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct HudWheel { + /// Where its tyre touches, in the world. + pub at: Vec3, + /// Where its middle is, in the car's own space, as its suspension has it: at rest it is + /// its radius above the car's origin. + pub hub: Vec3, + pub on_ground: bool, + pub surface: solstice_physics::vehicle::Surface, + /// How fast its tread passes over the ground, in metres a second: above zero spinning + /// faster than it rolls, below it locked or dragging. + pub slip: f32, + /// How far it has sunk into the ground, in metres, and how hard it is pressed to it, as a + /// share of its load standing still. + pub sink: f32, + pub load: f32, + /// What its tyre carries from where it has been, from 0 to 1: water, then mud. + pub carried: (f32, f32), + /// Its tyre's radius, in metres, and what its tread makes of soft ground: times its + /// grip there, more for a tyre with deep lugs. + pub radius: f32, + pub tread: f32, } impl Hud { @@ -369,6 +573,27 @@ impl Hud { if t.stability_active { line.push_str(" ESC"); } + if self.four_wheel_drive { + line.push_str(" "); + line.push_str(t.drive.name()); + match (t.front_locked, t.rear_locked) { + (true, true) => line.push_str(" diffs locked"), + (false, true) => line.push_str(" rear diff locked"), + (true, false) => line.push_str(" front diff locked"), + (false, false) => {} + } + if t.descent_active { + line.push_str(" HDC"); + } + if t.aired_down { + line.push_str(" tyres down"); + } + // The inclinometer: a truck goes over somewhere past forty degrees of lean. + line.push_str(&format!( + " pitch {:+3.0}° roll {:+3.0}°", + self.pitch, self.roll + )); + } if let Some(lap) = &self.lap { let time = |seconds: Option| seconds.map_or("-:--.---".to_owned(), format_time); line.push_str(&format!( @@ -429,7 +654,7 @@ mod tests { Vec3::new(10.0, 2.0, 5.0), ); let ahead = Look::default(); - let shot = chase.frame(car, 0.0, ahead, 1.0 / 60.0); + let shot = chase.frame(car, 0.0, ahead, 1.0 / 60.0, None); assert!(shot.position.x < 10.0 - 4.0, "behind: {}", shot.position); assert!((shot.position.z - 5.0).abs() < 1.0e-3 && shot.position.y > 3.0); assert!( @@ -446,12 +671,12 @@ mod tests { back: true, ..Look::default() }; - let shot = chase.frame(car, 0.0, back, 1.0 / 60.0); + let shot = chase.frame(car, 0.0, back, 1.0 / 60.0, None); assert!(shot.position.x > 14.0); assert!((turn(shot.yaw, std::f32::consts::FRAC_PI_2)).abs() < 1.0e-3); // When the car turns, the camera comes round after it, not at once. let turned = Mat4::from_rotation_translation(Quat::IDENTITY, Vec3::new(10.0, 2.0, 5.0)); - let first = chase.frame(turned, 30.0, ahead, 1.0 / 60.0); + let first = chase.frame(turned, 30.0, ahead, 1.0 / 60.0, None); assert!( first.position.x < 9.0 && first.position.z < 6.5, "{}", @@ -459,7 +684,7 @@ mod tests { ); let mut shot = first; for _ in 0..120 { - shot = chase.frame(turned, 30.0, ahead, 1.0 / 60.0); + shot = chase.frame(turned, 30.0, ahead, 1.0 / 60.0, None); } assert!((shot.position.x - 10.0).abs() < 0.05 && shot.position.z > 9.0); assert!(shot.yaw.abs() < 0.01); @@ -475,7 +700,7 @@ mod tests { Quat::from_rotation_y(0.5) * Quat::from_rotation_x(0.1), Vec3::new(1.0, 2.0, 3.0), ); - let shot = chase.frame(car, 20.0, Look::default(), 1.0 / 60.0); + let shot = chase.frame(car, 20.0, Look::default(), 1.0 / 60.0, None); assert!((shot.yaw - 0.5).abs() < 1.0e-4 && (shot.pitch - 0.1).abs() < 1.0e-4); assert!(shot.position.distance(Vec3::new(1.0, 2.0, 3.0)) < 1.3); // The stick turns the driver's head: to the right is a lower yaw. @@ -485,7 +710,7 @@ mod tests { }; let mut turned = shot; for _ in 0..60 { - turned = chase.frame(car, 20.0, right, 1.0 / 60.0); + turned = chase.frame(car, 20.0, right, 1.0 / 60.0, None); } assert!( turned.yaw < 0.5 - 1.5 && turned.yaw > 0.5 - 2.0, @@ -506,7 +731,7 @@ mod tests { view, ..Chase::default() }; - let shot = chase.frame(car, 0.0, Look::default(), 1.0 / 60.0); + let shot = chase.frame(car, 0.0, Look::default(), 1.0 / 60.0, None); let away = shot.position.length(); assert!(away > last * 1.3, "{view:?} is {away} m away, after {last}"); // And looks down at the car from behind it. @@ -525,9 +750,9 @@ mod tests { let car = Mat4::IDENTITY; let mut chase = Chase::default(); let settle = |chase: &mut Chase, look: Look| { - let mut shot = chase.frame(car, 0.0, look, 1.0 / 60.0); + let mut shot = chase.frame(car, 0.0, look, 1.0 / 60.0, None); for _ in 0..90 { - shot = chase.frame(car, 0.0, look, 1.0 / 60.0); + shot = chase.frame(car, 0.0, look, 1.0 / 60.0, None); } shot }; @@ -571,6 +796,7 @@ mod tests { ..Look::default() }, 1.0 / 60.0, + None, ); assert!(first.position.distance(ahead.position) < 3.5); // Let go, and it comes back behind. @@ -595,6 +821,29 @@ mod tests { assert!(low.position.y < ahead.position.y && low.position.y > 0.3); } + #[test] + fn a_handicap_pulls_the_wheel_and_holds_the_engine_back() { + let asked = Asked { + throttle: 1.0, + steer: 0.2, + ..Asked::default() + }; + // A sound car is asked for what its driver asks. + assert_eq!(Handicap::default().apply(asked), asked); + let wrecked = Handicap { + pull: -0.3, + power: 0.6, + }; + let felt = wrecked.apply(asked); + assert!((felt.steer + 0.1).abs() < 1.0e-6 && (felt.throttle - 0.6).abs() < 1.0e-6); + // It pulls no further than the wheel turns. + let hard = Asked { + steer: -0.9, + ..asked + }; + assert_eq!(wrecked.apply(hard).steer, -1.0); + } + #[test] fn the_instruments_read_as_one_line() { let hud = Hud { diff --git a/crates/solstice-game/src/ground.rs b/crates/solstice-game/src/ground.rs new file mode 100644 index 0000000..9e1ad32 --- /dev/null +++ b/crates/solstice-game/src/ground.rs @@ -0,0 +1,220 @@ +//! What the ground is made of, place by place: a map for land that is not a circuit. +//! +//! A circuit's track file says what lies either side of its road. Open country has no such +//! order: a bog lies where water gathers, rock where a ridge breaks through, and a track's +//! clay wherever the track has wandered. So the bake writes a map, a grid of squares each +//! holding one [`Surface`], and each tyre reads the square it is on. +//! +//! ```text +//! # surfaces X0 Z0 SPACING COLUMNS ROWS, then a line a row: runs of one surface, each a +//! # count and a letter (`a` is the first of Surface::ALL). +//! surfaces -500 -500 1 1000 1000 +//! 412i3f170i2g413i +//! ``` + +use crate::FileError; +use glam::Vec3; +use solstice_vehicle::Surface; +use std::fmt::Write; + +/// A grid of squares of ground, each of one surface. +#[derive(Clone, Debug, PartialEq)] +pub struct SurfaceMap { + /// World x and z of the first square's corner. + pub origin: [f32; 2], + /// The width of a square, in metres. + pub spacing: f32, + pub columns: u32, + pub rows: u32, + /// Each square's surface, as its place in [`Surface::ALL`]: `rows` rows of `columns`. + pub squares: Vec, +} + +impl SurfaceMap { + /// The surface at a place. Off the map, the nearest square's. + pub fn at(&self, point: Vec3) -> Surface { + if self.columns == 0 || self.rows == 0 { + return Surface::default(); + } + let column = (((point.x - self.origin[0]) / self.spacing).floor().max(0.0) as u32) + .min(self.columns - 1); + let row = (((point.z - self.origin[1]) / self.spacing).floor().max(0.0) as u32) + .min(self.rows - 1); + Surface::from_index(self.squares[(row * self.columns + column) as usize]) + .unwrap_or_default() + } + + pub fn parse(text: &str) -> Result { + let mut map: Option = None; + for (index, line) in text.lines().enumerate() { + let line = line.split('#').next().unwrap_or("").trim(); + if line.is_empty() { + continue; + } + let error = |message: String| FileError { + line: index + 1, + message, + }; + let Some(map) = &mut map else { + let words: Vec<&str> = line.split_whitespace().collect(); + let ["surfaces", x, z, spacing, columns, rows] = words[..] else { + return Err(error( + "expected `surfaces X0 Z0 SPACING COLUMNS ROWS` first".to_owned(), + )); + }; + let number = |word: &str| { + word.parse::() + .ok() + .filter(|n| n.is_finite()) + .ok_or_else(|| error(format!("`{word}` is not a number"))) + }; + let count = |word: &str| { + word.parse::() + .ok() + .filter(|&n| (1..=8192).contains(&n)) + .ok_or_else(|| error(format!("`{word}` should be from 1 to 8192"))) + }; + let spacing = number(spacing)?; + if spacing <= 0.0 { + return Err(error("the spacing must be above 0".to_owned())); + } + let (columns, rows) = (count(columns)?, count(rows)?); + map = Some(Self { + origin: [number(x)?, number(z)?], + spacing, + columns, + rows, + squares: Vec::with_capacity((columns * rows) as usize), + }); + continue; + }; + // A row: runs, each a count and a letter. + let mut count = 0_u32; + let mut filled = 0_u32; + let mut digits = false; + for letter in line.chars() { + if let Some(digit) = letter.to_digit(10) { + count = count + .checked_mul(10) + .and_then(|c| c.checked_add(digit)) + .ok_or_else(|| error("a run is too long".to_owned()))?; + digits = true; + continue; + } + let surface = (letter as u32) + .checked_sub('a' as u32) + .filter(|&s| s < Surface::ALL.len() as u32) + .ok_or_else(|| error(format!("`{letter}` is no surface")))?; + let run = if digits { count } else { 1 }; + filled += run; + if filled > map.columns { + return Err(error(format!("more than {} squares", map.columns))); + } + map.squares + .extend(std::iter::repeat_n(surface as u8, run as usize)); + (count, digits) = (0, false); + } + if digits || filled != map.columns { + return Err(error(format!( + "{filled} squares, where a row has {}", + map.columns + ))); + } + } + let map = map.ok_or(FileError { + line: 1, + message: "no `surfaces` line".to_owned(), + })?; + if map.squares.len() != (map.columns * map.rows) as usize { + return Err(FileError { + line: text.lines().count(), + message: format!( + "{} rows, where the map has {}", + map.squares.len() / map.columns as usize, + map.rows + ), + }); + } + Ok(map) + } + + /// The file's text, which [`SurfaceMap::parse`] reads back as it is. + pub fn to_text(&self) -> String { + let mut text = format!( + "surfaces {} {} {} {} {}\n", + self.origin[0], self.origin[1], self.spacing, self.columns, self.rows + ); + for row in self.squares.chunks(self.columns as usize) { + let mut k = 0; + while k < row.len() { + let run = row[k..].iter().take_while(|&&s| s == row[k]).count(); + let letter = (b'a' + row[k]) as char; + if run > 1 { + let _ = write!(text, "{run}"); + } + text.push(letter); + k += run; + } + text.push('\n'); + } + text + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn map() -> SurfaceMap { + let mut squares = vec![Surface::Litter.index(); 12]; + squares[5] = Surface::Bog.index(); + squares[6] = Surface::Mud.index(); + squares[7] = Surface::Mud.index(); + SurfaceMap { + origin: [-2.0, -1.5], + spacing: 1.0, + columns: 4, + rows: 3, + squares, + } + } + + #[test] + fn a_map_reads_back_what_it_wrote() { + let map = map(); + let text = map.to_text(); + assert_eq!(text, "surfaces -2 -1.5 1 4 3\n4i\nih2g\n4i\n"); + assert_eq!(SurfaceMap::parse(&text).unwrap(), map); + } + + #[test] + fn each_place_reads_its_square_and_the_nearest_beyond_the_edge() { + let map = map(); + let at = |x: f32, z: f32| map.at(Vec3::new(x, 9.0, z)); + assert_eq!(at(-0.5, 0.0), Surface::Bog); + assert_eq!(at(0.5, 0.0), Surface::Mud); + assert_eq!(at(1.99, -0.49), Surface::Mud); + assert_eq!(at(-1.5, 0.0), Surface::Litter); + assert_eq!(at(0.5, 0.6), Surface::Litter); + // Off the map: the nearest. + assert_eq!(at(50.0, 0.0), Surface::Mud); + assert_eq!(at(-50.0, -50.0), Surface::Litter); + } + + #[test] + fn mistakes_are_reported_with_their_line() { + for (text, line, part) in [ + ("4i", 1, "expected `surfaces"), + ("surfaces 0 0 1 2 1\n3i", 2, "more than 2"), + ("surfaces 0 0 1 2 1\ni", 2, "1 squares"), + ("surfaces 0 0 1 2 1\n2z", 2, "no surface"), + ("surfaces 0 0 1 2 2\n2a", 2, "1 rows"), + ("surfaces 0 0 0 2 1\n2a", 1, "above 0"), + ("# nothing", 1, "no `surfaces`"), + ] { + let error = SurfaceMap::parse(text).unwrap_err(); + assert_eq!(error.line, line, "{text}: {error}"); + assert!(error.message.contains(part), "{text}: {error}"); + } + } +} diff --git a/crates/solstice-game/src/impact.rs b/crates/solstice-game/src/impact.rs new file mode 100644 index 0000000..5040670 --- /dev/null +++ b/crates/solstice-game/src/impact.rs @@ -0,0 +1,378 @@ +//! Blows: what a car hits, where on it, which way, and how hard. +//! +//! Nothing here decides what a blow breaks: that is whoever plays the game's to say (the +//! viewer's `damage.rs`). This is the measuring. Two things are measured, both of them what +//! the physics already works out each step: +//! +//! * **What its body meets.** A car's body is a box among the scene's walls, its ground and +//! its blockers, and each step the physics says what meeting them did to the car's velocity +//! and its spin ([`solstice_physics::Knock`]). Times its mass and its inertia that is the +//! blow's impulse, and its turning impulse about the centre of mass; and the two together +//! say where the blow landed, for a push `J` at `r` from the centre turns the car by +//! `r × J`. A blow is seldom over in one step, so the steps of one blow are summed, and it +//! is told once it is over. The physics says too where the body is touching what it met +//! (`Physics::car_touches`): between them those places are the patch the blow landed on, +//! the whole of a nose against a wall or one corner of it against a post. +//! * **What comes up through a wheel.** A wheel is not in that box: it is a spring, and what +//! it lands on or runs into loads it. What the four of them push the car up with over a +//! step is a force already, in newtons: the car's mass times how hard it is pushed up +//! (`Telemetry::g`, which is over the whole step, bump stops and all), shared among the +//! wheels as they are loaded ([`wheel_forces`]). Several times what a wheel carries +//! standing still is a blow to that wheel, and its impulse is what it pushed with above +//! that, summed until the load has come back down. (Its peak is no measure: a tyre's load +//! is held to so many times its own, so every landing from over a metre peaks alike.) +//! +//! A blow's hardness is told as a force. The physics resolves a collision in a step, which +//! says nothing of how long the real thing would take: steel folding takes about a tenth of +//! a second, so a blow is its impulse over [`CRUSH_SECONDS`], to the body or through a wheel. + +use glam::{Quat, Vec3}; +use solstice_physics::vehicle::VehicleSpec; +use solstice_physics::Knock; +use solstice_world::STEP_SECONDS; + +/// How long a blow is taken to last, in seconds: its force is its impulse over this. A +/// car's nose folds for about a tenth of a second against a wall. +pub const CRUSH_SECONDS: f32 = 0.1; +/// The least a step's blow changes the car's velocity by, in metres a second, to be a blow +/// at all, once what merely holds the car up has been taken off it. +pub const LEAST_KNOCK: f32 = 0.12; +/// The most steps one blow is summed over: a car grinding along a wall is hit again and +/// again, not once for as long as it grinds. +pub const MOST_STEPS: u32 = 12; +/// How many times what it carries standing still a wheel must be loaded with to be struck, +/// and how far back down the load must come for the blow to be over. +pub const WHEEL_STRUCK: f32 = 3.0; +pub const WHEEL_OVER: f32 = 1.6; + +/// One blow to a car. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Impact { + /// Where on the car it landed, in the car's own space: from the ground under its middle, + /// +X to its right, +Y up, -Z ahead. + pub at: Vec3, + /// The way it pushed the car, in the car's own space: one long. + pub push: Vec3, + /// The patch of the car it landed on, in the car's own space: the least and the + /// greatest corners of a box round every place its body touched what it hit. For a + /// wheel, or where the physics names no place, it is the one point [`Self::at`]. + pub low: Vec3, + pub high: Vec3, + /// Its impulse, in newton seconds: for a wheel, of the load above what it carries at rest. + pub impulse: f32, + /// How hard it was, in newtons: its impulse over [`CRUSH_SECONDS`]. + pub force: f32, + /// The wheel it came up through, if it did: front left, front right, rear left, rear + /// right. + pub wheel: Option, +} + +/// A blow to the body that is not over yet. +#[derive(Clone, Copy, Debug, Default)] +struct Gathering { + /// The impulse so far, and the turning impulse about the centre of mass, in the car's + /// own space. + push: Vec3, + turn: Vec3, + steps: u32, + /// The box round every place the body has touched what it hit, if it has any. + patch: Option<(Vec3, Vec3)>, +} + +/// A wheel that is being struck: the impulse so far, of what it pushes with above what it +/// carries at rest. +#[derive(Clone, Copy, Debug, Default)] +struct Struck { + impulse: f32, +} + +/// Gathers one car's blows, step by step. +#[derive(Clone, Debug, Default)] +pub struct Blows { + body: Option, + wheels: [Option; 4], +} + +/// Where a push that turned the car so landed on its body: on the line the push acts along, +/// where that line comes into the car's box. `push` and `turn` are the impulse and the +/// turning impulse about the centre of mass, in the car's own space. +pub fn landed(spec: &VehicleSpec, push: Vec3, turn: Vec3) -> Vec3 { + let along = push.normalize_or_zero(); + // The nearest point of the line to the centre of mass: `r × J = L` gives `r` across `J`. + let across = push.cross(turn) / push.length_squared().max(1.0e-9); + let from = spec.centre + across; + let (low, high) = ( + spec.body_at - spec.body_size * 0.5, + spec.body_at + spec.body_size * 0.5, + ); + // Where the line is inside the box, if it is: between the last face it comes in by and + // the first it goes out by. + let (mut enters, mut leaves) = (f32::MIN, f32::MAX); + for axis in 0..3 { + if along[axis].abs() < 1.0e-6 { + if from[axis] < low[axis] || from[axis] > high[axis] { + enters = f32::MAX; + } + continue; + } + let (a, b) = ( + (low[axis] - from[axis]) / along[axis], + (high[axis] - from[axis]) / along[axis], + ); + enters = enters.max(a.min(b)); + leaves = leaves.min(a.max(b)); + } + if enters <= leaves { + return from + along * enters; + } + // Several things met at once need not sum to a push through the box: then it is the + // nearest of the box to the line, on the side the push came from. + let reach = spec.body_size.length() * 0.5; + (from - along * reach).clamp(low, high) +} + +/// What each wheel pushes the car up with over a step, in newtons: the car's mass times how +/// hard its wheels push it up between them (`lifted`, in g, as its instruments have it), +/// shared among the wheels as each is loaded at the step's end. +pub fn wheel_forces(spec: &VehicleSpec, loads: [f32; 4], lifted: f32) -> [f32; 4] { + let all: f32 = loads.iter().map(|load| load.max(0.0)).sum(); + if all <= 0.0 { + return [0.0; 4]; + } + let pushed = spec.mass * solstice_physics::GRAVITY * lifted.max(0.0); + loads.map(|load| pushed * load.max(0.0) / all) +} + +impl Blows { + /// A step of the car's body: what hitting things did to it, how it is turned, its + /// numbers, and where its body is touching things (asked for only in a step that is + /// part of a blow). Gives a blow, once one is over. + pub fn body( + &mut self, + knock: Knock, + rotation: Quat, + spec: &VehicleSpec, + touches: impl FnOnce() -> Vec, + ) -> Option { + // What holds a car up that lies on its belly, its side or its roof is no blow: it + // undoes a step's gravity, and no more than that is taken off. + let held = (solstice_physics::GRAVITY * STEP_SECONDS as f32).min(knock.velocity.y.max(0.0)); + let knocked = knock.velocity - Vec3::Y * held; + let quiet = knocked.length() < LEAST_KNOCK; + if !quiet { + let to_car = rotation.inverse(); + let gathering = self.body.get_or_insert_with(Gathering::default); + gathering.push += to_car * knocked * spec.mass; + gathering.turn += to_car * knock.spin * spec.inertia; + gathering.steps += 1; + for touch in touches() { + let (low, high) = gathering.patch.get_or_insert((touch, touch)); + (*low, *high) = (low.min(touch), high.max(touch)); + } + } + let over = self + .body + .is_some_and(|gathering| quiet || gathering.steps >= MOST_STEPS); + let gathered = self.body.take_if(|_| over)?; + let impulse = gathered.push.length(); + if impulse <= 0.0 { + return None; + } + let at = landed(spec, gathered.push, gathered.turn); + let (low, high) = gathered.patch.unwrap_or((at, at)); + Some(Impact { + at, + push: gathered.push / impulse, + low, + high, + impulse, + force: impulse / CRUSH_SECONDS, + wheel: None, + }) + } + + /// A step of one of the car's wheels: what it pushes the car up with, in newtons + /// ([`wheel_forces`]). Gives a blow, once the wheel has been struck and the load has + /// come back down. + pub fn wheel(&mut self, index: usize, load: f32, spec: &VehicleSpec) -> Option { + let (front, rear) = spec.static_loads(solstice_physics::GRAVITY); + let rest = if index < 2 { front } else { rear }; + let struck = &mut self.wheels[index]; + match struck { + None if load >= rest * WHEEL_STRUCK => { + *struck = Some(Struck { + impulse: (load - rest) * STEP_SECONDS as f32, + }); + None + } + None => None, + Some(blow) if load > rest * WHEEL_OVER => { + blow.impulse += (load - rest) * STEP_SECONDS as f32; + None + } + Some(blow) => { + let blow = *blow; + *struck = None; + // Where its tyre meets the ground. + let at = spec.hubs()[index] - Vec3::Y * spec.axle(index).radius; + Some(Impact { + at, + push: Vec3::Y, + low: at, + high: at, + impulse: blow.impulse, + force: blow.impulse / CRUSH_SECONDS, + wheel: Some(index), + }) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const TRUCK: &str = include_str!("../../solstice-vehicle/tests/wagon.vehicle"); + + fn spec() -> VehicleSpec { + VehicleSpec::parse(TRUCK).expect("the truck's file reads") + } + + /// The physics names no place the body touched. + fn none() -> Vec { + Vec::new() + } + + /// The knock a push at a place on the car gives it: the other way round from what is + /// measured. + fn knock_of(spec: &VehicleSpec, at: Vec3, push: Vec3) -> Knock { + Knock { + velocity: push / spec.mass, + spin: (at - spec.centre).cross(push) / spec.inertia, + } + } + + #[test] + fn a_blow_is_found_where_it_landed_and_is_as_hard_as_its_impulse() { + let spec = spec(); + // Its nose's left corner, half a metre up, pushed straight back: two tonnes stopped + // from three metres a second. + let corner = Vec3::new(-0.7, 0.6, spec.body_at.z - spec.body_size.z * 0.5); + let push = Vec3::Z * spec.mass * 3.0; + let mut blows = Blows::default(); + // It is told when it is over: the step after. + let turned = Quat::IDENTITY; + assert!(blows + .body(knock_of(&spec, corner, push), turned, &spec, none) + .is_none()); + let blow = blows.body(Knock::default(), turned, &spec, none).unwrap(); + assert!(blow.at.distance(corner) < 0.02, "{}", blow.at); + assert!(blow.push.distance(Vec3::Z) < 1.0e-4); + assert!((blow.impulse - spec.mass * 3.0).abs() < 1.0); + assert!((blow.force - spec.mass * 3.0 / CRUSH_SECONDS).abs() < 10.0); + assert_eq!(blow.wheel, None); + // With no place named, its patch is the point it landed at. + assert_eq!((blow.low, blow.high), (blow.at, blow.at)); + // And nothing more is told of it. + assert!(blows.body(Knock::default(), turned, &spec, none).is_none()); + } + + #[test] + fn a_blow_over_several_steps_is_one_blow_however_the_car_is_turned() { + let spec = spec(); + // The car faces +X in the world, and is hit in its right side, at the door: in the + // world the push is along -Z... and it comes in three steps. + let turned = Quat::from_rotation_y(-std::f32::consts::FRAC_PI_2); + let door = Vec3::new(spec.body_size.x * 0.5, 1.0, 0.3); + let push = Vec3::NEG_X * spec.mass * 2.0; + let own = knock_of(&spec, door, push / 3.0); + let world = Knock { + velocity: turned * own.velocity, + spin: turned * own.spin, + }; + let mut blows = Blows::default(); + // Each step its body touches the thing in two places, a little further along. + for step in 0..3 { + let touches = move || { + let along = 0.1 * step as f32; + vec![door + Vec3::Z * along, door - Vec3::new(0.0, 0.4, along)] + }; + assert!(blows.body(world, turned, &spec, touches).is_none()); + } + let blow = blows.body(Knock::default(), turned, &spec, none).unwrap(); + // Its patch is the box round all of them. + assert!(blow.low.distance(door - Vec3::new(0.0, 0.4, 0.2)) < 1.0e-5); + assert!(blow.high.distance(door + Vec3::Z * 0.2) < 1.0e-5); + assert!(blow.at.distance(door) < 0.02, "{}", blow.at); + assert!(blow.push.distance(Vec3::NEG_X) < 1.0e-4); + assert!((blow.impulse - spec.mass * 2.0).abs() < 1.0); + } + + #[test] + fn what_holds_a_car_up_is_not_a_blow_and_grinding_is_many() { + let spec = spec(); + let mut blows = Blows::default(); + // Lying on its roof: the ground undoes a step's gravity, every step. + let held = Knock { + velocity: Vec3::Y * solstice_physics::GRAVITY * STEP_SECONDS as f32, + spin: Vec3::ZERO, + }; + for _ in 0..200 { + assert!(blows.body(held, Quat::IDENTITY, &spec, none).is_none()); + } + // Landing on it is: what is over and above the holding up. + let landing = Knock { + velocity: Vec3::Y * 4.0, + spin: Vec3::ZERO, + }; + assert!(blows.body(landing, Quat::IDENTITY, &spec, none).is_none()); + let blow = blows.body(held, Quat::IDENTITY, &spec, none).unwrap(); + let above = 4.0 - solstice_physics::GRAVITY * STEP_SECONDS as f32; + assert!((blow.impulse - spec.mass * above).abs() < 1.0); + // A push that goes on and on is told every so many steps. + let grind = knock_of(&spec, Vec3::new(0.9, 1.0, 0.0), Vec3::NEG_X * 900.0); + let mut told = 0; + for _ in 0..MOST_STEPS * 3 { + told += u32::from(blows.body(grind, Quat::IDENTITY, &spec, none).is_some()); + } + assert_eq!(told, 3); + } + + #[test] + fn pushes_that_do_not_sum_to_one_through_the_car_land_on_its_near_side() { + let spec = spec(); + // A push back with a turn no one push through the box could give it. + let at = landed(&spec, Vec3::Z * 4000.0, Vec3::Y * 40_000.0); + let (low, high) = ( + spec.body_at - spec.body_size * 0.5, + spec.body_at + spec.body_size * 0.5, + ); + assert!(at.cmpge(low).all() && at.cmple(high).all(), "{at}"); + assert!((at.z - low.z).abs() < 1.0e-4, "on its nose: {at}"); + } + + #[test] + fn a_wheel_is_struck_by_several_times_its_load_and_as_hard_as_its_impulse() { + let spec = spec(); + let (front, _) = spec.static_loads(solstice_physics::GRAVITY); + let mut blows = Blows::default(); + // Driven over rough ground: twice its load is nothing. + for _ in 0..30 { + assert!(blows.wheel(1, front * 2.0, &spec).is_none()); + } + // A landing: up to six times, and back down. + for times in [3.5, 6.0, 4.0, 2.0] { + assert!(blows.wheel(1, front * times, &spec).is_none()); + } + let blow = blows.wheel(1, front, &spec).unwrap(); + assert_eq!(blow.wheel, Some(1)); + assert_eq!(blow.push, Vec3::Y); + // Under the front right wheel. + assert!(blow.at.x > 0.5 && blow.at.z < -1.0 && blow.at.y.abs() < 1.0e-4); + let summed = front * (2.5 + 5.0 + 3.0 + 1.0) * STEP_SECONDS as f32; + assert!((blow.impulse - summed).abs() < 1.0); + assert!((blow.force - summed / CRUSH_SECONDS).abs() < 10.0); + assert!(blows.wheel(1, front, &spec).is_none()); + } +} diff --git a/crates/solstice-game/src/input.rs b/crates/solstice-game/src/input.rs index 525e915..5a5491a 100644 --- a/crates/solstice-game/src/input.rs +++ b/crates/solstice-game/src/input.rs @@ -101,9 +101,21 @@ look_round key KeyJ -1 look_over gamepad right_y look_over key KeyI look_over key KeyK -1 +# The mouse swings the view right round the car, and up over it. +orbit mouse x -0.0032 +orbit_up mouse y 0.0026 # P hands the car to a driver of its own, round the circuit, and takes it back. autopilot key KeyP autopilot gamepad start +# A four-wheel drive: T moves its transfer case on, from two-wheel drive to four high to four +# low; G locks its differentials, the rear, then both, then neither. +drive_mode key KeyT +drive_mode gamepad west +diff_lock key KeyG +diff_lock gamepad south +# Y lets its tyres down for mud and sand, and pumps them up again for hard ground. +tyres key KeyY +tyres gamepad up "; /// A kind of input device. @@ -288,6 +300,10 @@ pub const STICK_DEAD_ZONE: f32 = 0.15; pub struct Devices { values: HashMap<(Device, String), f32>, pressed: HashSet<(Device, String)>, + /// How many times as fast as it was made to a controller's right stick looks round: as + /// it was made, if this is nothing. What is bound to the stick is a rate, so more of + /// the stick is more of the rate. + pub look: f32, } impl Devices { @@ -354,6 +370,8 @@ impl Devices { } else { value.signum() * ((size - STICK_DEAD_ZONE) / (1.0 - STICK_DEAD_ZONE)).min(1.0) }; + let faster = axis.starts_with("right_") && self.look > 0.0; + let value = if faster { value * self.look } else { value }; self.set(Device::Gamepad, axis, value); } @@ -391,6 +409,14 @@ impl Devices { self.values .retain(|(device, control), _| !device.is_movement(control)); } + + /// Whether anything of a device's was pressed this frame: a key or a button going down, + /// a trigger pulled or a stick pushed past half way. What is only resting off its + /// middle, a worn stick, never is; nor is the mouse being moved. So it says which + /// device a hand is on, for whoever names its buttons. + pub fn pressed_on(&self, device: Device) -> bool { + self.pressed.iter().any(|(of, _)| *of == device) + } } #[cfg(test)] @@ -511,6 +537,24 @@ mod tests { assert_eq!(presses, 2, "pressed, held, released, pressed again"); } + #[test] + fn the_device_in_hand_is_the_one_that_was_pressed() { + let mut devices = Devices::new(); + // A worn stick resting off its middle, and the mouse moving, are nobody's hand. + devices.gamepad_axis("left_x", 0.3); + devices.mouse_motion(40.0, 0.0); + assert!(!devices.pressed_on(Device::Gamepad) && !devices.pressed_on(Device::Mouse)); + // A trigger pulled past half way is, once: held, it is not pressed again. + devices.gamepad_button("r2", 0.8); + assert!(devices.pressed_on(Device::Gamepad) && !devices.pressed_on(Device::Key)); + devices.end_frame(); + devices.gamepad_button("r2", 0.9); + assert!(!devices.pressed_on(Device::Gamepad)); + devices.key("KeyW", true); + devices.mouse_button("left", true); + assert!(devices.pressed_on(Device::Key) && devices.pressed_on(Device::Mouse)); + } + #[test] fn a_tap_presses_without_holding_and_focus_loss_lets_go() { let map = InputMap::default(); diff --git a/crates/solstice-game/src/lib.rs b/crates/solstice-game/src/lib.rs index e830def..79cfa44 100644 --- a/crates/solstice-game/src/lib.rs +++ b/crates/solstice-game/src/lib.rs @@ -8,6 +8,8 @@ //! * [`play`]: a running game, built from a baked scene's gameplay files. //! * [`track`]: `.track` files, a circuit's centre line and what lies beside it; [`race`], which //! times laps round it; and [`drive`], the player's car, its camera and its instruments. +//! * [`ground`]: a map of what open country is made of, for land that is not a circuit. +//! * [`par`]: how long a track takes a truck of some kind, worked out from the track. //! //! None of it touches the GPU. The viewers move the renderer's instances, and its camera, as //! [`play::Play::frame`] tells them. @@ -17,7 +19,10 @@ use solstice_asset::MAX_COORDINATE; pub mod actor; pub mod animation; pub mod drive; +pub mod ground; +pub mod impact; pub mod input; +pub mod par; pub mod play; pub mod race; pub mod scene; @@ -25,10 +30,13 @@ pub mod track; pub use actor::{ActorFile, Mesh, Property, PropertyKind}; pub use drive::Hud; +pub use ground::SurfaceMap; +pub use impact::Impact; pub use input::{Binding, Device, Devices, InputMap}; pub use play::{Message, Play, View}; pub use scene::{missing_files, ActorLine, Blocker, SceneGame, GAME_FILE}; -pub use solstice_vehicle::VehicleSpec; +pub use solstice_vehicle::{rut, Surface, VehicleSpec}; +pub use solstice_world::Entity; pub use track::Track; use std::fmt; diff --git a/crates/solstice-game/src/par.rs b/crates/solstice-game/src/par.rs new file mode 100644 index 0000000..713734d --- /dev/null +++ b/crates/solstice-game/src/par.rs @@ -0,0 +1,292 @@ +//! How long a track takes: the time a good driver gets round it in, worked out from the track +//! itself, so that a track that is changed, or a new one, has times to beat without anybody +//! driving it first. +//! +//! It goes along the centre line a couple of metres at a time and asks how fast each place can +//! be taken, as [`crate::drive::autopilot`] asks of the road ahead of it: by how tight the bend +//! is, by what is underfoot, by whether the track drops away and comes back, by how steep it +//! is, and no faster than the truck goes. Then it works back from every slow place by how hard +//! the truck brakes, and forward by how hard it pulls away, and adds up the time. + +use crate::drive::Pace; +use crate::track::Track; +use glam::Vec3; + +/// How a truck of some kind gets round a track. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Going { + /// How hard it corners and brakes, and how fast it will go. + pub pace: Pace, + /// How hard it pulls away, in metres a second squared. + pub pull: f32, + /// How much faster than a car that drives itself it crosses what is crossed at a crawl: a + /// ford, a bog, a step. + pub crawl: f32, +} + +/// How far apart the places asked about are, in metres, or a little less: a whole number of +/// them go round the lap. +const STEP: f32 = 2.0; +/// How far behind the line a timed run starts from rest, in metres. +pub const RUN_UP: f32 = 6.0; +/// How much of its top speed a truck loses for each metre it climbs or drops in a metre, and +/// the least of it that is left however steep. +const STEEP: f32 = 2.5; +const STEEPEST: f32 = 0.2; + +/// A track as one kind of truck drives it: how fast at each place, and how long to there. +#[derive(Clone, Debug, PartialEq)] +pub struct Profile { + /// How far apart its places are, and how long the lap is, in metres. + step: f32, + length: f32, + /// How fast each place is taken, in metres a second. + speeds: Vec, + /// How long it takes to get to each place from the line, in seconds, and, last, round to + /// the line again. + times: Vec, +} + +impl Profile { + /// Works a track out for a truck. `caution` says how fast a place may be crossed by a car + /// that drives itself, as the autopilot is told: a ford or a bog at a crawl. + /// + /// The lap is from rest, [`RUN_UP`] behind the line, and is not slowed for the line at its + /// end: a timed run. + pub fn of(track: &Track, going: &Going, caution: Option<&dyn Fn(Vec3) -> f32>) -> Self { + let length = track.length(); + let count = ((length / STEP).ceil() as usize).max(3); + let step = length / count as f32; + let pace = &going.pace; + let flat = |v: Vec3| Vec3::new(v.x, 0.0, v.z); + let mut speeds: Vec = (0..count) + .map(|index| { + let along = index as f32 * step; + let at = |d: f32| track.place(along + d).0; + let mut limit = pace.top_speed; + // The bend: the circle through three points of the road, twelve metres of it. + let (a, b, c) = (flat(at(-6.0)), flat(at(0.0)), flat(at(6.0))); + let bend = 2.0 * (b - a).cross(c - b).length() + / ((b - a).length() * (c - b).length() * (c - a).length()).max(1.0e-6); + limit = limit.min((pace.cornering / bend.max(1.0e-4)).sqrt()); + // A track that drops away and comes back, as at a washout or a step. + let (before, here, after) = (at(-3.0), at(0.0), at(3.0)); + let dip = (before.y + after.y - 2.0 * here.y).abs(); + if dip > 0.22 { + limit = limit.min(2.2 * going.crawl); + } else if dip > 0.1 { + limit = limit.min(4.0 * going.crawl); + } + // What is underfoot. + if let Some(caution) = caution { + limit = limit.min(caution(here) * going.crawl); + } + // And how steep it is, up or down. + let grade = (at(6.0).y - at(-6.0).y).abs() / 12.0; + limit.min(pace.top_speed * (1.0 - STEEP * grade).max(STEEPEST)) + }) + .collect(); + // Back from every slow place, by how hard it brakes: twice round, so that what is + // just past the line slows what comes up to it. + for index in (0..2 * count).rev() { + let next = speeds[(index + 1) % count]; + let here = &mut speeds[index % count]; + *here = here.min((next * next + 2.0 * pace.braking * step).sqrt()); + } + // Forward from the start, by how hard it pulls away. + speeds[0] = speeds[0].min((2.0 * going.pull * RUN_UP).sqrt()); + for index in 1..count { + let before = speeds[index - 1]; + speeds[index] = speeds[index].min((before * before + 2.0 * going.pull * step).sqrt()); + } + let mut times = Vec::with_capacity(count + 1); + let mut seconds = 0.0; + for index in 0..count { + times.push(seconds); + let next = speeds[(index + 1).min(count - 1)]; + seconds += step / ((speeds[index] + next) * 0.5).max(0.3); + } + times.push(seconds); + Self { + step, + length, + speeds, + times, + } + } + + /// How long the lap takes, in seconds. + pub fn seconds(&self) -> f32 { + self.times[self.times.len() - 1] + } + + /// How long the lap is, in metres. + pub fn length(&self) -> f32 { + self.length + } + + /// How long it takes to get this far round from the line, in seconds. + pub fn time_at(&self, along: f32) -> f32 { + let place = (along.clamp(0.0, self.length) / self.step).min(self.speeds.len() as f32); + let index = (place.floor() as usize).min(self.speeds.len() - 1); + let share = place - index as f32; + self.times[index] + (self.times[index + 1] - self.times[index]) * share + } + + /// How far round from the line it has got after this long, in metres: no further than the + /// line again. + pub fn along_at(&self, seconds: f32) -> f32 { + if seconds <= 0.0 { + return 0.0; + } + let after = self.times.partition_point(|&time| time <= seconds); + if after >= self.times.len() { + return self.length; + } + let (from, to) = (self.times[after - 1], self.times[after]); + let share = (seconds - from) / (to - from).max(1.0e-6); + (((after - 1) as f32 + share) * self.step).min(self.length) + } + + /// How fast this place is taken, in metres a second. + pub fn speed_at(&self, along: f32) -> f32 { + let index = (along.rem_euclid(self.length) / self.step) as usize; + self.speeds[index.min(self.speeds.len() - 1)] + } + + /// How much of the lap's length is taken slower than this, from 0 to 1. + pub fn share_below(&self, speed: f32) -> f32 { + let slow = self.speeds.iter().filter(|&&at| at < speed).count(); + slow as f32 / self.speeds.len() as f32 + } + + /// The slowest places on the track, where time is won and lost: the slowest of each of + /// `count` equal stretches of the lap, so that they are from all round it, no two within + /// `apart` metres of each other or of the line, in the order they come. + pub fn slowest(&self, count: usize, apart: f32) -> Vec { + let places = self.speeds.len(); + let mut found: Vec = Vec::new(); + for stretch in 0..count { + let (from, to) = (stretch * places / count, (stretch + 1) * places / count); + let slowest = (from..to) + .filter(|&index| { + let along = index as f32 * self.step; + let clear = |other: f32| { + let gap = (along - other).abs(); + gap.min(self.length - gap) >= apart + }; + clear(0.0) && found.iter().all(|&other| clear(other)) + }) + .min_by(|&a, &b| self.speeds[a].total_cmp(&self.speeds[b])); + if let Some(index) = slowest { + found.push(index as f32 * self.step); + } + } + found + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::track::tests::oval; + + fn going(scale: f32) -> Going { + Going { + pace: Pace { + cornering: 3.0 * scale, + braking: 3.5 * scale, + top_speed: 14.0 * scale, + looks: Pace::TOURING.looks, + }, + pull: 1.5 * scale, + crawl: 1.0, + } + } + + #[test] + fn a_lap_takes_longer_than_flat_out_and_a_better_truck_is_quicker() { + let track = oval(); + let slow = Profile::of(&track, &going(1.0), None); + let quick = Profile::of(&track, &going(1.5), None); + let flat_out = track.length() / 14.0; + assert!( + slow.seconds() > flat_out && slow.seconds() < flat_out * 2.0, + "{} against {flat_out}", + slow.seconds() + ); + assert!(quick.seconds() < slow.seconds() * 0.85); + // The oval's bends are fifty metres round: taken at what the truck corners at, and the + // straights faster. + let bend = (3.0_f32 * 50.0).sqrt(); + assert!( + (slow.speed_at(190.0) - bend).abs() < 0.8, + "{}", + slow.speed_at(190.0) + ); + assert!(slow.speed_at(420.0) > bend + 1.0); + // It starts from rest behind the line, and is still getting going over it. + assert!(slow.speed_at(0.0) < 5.0); + } + + #[test] + fn what_is_underfoot_slows_it_and_is_braked_for() { + let track = oval(); + let dry = Profile::of(&track, &going(1.0), None); + // A ford across the far straight, twenty metres of it. + let ford = |at: Vec3| { + if at.x > 90.0 && at.z.abs() < 10.0 { + 2.6 + } else { + f32::INFINITY + } + }; + let wet = Profile::of(&track, &going(1.0), Some(&ford)); + assert!(wet.seconds() > dry.seconds() + 4.0); + let slowest = wet.slowest(1, 60.0); + assert_eq!(slowest.len(), 1); + assert!( + (wet.speed_at(slowest[0]) - 2.6).abs() < 0.01, + "the ford is the slowest place: {slowest:?}" + ); + // Ten metres before it the truck is already slowing for it. + assert!(wet.speed_at(slowest[0] - 10.0) < dry.speed_at(slowest[0] - 10.0) - 1.0); + // A truck that crawls faster loses less to it. + let keen = Going { + crawl: 1.5, + ..going(1.0) + }; + assert!(Profile::of(&track, &keen, Some(&ford)).seconds() < wet.seconds() - 1.0); + } + + #[test] + fn where_it_is_and_when_agree() { + let track = oval(); + let profile = Profile::of(&track, &going(1.0), None); + assert_eq!(profile.time_at(0.0), 0.0); + assert!((profile.time_at(track.length()) - profile.seconds()).abs() < 1.0e-3); + let mut last = -1.0; + for tenth in 0..=10 { + let along = track.length() * tenth as f32 / 10.0; + let seconds = profile.time_at(along); + assert!(seconds > last, "time goes on round the lap"); + last = seconds; + assert!( + (profile.along_at(seconds) - along).abs() < 0.05, + "{along} m is reached at {seconds} s" + ); + } + assert_eq!(profile.along_at(-3.0), 0.0); + assert_eq!(profile.along_at(profile.seconds() + 60.0), track.length()); + } + + #[test] + fn the_slowest_places_are_apart_and_in_order() { + let track = oval(); + let profile = Profile::of(&track, &going(1.0), None); + let places = profile.slowest(3, 80.0); + assert!(places.len() >= 2, "{places:?}"); + assert!(places.windows(2).all(|pair| pair[1] - pair[0] >= 80.0)); + assert!(places.iter().all(|&along| along >= 80.0)); + } +} diff --git a/crates/solstice-game/src/play.rs b/crates/solstice-game/src/play.rs index ea03085..760e746 100644 --- a/crates/solstice-game/src/play.rs +++ b/crates/solstice-game/src/play.rs @@ -20,7 +20,7 @@ use solstice_physics::vehicle::{Surface, Vehicle, VehicleSpec}; use solstice_physics::{Car, Overlap, Physics, GRAVITY}; use solstice_script::{Script, ScriptEvent, ScriptHost}; use solstice_world::{ - Entity, Game, GlobalTransform, Name, Played, Schedule, TickGroup, Transform, World, + Entity, Game, GlobalTransform, Idle, Name, Played, Schedule, TickGroup, Transform, World, STEP_SECONDS, }; use std::cell::{Cell, RefCell}; @@ -81,6 +81,14 @@ pub struct Play { host: Rc>, drawn: Vec, player: Option, + /// Whoever drives the player's car, who can get out of it and walk: an actor of their + /// own with a camera, when the scene has one beside the car. And whether they are out. + walker: Option, + afoot: bool, + /// What the driver carries on foot, and where it is: in their hand, lying where it was + /// put down, or put away. Whoever runs the game says ([`Play::carry`]). + carried: Vec, + carry: Option<(Vec3, Quat)>, map: InputMap, /// How far the camera looks up, as of the last step. pitch: f32, @@ -100,14 +108,26 @@ pub struct Play { flying: bool, /// The circuit, if the scene is one. track: Option>, + /// How wet the ground is, from 0 to 1, as whoever runs the weather last said. + wetness: Rc>, + /// The pace the game drives the player's car at, while it does: see + /// [`Play::set_autopilot`]. + chauffeur: Rc>>, /// The camera that follows the player's car. chase: Chase, /// The player's car's instruments, as of the latest frame. hud: Option, /// What the timing of laps has to say, for the viewer to show. race_log: Rc>>, + /// The blows the player's car has taken since they were last asked for (`impact.rs`), + /// and what is wrong with it, as whoever keeps its damage last said. + impacts: Rc>>, + handicap: Rc>, } +/// How fast a stick held right over swings the view round a car, in radians a second. +const STICK_ORBIT: f32 = 3.4; + impl Play { /// Builds the game in a baked scene's gameplay `files`. `instance` gives where the bake /// placed a renderer instance. Every mistake found is reported, each with its file and line. @@ -172,6 +192,29 @@ impl Play { place.surface }); } + // Open country has a map of its ground, which says more than a track's edges can. + let ground: Option> = match &scene.surfaces { + None => None, + Some(name) => match file(name).map(|text| crate::SurfaceMap::parse(text)) { + Some(Ok(map)) => { + let map = Rc::new(map); + let tyres = map.clone(); + physics + .borrow_mut() + .set_surfaces(move |point| tyres.at(point)); + Some(map) + } + Some(Err(e)) => { + errors.push(format!("{name}: {e}")); + None + } + None => { + errors.push(format!("{name}: missing from the scene's gameplay")); + None + } + }, + }; + let mapped = ground.is_some(); if let Some(collision) = collision { physics.borrow_mut().add_scene(collision, &instance); } @@ -184,7 +227,9 @@ impl Play { } let mut world = World::new(); let mut drawn = Vec::new(); - let mut player = None; + let mut player: Option = None; + let mut walker: Option = None; + let mut carried = Vec::new(); let mut scripts: Vec = Vec::new(); for (index, line) in scene.actors.iter().enumerate() { let at = format!("{GAME_FILE}: actor {} ({})", index + 1, line.file); @@ -252,7 +297,7 @@ impl Play { if let Some(character) = actor.character { components.add(character); } - if actor.camera.is_some() && player.is_none() { + if actor.camera.is_some() { components.add(Played); } // A car: its numbers, its wheels as they are drawn, and its laps. @@ -276,17 +321,30 @@ impl Play { } } let entity = world.spawn(components.build()); + if actor.carried { + carried.push(entity); + } if let Some(eye) = actor.camera { - if player.is_some() { - errors.push(format!( - "{at}: only one actor can have a camera, and one already does" - )); - } - player = Some(Player { + let this = Player { entity, eye, car: hubs.is_some(), - }); + }; + match (&player, &walker) { + (None, _) => player = Some(this), + // A car and whoever drives it: the car is played first, and its driver + // when they get out. + (Some(first), None) if first.car != this.car => { + if this.car { + walker = player.replace(this); + } else { + walker = Some(this); + } + } + _ => errors.push(format!( + "{at}: only one actor can have a camera, or a car and its driver, and there is one already" + )), + } } if let Some(range) = &line.instances { let placed = Mat4::from_rotation_translation(rotation, line.position); @@ -347,23 +405,60 @@ impl Play { ScriptHost::install(&host, &mut schedule); // The player's car takes what the player asks of it, after scripts have had their say. let driven = player.as_ref().filter(|p| p.car).map(|p| p.entity); + // The driver sits in the car until they get out of it. + if let Some(walker) = &walker { + let _ = world.entities.insert_one(walker.entity, Idle); + } let circuit = track.clone(); // Whether the car is driving itself round the circuit, and where on it it last was. let (mut itself, mut last_at) = (false, None); + // How long the car driving itself has been asking to go and going nowhere. + let mut stuck_for = 0.0_f32; + // Where it was when it last got anywhere: a car wedged in a hole can spin its wheels + // and shake without going anywhere at all. + let mut last_place = Vec3::ZERO; // Whether the player's own gearbox is automatic, while the car drives itself. let mut players_gearbox = true; + let wetness: Rc> = Rc::default(); + let rained = wetness.clone(); + // The pace the car is to be driven at by the game, when whoever runs it asks. + let chauffeur: Rc>> = Rc::default(); + let (hired, mut was_hired) = (chauffeur.clone(), false); + // What is wrong with the car, which it is driven with whoever drives it. + let handicap: Rc> = Rc::default(); + let wrong = handicap.clone(); + // On a bush track a car that drives itself tours; round a circuit, it races. + let pace = if mapped { + drive::Pace::TOURING + } else { + drive::Pace::RACING + }; + // The lowest the track goes: a car far below that has fallen out of the world. + let lowest = track.as_ref().map_or(f32::MIN, |track| { + let heights = track.samples.iter().map(|sample| sample.position.y); + heights.fold(f32::MAX, f32::min) + }); schedule.add(TickGroup::PrePhysics, "driving", move |world| { + // Every car's tyres are on ground as wet as the weather has made it. + for (_, car) in world.entities.query_mut::<(Entity, &mut Car)>() { + car.vehicle.set_wetness(rained.get()); + } let Some(entity) = driven else { return; }; // While the player is away flying the camera, the keys that fly it are not the // car's: it is asked for nothing, as a walker left standing hears nothing. - let away = world.input().away(); + // Nor is a car whose driver has got out of it, which stands on its handbrake. + let idle = world.entities.get::<&Idle>(entity).is_ok(); + let away = world.input().away() || idle; let mut asked = if away { Default::default() } else { drive::asked(world.input()) }; + if idle { + asked.handbrake = 1.0; + } let reset = !away && world.input().pressed("reset"); // With no circuit there is nothing to drive round: the key does nothing. if !away && circuit.is_some() && world.input().pressed("autopilot") { @@ -375,11 +470,43 @@ impl Play { if itself { players_gearbox = car.driver.automatic; car.driver.automatic = true; + // Off the road it drives as anyone would: both axles driven, and + // the rear differential locked. + if mapped { + car.vehicle + .set_drive_mode(solstice_physics::vehicle::DriveMode::FourHigh); + car.vehicle.set_lockers(false, true); + } } else { car.driver.automatic = players_gearbox; } } } + // Whoever runs the game may have the car driven at a pace of their choosing, as + // when another driver's run is shown: handed over, and handed back, as the key + // does it. + let hire = hired.get(); + if hire.is_some() != was_hired { + was_hired = hire.is_some(); + last_at = None; + if let Ok(mut car) = world.entities.get::<&mut Car>(entity) { + if was_hired { + if !itself { + players_gearbox = car.driver.automatic; + } + car.driver.automatic = true; + if mapped { + car.vehicle + .set_drive_mode(solstice_physics::vehicle::DriveMode::FourHigh); + car.vehicle.set_lockers(false, true); + } + } else if !itself { + car.driver.automatic = players_gearbox; + } + } + } + let itself = itself || hire.is_some(); + let pace = hire.unwrap_or(pace); if let (true, Some(track)) = (itself, &circuit) { let car = world .entities @@ -392,26 +519,94 @@ impl Play { transform.rotation * Vec3::NEG_Z, car.vehicle.telemetry().speed, last_at, + &pace, + // On mapped ground it goes by what is ahead: a crawl through water + // and bog, slowly over rock and mud. + ground + .as_ref() + .map(|map| { + let map = map.clone(); + move |point: Vec3| match map.at(point) { + Surface::Ford | Surface::Bog => 2.6_f32, + Surface::Rock => 3.2, + Surface::Mud => 5.0, + _ => f32::INFINITY, + } + }) + .as_ref() + .map(|caution| caution as &dyn Fn(Vec3) -> f32), ); (asked, last_at) = (driven, Some(at)); } } + let (shift_drive, shift_lock, air) = ( + !away && world.input().pressed("drive_mode"), + !away && world.input().pressed("diff_lock"), + !away && world.input().pressed("tyres"), + ); if let Ok(mut car) = world.entities.get::<&mut Car>(entity) { - car.asked = asked; + // A car nobody is in is asked for nothing, whatever is wrong with it. + car.asked = if away { + asked + } else { + wrong.get().apply(asked) + }; + // A four-wheel drive's lever, and its lockers: the rear, then both, then none. + if shift_drive { + let next = car.vehicle.drive_mode().next(); + car.vehicle.set_drive_mode(next); + } + if shift_lock { + let (front, rear) = match car.vehicle.lockers() { + (false, false) => (false, true), + (false, true) => (true, true), + _ => (false, false), + }; + car.vehicle.set_lockers(front, rear); + } + if air { + let aired = car.vehicle.aired_down(); + car.vehicle.set_aired_down(!aired); + } } // Put back on the track when the player asks, and when the car has fallen far // below it: off a cliff, or into the sea. + // (In the bush a car is wherever it has been driven, down a hill from the track + // as likely as not: there it is lost only if it is under all the land there is.) let fallen = circuit.as_ref().is_some_and(|track| { world.entities.get::<&Transform>(entity).is_ok_and(|at| { + if mapped { + return at.translation.y < lowest - drive::FALLEN * 4.0; + } let place = track.locate(at.translation, last_at); // Kept as the next step's hint, or every step searches the whole lap. last_at = Some(place.sample); at.translation.y < track.samples[place.sample].position.y - drive::FALLEN }) }); - if let (true, Some(track)) = (reset || fallen, &circuit) { + // A car driving itself that has gone nowhere for five seconds is stuck: against a + // tree, in a bog, or on its side. It is put back, as a player would ask to be. + let here = world + .entities + .get::<&Transform>(entity) + .map_or(Vec3::ZERO, |at| at.translation); + if !itself || here.distance(last_place) > 1.5 { + last_place = here; + stuck_for = 0.0; + } else { + stuck_for += STEP_SECONDS as f32; + } + // Going nowhere for two seconds, it locks the front differential as well. + if itself && mapped && stuck_for > 2.0 { + if let Ok(mut car) = world.entities.get::<&mut Car>(entity) { + car.vehicle.set_lockers(true, true); + } + } + let stuck = stuck_for > 6.0; + if let (true, Some(track)) = (reset || fallen || stuck, &circuit) { drive::put_back(world, entity, track); last_at = None; + stuck_for = 0.0; } }); Physics::install(&physics, &mut schedule); @@ -431,8 +626,11 @@ impl Play { }; // Off the track: every wheel that is on the ground is on neither asphalt nor // kerb. + // On mapped ground the loop is a track through the bush, not a road with + // edges: wherever a car goes on its way round counts. let mut grounded = car.vehicle.wheels.iter().filter(|wheel| wheel.on_ground); - let off_track = grounded.clone().next().is_some() + let off_track = !mapped + && grounded.clone().next().is_some() && grounded .all(|wheel| !matches!(wheel.surface, Surface::Asphalt | Surface::Kerb)); for event in lap.step(track, transform.translation, off_track, STEP_SECONDS) { @@ -462,6 +660,37 @@ impl Play { } } }); + // What the player's car hits, and what comes up through its wheels: measured each + // step from what the physics made of it, and kept for whoever asks. + let impacts: Rc>> = Rc::default(); + let (struck, measured) = (impacts.clone(), physics.clone()); + let mut blows = crate::impact::Blows::default(); + schedule.add(TickGroup::PostPhysics, "blows", move |world| { + let Some(entity) = driven else { + return; + }; + let measured = measured.borrow(); + let Some(knock) = measured.car_knock(entity) else { + return; + }; + let Ok((car, transform)) = world.entities.query_one_mut::<(&Car, &Transform)>(entity) + else { + return; + }; + let spec = car.vehicle.spec(); + let mut struck = struck.borrow_mut(); + let touches = || measured.car_touches(entity); + struck.extend(blows.body(knock, transform.rotation, spec, touches)); + let loads = std::array::from_fn(|index| car.vehicle.wheels[index].load); + let lifted = car.vehicle.telemetry().g.z; + let forces = crate::impact::wheel_forces(spec, loads, lifted); + for (index, force) in forces.into_iter().enumerate() { + struck.extend(blows.wheel(index, force, spec)); + } + // Nobody asking is no reason to keep them for ever. + let kept = struck.len().saturating_sub(64); + struck.drain(..kept); + }); let animated: Rc> = Default::default(); let running = animated.clone(); schedule.add(TickGroup::PostPhysics, "animation", move |world| { @@ -493,6 +722,10 @@ impl Play { host, drawn, player, + walker, + afoot: false, + carried, + carry: None, map, pitch: 0.0, unstepped: 0.0, @@ -505,22 +738,57 @@ impl Play { viewer: Vec3::ZERO, flying: false, track, + wetness, + chauffeur, chase: Chase::default(), hud: None, race_log, + impacts, + handicap, }) } + /// The blows the player's car has taken since this was last asked: what its body hit + /// and what came up through its wheels, each with where, which way and how hard. + pub fn take_impacts(&mut self) -> Vec { + std::mem::take(&mut *self.impacts.borrow_mut()) + } + + /// Says what is wrong with the player's car, as its driver is to feel it. It stays so + /// until said again. + pub fn set_handicap(&self, handicap: drive::Handicap) { + self.handicap.set(handicap); + } + /// The circuit, if the scene is one. pub fn track(&self) -> Option<&Track> { self.track.as_deref() } + /// Says how wet the ground is, from 0, dry, to 1, soaked: whoever runs the weather tells + /// the game, and every car's tyres feel it from the next step. + pub fn set_wetness(&self, wetness: f32) { + self.wetness.set(wetness.clamp(0.0, 1.0)); + } + + /// What tyres have pressed into the ground (`solstice_vehicle::rut`): the ruts every + /// car's wheels stand in and deepen, for whoever draws them to read, and to lay what a + /// wheel threw where it landed. + pub fn ruts(&self, with: impl FnOnce(&mut solstice_physics::vehicle::Ruts) -> R) -> R { + with(self.physics.borrow_mut().ruts_mut()) + } + /// The player's car's instruments as of the latest frame, if the player drives a car. pub fn hud(&self) -> Option<&Hud> { self.hud.as_ref() } + /// How the devices' controls become the game's actions: the scene's `.input` file, or + /// the built-in set. For whoever shows a player which key or button does what. + pub fn input_map(&self) -> &InputMap { + &self.map + } + /// Whether the player is a car, whose instruments [`Play::hud`] has while it is driven. pub fn drives(&self) -> bool { self.player.as_ref().is_some_and(|player| player.car) @@ -576,6 +844,94 @@ impl Play { .flat_map(|d| d.instances.iter().map(|(id, _)| *id)) } + /// Moves one instance of an actor within the actor: a door swung on its hinge. `by` is + /// applied to where the instance now is, in the actor's own space. + pub fn move_within(&mut self, instance: u32, by: Mat4) { + for drawn in &mut self.drawn { + for (id, local) in &mut drawn.instances { + if *id == instance { + *local = by * *local; + // Drawn again, though the actor has not moved. + drawn.drawn = None; + } + } + } + } + + /// Takes an instance off its actor: the actor no longer moves it, and whoever took it + /// off draws it where they will (a piece torn off a truck, lying where it fell). Gives + /// where it was in the actor's own space, to put it back with ([`Play::attach`]). A + /// car's wheel is not taken off: it is where its hub is. + pub fn detach(&mut self, instance: u32) -> Option { + for drawn in &mut self.drawn { + let Some(at) = drawn.instances.iter().position(|(id, _)| *id == instance) else { + continue; + }; + if drawn.wheels[at].is_some() { + return None; + } + drawn.wheels.remove(at); + return Some(drawn.instances.remove(at).1); + } + None + } + + /// Puts an instance on the player's car, there in the car's own space: one that was + /// taken off it ([`Play::detach`]). Whether there is a car to put it on. + pub fn attach(&mut self, instance: u32, local: Mat4) -> bool { + let Some(car) = self.player.as_ref().filter(|player| player.car) else { + return false; + }; + let Some(drawn) = self + .drawn + .iter_mut() + .find(|drawn| drawn.entity == car.entity) + else { + return false; + }; + if !drawn.instances.iter().any(|(id, _)| *id == instance) { + drawn.instances.push((instance, local)); + drawn.wheels.push(None); + // Drawn again, though the car has not moved. + drawn.drawn = None; + } + true + } + + /// Gets the player out of the car and stands them somewhere: where they came out of a + /// door. Whether they are on foot there. + pub fn stand_at(&mut self, at: Vec3) -> bool { + if !self.afoot && !self.get_out() { + return false; + } + let Some(walker) = &self.walker else { + return false; + }; + let at = at + Vec3::Y * 0.2; + if let Ok(mut transform) = self + .game + .world + .entities + .get::<&mut Transform>(walker.entity) + { + transform.translation = at; + } + self.physics.borrow_mut().place(walker.entity, at); + true + } + + /// The instances that draw the player's car, its wheels among them. + pub fn car_instances(&self) -> Vec { + let Some(car) = self.player.as_ref().filter(|player| player.car) else { + return Vec::new(); + }; + self.drawn + .iter() + .filter(|drawn| drawn.entity == car.entity) + .flat_map(|drawn| drawn.instances.iter().map(|(id, _)| *id)) + .collect() + } + /// The scripts the game runs, by name, which a viewer may watch and [`Play::reload`]. pub fn scripts(&self) -> &[String] { &self.scripts @@ -599,6 +955,192 @@ impl Play { self.flying = flying; } + /// Whether the player's car has a driver who can get out of it and walk. + pub fn can_walk(&self) -> bool { + self.walker.is_some() && self.player.as_ref().is_some_and(|player| player.car) + } + + /// Whether the driver is out of the car, walking. + pub fn afoot(&self) -> bool { + self.afoot + } + + /// Gets the driver out of the car, to stand beside its door: the car is left on its + /// handbrake, and the keys walk the driver. Whether they got out. + pub fn get_out(&mut self) -> bool { + if self.afoot || self.flying { + return false; + } + let (Some(car), Some(walker)) = (&self.player, &self.walker) else { + return false; + }; + let entities = &mut self.game.world.entities; + let Ok(at) = entities.get::<&Transform>(car.entity).map(|at| *at) else { + return false; + }; + let yaw = at.rotation.to_euler(EulerRot::YXZ).0; + let facing = Quat::from_rotation_y(yaw); + // Out of the door they sit by: the left, unless the car's numbers say the right. + let right = entities + .get::<&Car>(car.entity) + .is_ok_and(|car| car.vehicle.spec().driver_right); + let side = if right { 1.95 } else { -1.95 }; + let beside = at.translation + facing * Vec3::new(side, 0.0, 0.3) + Vec3::Y * 0.35; + if let Ok(mut transform) = entities.get::<&mut Transform>(walker.entity) { + transform.translation = beside; + transform.rotation = facing; + } + self.physics.borrow_mut().place(walker.entity, beside); + let _ = entities.remove_one::(walker.entity); + let _ = entities.insert_one(car.entity, Idle); + self.afoot = true; + self.pitch = 0.0; + true + } + + /// Gets the driver back into the car, if they are within `reach` of it. Whether they did. + pub fn get_in(&mut self, reach: f32) -> bool { + if !self.afoot { + return false; + } + let (Some(car), Some(walker)) = (&self.player, &self.walker) else { + return false; + }; + let entities = &mut self.game.world.entities; + let place = |entity| entities.get::<&Transform>(entity).map(|at| at.translation); + let (Ok(car_at), Ok(walker_at)) = (place(car.entity), place(walker.entity)) else { + return false; + }; + if car_at.distance(walker_at) > reach { + return false; + } + let _ = entities.remove_one::(car.entity); + let _ = entities.insert_one(walker.entity, Idle); + self.afoot = false; + true + } + + /// Puts the player's car somewhere, facing a way, at rest: where it was left. Whether + /// there is a car to put. + pub fn place_car(&mut self, position: Vec3, yaw_degrees: f32) -> bool { + let Some(car) = self.player.as_ref().filter(|player| player.car) else { + return false; + }; + drive::put_at(&mut self.game.world, car.entity, position, yaw_degrees); + true + } + + /// Has the game drive the player's car round the track at a pace, whatever the player + /// asks of it, or gives it back to them: for showing how somebody else drives it. + pub fn set_autopilot(&mut self, pace: Option) { + self.chauffeur.set(pace); + } + + /// Puts the player's car `back` metres behind the start line, facing the way the lap + /// runs, at rest, with no lap begun: the start of a timed run. Whether there is a car + /// and a track to put it on. + pub fn to_the_line(&mut self, back: f32) -> bool { + let (Some(car), Some(track)) = ( + self.player.as_ref().filter(|player| player.car), + self.track.clone(), + ) else { + return false; + }; + let (centre, forward, left) = track.place(-back); + let up = forward.cross(left).normalize_or(Vec3::Y); + let entities = &mut self.game.world.entities; + if let Ok(mut transform) = entities.get::<&mut Transform>(car.entity) { + transform.rotation = + Quat::from_mat3(&glam::Mat3::from_cols(-left, up, -forward)).normalize(); + transform.translation = centre + up * 0.08; + } + if let Ok(mut driven) = entities.get::<&mut Car>(car.entity) { + driven.vehicle.settle(); + driven.asked = Default::default(); + } + if let Ok(mut lap) = entities.get::<&mut Lap>(car.entity) { + *lap = Lap::new(&track); + } + true + } + + /// Loads the player's car with this many kilograms, which it then has to carry. + pub fn set_payload(&mut self, kilograms: f32) { + let Some(car) = self.player.as_ref().filter(|player| player.car) else { + return; + }; + if let Ok(mut car) = self.game.world.entities.get::<&mut Car>(car.entity) { + car.vehicle.set_payload(kilograms); + } + } + + /// Says where what the driver carries is: there, turned so, or put away. It stays until + /// said again. + pub fn carry(&mut self, pose: Option<(Vec3, Quat)>) { + self.carry = pose; + } + + /// Puts a loose thing in the world: a box of this size, weighing this much, which falls, + /// lies where it comes to rest, is pushed by what meets it and weighs on what it lies + /// on. Nothing draws it: whoever put it there asks where it is ([`Play::thing`]). + pub fn add_thing(&mut self, at: Vec3, rotation: Quat, size: Vec3, kilograms: f32) -> Entity { + self.game.world.spawn(( + Name::new("thing"), + Transform::from_translation(at).with_rotation(rotation), + solstice_physics::ActorCollider { + shape: solstice_physics::Shape::Box(size), + kind: solstice_physics::BodyKind::Dynamic(kilograms.max(0.01)), + offset: Vec3::ZERO, + }, + )) + } + + /// Takes a loose thing out of the world. + pub fn remove_thing(&mut self, thing: Entity) { + let _ = self.game.world.entities.despawn(thing); + } + + /// Where a loose thing is, and how it is turned. + pub fn thing(&self, thing: Entity) -> Option<(Vec3, Quat)> { + self.game + .world + .entities + .get::<&Transform>(thing) + .ok() + .map(|at| (at.translation, at.rotation)) + } + + /// Puts a loose thing somewhere else, at rest. + pub fn move_thing(&mut self, thing: Entity, at: Vec3, rotation: Quat) { + if let Ok(mut transform) = self.game.world.entities.get::<&mut Transform>(thing) { + transform.translation = at; + transform.rotation = rotation; + } + } + + /// The height of whatever is under a place: the ground, a floor, a truck's tray, a + /// thing lying there. + pub fn surface_below(&self, from: Vec3) -> Option { + self.physics.borrow().ground_below(from) + } + + /// The height of whatever of the scene itself is under a place: its land and what is + /// built on it, and nothing that moves. + pub fn fixed_below(&self, from: Vec3) -> Option { + self.physics.borrow().fixed_below(from) + } + + /// The height of the land itself under a place, whatever stands on it. + pub fn land_below(&self, from: Vec3) -> Option { + self.physics.borrow().land_below(from) + } + + /// Where the player's car is, and how it is turned. + pub fn car_pose(&self) -> Option<(Vec3, Quat)> { + let car = self.player.as_ref().filter(|player| player.car)?; + self.thing(car.entity) + } + /// Whether the player is flying the camera, away from whoever they play. pub fn flying(&self) -> bool { self.flying && self.player.is_some() @@ -631,6 +1173,37 @@ impl Play { for action in self.presses.drain(..) { input.press(&action); } + // While the driver is in the car they are not standing anywhere: their body is kept + // well up out of the way, where the car's wheels cannot find it to stand on. + if let (false, Some(walker), Some(car)) = (self.afoot, &self.walker, &self.player) { + let entities = &self.game.world.entities; + let above = entities + .get::<&Transform>(car.entity) + .ok() + .map(|at| at.translation + Vec3::Y * 120.0); + if let Some(above) = above { + if let Ok(mut transform) = entities.get::<&mut Transform>(walker.entity) { + transform.translation = above; + } + self.physics.borrow_mut().place(walker.entity, above); + } + } + // What the driver carries is where it was last said to be, or put away. + if !self.carried.is_empty() { + let entities = &self.game.world.entities; + for &entity in &self.carried { + if let Ok(mut transform) = entities.get::<&mut Transform>(entity) { + match self.carry { + Some((at, turned)) => { + transform.translation = at; + transform.rotation = turned; + } + // Away under the ground. + None => transform.translation.y = -900.0, + } + } + } + } let steps = self.game.frame(seconds, &input); devices.end_frame(); self.animated.borrow_mut().frame( @@ -696,7 +1269,12 @@ impl Play { // The car is not being driven, and its instruments go with the player. self.hud = None; } - let player = self.player.as_ref().filter(|_| !flying)?; + let player = if self.afoot { + &self.walker + } else { + &self.player + }; + let player = player.as_ref().filter(|_| !flying)?; let world = entities .get::<&GlobalTransform>(player.entity) .ok()? @@ -706,15 +1284,40 @@ impl Play { let telemetry = *car.vehicle.telemetry(); let look = drive::Look { back: input.held("look_back"), - around: input.value("look_round"), - over: input.value("look_over"), + // The right stick and the mouse do the same thing: swing the view, which + // then stays where it was put. A stick held over turns it at a steady rate. + around: 0.0, + over: 0.0, + orbit: (input.value("orbit") - input.value("look_round") * STICK_ORBIT) + * seconds as f32, + orbit_up: (input.value("orbit_up") + input.value("look_over") * STICK_ORBIT * 0.6) + * seconds as f32, }; + // A truck is followed from further off than a racing car, and seen out of from + // higher up. + let body = car.vehicle.spec(); + if body.body_size.z > 4.8 || body.centre.y > 0.55 { + let tall = 1.0 + (body.centre.y - 0.4).max(0.0) * 0.8; + self.chase.reach = (body.body_size.z / 4.5).max(1.0) * tall; + self.chase.eyes = Some([ + Vec3::new(0.0, body.body_at.y + body.body_size.y * 0.42, -0.25), + Vec3::new(0.0, body.body_at.y - 0.2, -(body.body_size.z * 0.5 + 0.35)), + ]); + } + let physics = self.physics.borrow(); + let land = |at: Vec3| physics.land_below(at); let shot = self .chase - .frame(world, telemetry.speed, look, seconds as f32); + .frame(world, telemetry.speed, look, seconds as f32, Some(&land)); // Filled in place each frame: the lap's times are copied into what the last frame // had, and the track's name is set once. let hud = self.hud.get_or_insert_with(|| Hud { + afoot: false, + walker: Vec3::ZERO, + walker_yaw: 0.0, + origin: Vec3::ZERO, + rotation: Quat::IDENTITY, + tray: None, telemetry, limit: 0.0, throttle: 0.0, @@ -727,13 +1330,49 @@ impl Play { .map(|track| track.name.clone()) .unwrap_or_default(), view: self.chase.view, + wheels: Default::default(), + forward: Vec3::NEG_Z, + velocity: Vec3::ZERO, + four_wheel_drive: false, + pitch: 0.0, + roll: 0.0, }); + hud.afoot = false; hud.telemetry = telemetry; hud.limit = car.vehicle.spec().engine.limit; hud.throttle = car.controls.throttle; hud.brake = car.controls.brake; hud.steer = car.controls.steer; hud.view = self.chase.view; + hud.four_wheel_drive = car.vehicle.spec().transfer.is_some(); + let (_, rotation, origin) = world.to_scale_rotation_translation(); + // How far its nose is up, and how far it leans to its right, as an inclinometer + // on the dash shows them. + let (_, pitch, roll) = rotation.to_euler(glam::EulerRot::YXZ); + (hud.pitch, hud.roll) = (pitch.to_degrees(), -roll.to_degrees()); + hud.forward = rotation * Vec3::NEG_Z; + (hud.origin, hud.rotation) = (origin, rotation); + hud.tray = car.vehicle.spec().tray; + hud.velocity = hud.forward * telemetry.speed; + let spec = car.vehicle.spec(); + let (front, rear) = spec.static_loads(9.81); + for (index, shown) in hud.wheels.iter_mut().enumerate() { + let wheel = &car.vehicle.wheels[index]; + let axle = spec.axle(index); + let (hub, _) = car.vehicle.wheel_pose(index); + *shown = drive::HudWheel { + at: origin + rotation * (hub - Vec3::Y * axle.radius), + hub, + on_ground: wheel.on_ground, + surface: wheel.surface, + slip: wheel.speed * axle.radius - telemetry.speed, + sink: wheel.sink, + load: wheel.load / if index < 2 { front } else { rear }, + carried: car.vehicle.carried()[index], + radius: axle.radius, + tread: spec.tyre.tread.1, + }; + } match (entities.get::<&Lap>(player.entity).ok(), &mut hud.lap) { (Some(lap), Some(shown)) => shown.clone_from(&lap), (Some(lap), shown) => *shown = Some((*lap).clone()), @@ -746,6 +1385,12 @@ impl Play { }); } let (_, rotation, translation) = world.to_scale_rotation_translation(); + // Out of the car, its instruments are as it was left, and say where its driver is. + if let Some(hud) = self.hud.as_mut().filter(|_| self.afoot) { + hud.afoot = true; + hud.walker = translation; + hud.walker_yaw = rotation.to_euler(EulerRot::YXZ).0; + } Some(View { position: translation + rotation * player.eye, yaw: rotation.to_euler(EulerRot::YXZ).0, diff --git a/crates/solstice-game/src/race.rs b/crates/solstice-game/src/race.rs index 1102a21..6e4a63d 100644 --- a/crates/solstice-game/src/race.rs +++ b/crates/solstice-game/src/race.rs @@ -44,6 +44,10 @@ pub struct Lap { pub valid: bool, /// Whether the last lap finished did. pub last_valid: bool, + /// How many times the car has been put back on the track on the lap being driven, and + /// how many it was on the last lap finished. Each costs time; none costs the lap. + pub resets: u32, + pub last_resets: u32, /// The sector the car is in, from 0. pub sector: usize, /// This lap's sector times so far, and the best there has been of each. @@ -101,6 +105,8 @@ impl Lap { best: None, valid: true, last_valid: true, + resets: 0, + last_resets: 0, sector: 0, splits: Vec::new(), best_splits: vec![None; track.sectors.len() + 1], @@ -113,13 +119,27 @@ impl Lap { } } - /// The car was put back on the track: the lap being driven no longer counts. + /// The car was put back on the track: it is counted, against the lap being driven. The + /// lap still stands. Its lines are still to be crossed in turn, so being put down past + /// one is not having driven to it. pub fn interrupt(&mut self) { - self.valid = false; + if self.current.is_some() { + self.resets += 1; + } self.before = None; self.hint = None; } + /// The section of the lap that is being driven: how far round the lap it starts, and + /// how far round it ends. A car put back on the track is put back in it. + pub fn section(&self, track: &Track) -> (f32, f32) { + let ends = match self.next { + 0 => track.length(), + next => track.sector_start(next), + }; + (track.sector_start(self.sector), ends) + } + /// Follows the car through one step of `seconds`. `off_track` is whether it has all four /// wheels off the track. pub fn step( @@ -175,6 +195,7 @@ impl Lap { self.count += 1; self.last = Some(current); self.last_valid = self.valid; + self.last_resets = self.resets; if self.valid && self.best.is_none_or(|best| current < best) { self.best = Some(current); } @@ -182,6 +203,7 @@ impl Lap { events.push(LapEvent::Started); } self.current = Some(0.0); + self.resets = 0; self.valid = !off_track; self.splits.clear(); self.sector = 0; diff --git a/crates/solstice-game/src/scene.rs b/crates/solstice-game/src/scene.rs index e36766e..b1356ce 100644 --- a/crates/solstice-game/src/scene.rs +++ b/crates/solstice-game/src/scene.rs @@ -27,6 +27,9 @@ pub struct ActorLine { pub settings: Vec<(String, String)>, /// The renderer instances drawing its mesh, once baked. pub instances: Option>, + /// Its model is not in this scene's file but in the one every scene of a game shares, + /// which gives it its instances when the two are read together: `shared`, at the end. + pub shared: bool, } impl ActorLine { @@ -45,8 +48,13 @@ impl ActorLine { yaw_degrees: number(words[4])?, settings: Vec::new(), instances: None, + shared: false, }; for word in &words[5..] { + if *word == "shared" { + actor.shared = true; + continue; + } let (name, value) = word .split_once('=') .ok_or_else(|| format!("`{word}` should be NAME=VALUE"))?; @@ -85,6 +93,9 @@ impl ActorLine { if let Some(instances) = &self.instances { let _ = write!(text, " instances={}+{}", instances.start, instances.len()); } + if self.shared { + text.push_str(" shared"); + } text } } @@ -134,6 +145,9 @@ pub struct SceneGame { pub input: Option, /// The `.track` file, relative to the scene's text file, if the scene is a circuit. pub track: Option, + /// The map of what the ground is made of (`ground.rs`), if the scene has one: it says + /// what each tyre is on, in place of the track. + pub surfaces: Option, } impl SceneGame { @@ -162,6 +176,13 @@ impl SceneGame { game.track = Some(words[1].to_owned()); } "track" => return Err(error("expected `track FILE`".to_owned())), + "surfaces" if words.len() == 2 => { + if game.surfaces.is_some() { + return Err(error("`surfaces` is given twice".to_owned())); + } + game.surfaces = Some(words[1].to_owned()); + } + "surfaces" => return Err(error("expected `surfaces FILE`".to_owned())), other => return Err(error(format!("unknown line `{other}`"))), } } @@ -176,6 +197,9 @@ impl SceneGame { if let Some(track) = &self.track { let _ = writeln!(text, "track {track}"); } + if let Some(surfaces) = &self.surfaces { + let _ = writeln!(text, "surfaces {surfaces}"); + } for actor in &self.actors { text.push_str(&actor.to_text()); text.push('\n'); @@ -202,12 +226,18 @@ pub fn missing_files(files: &[GameFile]) -> Vec { Some(Ok(scene)) => { named.extend(scene.input); named.extend(scene.track); + named.extend(scene.surfaces); for line in scene.actors { let actor = file(&line.file).map(ActorFile::parse); named.push(line.file.clone()); if let Some(Ok(actor)) = actor { let vehicle = actor.vehicle.as_ref().map(|vehicle| &vehicle.path); - let relative = actor.script.iter().chain(&actor.animation).chain(vehicle); + let relative = actor + .script + .iter() + .chain(&actor.animation) + .chain(vehicle) + .chain(&actor.kit); named.extend(relative.map(|name| resolve(&line.file, name))); } } diff --git a/crates/solstice-game/src/track.rs b/crates/solstice-game/src/track.rs index 000142d..e31c356 100644 --- a/crates/solstice-game/src/track.rs +++ b/crates/solstice-game/src/track.rs @@ -547,7 +547,7 @@ pub(crate) mod tests { ("p 0 0 0 1 0 0 6", 1, "expected `p X Y Z"), ("name A\np 0 0 0 2 0 0 6 6", 2, "unit vector"), ("p 0 0 0 1 0 0 6 0", 1, "width must be above 0"), - ("p 0 0 0 1 0 0 6 6 l=mud:3", 1, "not a surface"), + ("p 0 0 0 1 0 0 6 6 l=lava:3", 1, "not a surface"), ("p 0 0 0 1 0 0 6 6 x=kerb:3", 1, "l=... or r=..."), ("p 0 0 0 1 0 0 6 6 l=kerb", 1, "SURFACE:WIDTH"), ("lap 3", 1, "unknown line `lap`"), diff --git a/crates/solstice-game/tests/blows.rs b/crates/solstice-game/tests/blows.rs new file mode 100644 index 0000000..55cc9b5 --- /dev/null +++ b/crates/solstice-game/tests/blows.rs @@ -0,0 +1,230 @@ +//! Blows: a truck driven into things, and what the game measures of it (`impact.rs`). The +//! truck is driven by the game as it is played, on the physics as it is played; nothing +//! here is worked out by hand but what the answer should be. + +use glam::{Mat4, Vec3}; +use solstice_asset::{Collision, CollisionShape, GameFile}; +use solstice_game::drive::Handicap; +use solstice_game::{Devices, Impact, Play, GAME_FILE}; +use solstice_physics::vehicle::VehicleSpec; +use solstice_world::STEP_SECONDS; + +const TRUCK: &str = include_str!("../../solstice-vehicle/tests/wagon.vehicle"); +const ACTOR: &str = "name truck\nmesh wagon.glb 1\nvehicle wagon.vehicle\ncamera 0 1.6 0\n"; +const KEYS: &str = "throttle key KeyW\nbrake key KeyS\nsteer key KeyD\nsteer key KeyA -1\n"; + +/// A flat floor at height zero, 2 km across. +fn floor() -> Collision { + let far = 1000.0; + Collision { + shapes: vec![CollisionShape { + hull: false, + vertices: vec![ + [-far, 0.0, -far], + [far, 0.0, -far], + [far, 0.0, far], + [-far, 0.0, far], + ], + triangles: vec![[0, 2, 1], [0, 3, 2]], + }], + instance_shapes: vec![0], + heightfield: None, + } +} + +fn spec() -> VehicleSpec { + VehicleSpec::parse(TRUCK).expect("the truck's file reads") +} + +/// The truck on the floor at a height, facing -Z, and the scene's blockers. +fn truck(height: f32, blockers: &str) -> Play { + let hubs = spec().hubs(); + let scene = + format!("input keys.input\nactor truck.actor 0 {height} 0 0 instances=1+5\n{blockers}"); + let files: Vec = [ + (GAME_FILE, scene.as_str()), + ("truck.actor", ACTOR), + ("wagon.vehicle", TRUCK), + ("keys.input", KEYS), + ] + .iter() + .map(|(name, text)| GameFile { + name: (*name).to_owned(), + text: (*text).to_owned(), + }) + .collect(); + let placed = Mat4::from_translation(Vec3::Y * height); + // The floor is the scene's first instance, and the truck's body its second. + let baked = move |id: u32| match id { + 0 => Some(Mat4::IDENTITY), + 1 => Some(placed), + 2..=5 => Some(placed * Mat4::from_translation(hubs[id as usize - 2])), + _ => None, + }; + Play::load(&files, baked, Some(&floor())).unwrap_or_else(|e| panic!("{e:?}")) +} + +/// Runs the game, and gives every blow the truck took. +fn run(play: &mut Play, devices: &mut Devices, seconds: f64) -> Vec { + let mut blows = Vec::new(); + for _ in 0..(seconds / STEP_SECONDS).round() as u32 { + play.frame(STEP_SECONDS, devices, |_, _| {}); + blows.extend(play.take_impacts()); + } + blows +} + +/// The hardest blow to the body among some. +fn hardest(blows: &[Impact]) -> Impact { + let body = blows.iter().filter(|blow| blow.wheel.is_none()); + *body + .max_by(|a, b| a.force.total_cmp(&b.force)) + .expect("the body was hit") +} + +/// How fast the truck is going over the ground, in metres a second. +fn speed(play: &Play) -> f32 { + play.hud().expect("it is driven").telemetry.speed +} + +/// Drives at a wall across the road so far ahead, and gives how fast it was going when it +/// got there and every blow from then on. +fn into_a_wall(play: &mut Play, ahead: f32) -> (f32, Vec) { + let nose = spec().body_at.z - spec().body_size.z * 0.5; + let mut devices = Devices::new(); + // Settled on its springs first: it is put down a little above the ground. + let settling = run(play, &mut devices, 1.5); + assert!( + settling.iter().all(|blow| blow.wheel.is_some()), + "standing on its wheels, its body meets nothing: {settling:?}" + ); + devices.key("KeyW", true); + let mut going = 0.0; + for _ in 0..3000 { + let (at, _) = play.car_pose().expect("a truck"); + // A step short of the wall: how fast it is going as it gets there. + if at.z + nose - speed(play) * STEP_SECONDS as f32 * 2.0 < -ahead { + going = speed(play); + break; + } + let before = run(play, &mut devices, STEP_SECONDS); + assert!(before.iter().all(|blow| blow.wheel.is_some()), "{before:?}"); + } + assert!(going > 0.5, "it got to the wall"); + devices.key("KeyW", false); + (going, run(play, &mut devices, 1.0)) +} + +#[test] +fn a_wall_hit_square_on_is_a_blow_to_the_nose_as_hard_as_the_truck_was_going() { + let spec = spec(); + // A wall across the road: slowly, and then three times as fast. + let mut slow = truck(0.1, "blocker 0 1.5 -12 20 3 1 0\n"); + let (crawl, blows) = into_a_wall(&mut slow, 11.5); + let tap = hardest(&blows); + let mut fast = truck(0.1, "blocker 0 1.5 -62 20 3 1 0\n"); + let (going, blows) = into_a_wall(&mut fast, 61.5); + let blow = hardest(&blows); + assert!(going > crawl * 1.5, "{crawl} m/s and then {going} m/s"); + + // It landed on the nose, about the middle of it, and pushed the truck back. + let nose = spec.body_at.z - spec.body_size.z * 0.5; + assert!((blow.at.z - nose).abs() < 0.1, "on its nose: {}", blow.at); + assert!(blow.at.x.abs() < 0.35, "about its middle: {}", blow.at); + assert!(blow.push.z > 0.95, "pushed back: {}", blow.push); + // The wall took all its speed off it, and a little more if it bounced: its impulse is + // its mass times that. + let stopped = spec.mass * going; + assert!( + blow.impulse > stopped * 0.85 && blow.impulse < stopped * 1.35, + "{} N s for {stopped} N s of going", + blow.impulse + ); + // Faster is harder, by as much. + let share = (blow.impulse / tap.impulse) / (going / crawl); + assert!(share > 0.7 && share < 1.4, "{share}"); + // The whole of its nose met the wall: the patch is as wide as the truck, all but, and + // most of the height of its body (it meets a wall a little nose up or nose down). + let across = blow.high.x - blow.low.x; + assert!( + across > spec.body_size.x * 0.8, + "{} to {}", + blow.low, + blow.high + ); + assert!(blow.high.y - blow.low.y > spec.body_size.y * 0.5); + assert!(blow.high.z < nose + 0.3, "and no deeper than its nose"); + // And it has stopped. + assert!(speed(&fast).abs() < 1.0); +} + +#[test] +fn a_post_met_with_one_corner_is_a_blow_to_that_corner() { + let spec = spec(); + // A post a metre square, in front of the truck's right headlamp only. + let mut play = truck(0.1, "blocker 1.1 1.5 -40 1 3 1 0\n"); + let (_, blows) = into_a_wall(&mut play, 39.5); + let blow = hardest(&blows); + let nose = spec.body_at.z - spec.body_size.z * 0.5; + assert!((blow.at.z - nose).abs() < 0.25, "on its nose: {}", blow.at); + assert!(blow.at.x > 0.45, "on its right: {}", blow.at); + // The post is in front of its right side only, and so is the patch. + assert!(blow.low.x > 0.4, "{} to {}", blow.low, blow.high); + assert!(blow.push.z > 0.7, "pushed back: {}", blow.push); +} + +#[test] +fn a_drop_is_a_blow_up_through_the_wheels_and_driving_on_the_flat_is_none() { + // Driven off down the flat for ten seconds: nothing strikes it. + let mut play = truck(0.1, ""); + let mut devices = Devices::new(); + run(&mut play, &mut devices, 1.5); + devices.key("KeyW", true); + let driven = run(&mut play, &mut devices, 10.0); + assert!(driven.is_empty(), "{driven:?}"); + + // Dropped from a height, every wheel is struck, harder than it stands: and from three + // times as high, harder again. + let spec = spec(); + let (front, rear) = spec.static_loads(9.81); + let landing = |height: f32| -> [f32; 4] { + let mut dropped = truck(height, ""); + let blows = run(&mut dropped, &mut Devices::new(), 3.0); + std::array::from_fn(|wheel| { + let struck = blows.iter().filter(|blow| blow.wheel == Some(wheel)); + struck.map(|blow| blow.force).fold(0.0, f32::max) + }) + }; + let (low, high) = (landing(0.8), landing(2.4)); + for wheel in 0..4 { + let rest = if wheel < 2 { front } else { rear }; + assert!(low[wheel] > rest * 2.0, "wheel {wheel}: {} N", low[wheel]); + assert!(high[wheel] > low[wheel] * 1.4, "wheel {wheel}: {high:?}"); + } +} + +#[test] +fn a_handicap_is_felt_at_the_wheel_and_under_the_foot() { + // Two trucks driven off flat out with the wheel straight: one sound, one that pulls to + // its right and has lost half its power. + let drive = |handicap: Option| { + let mut play = truck(0.1, ""); + let mut devices = Devices::new(); + run(&mut play, &mut devices, 1.5); + if let Some(handicap) = handicap { + play.set_handicap(handicap); + } + devices.key("KeyW", true); + run(&mut play, &mut devices, 5.0); + let at = play.car_pose().expect("a truck").0; + (at, speed(&play)) + }; + let (sound, pace) = drive(None); + let (wrecked, slower) = drive(Some(Handicap { + pull: 0.25, + power: 0.5, + })); + assert!(sound.x.abs() < 0.5, "a sound truck runs straight: {sound}"); + assert!(wrecked.x > 2.0, "this one has gone to its right: {wrecked}"); + assert!(slower < pace * 0.85, "{slower} m/s against {pace} m/s"); +} diff --git a/crates/solstice-game/tests/things.rs b/crates/solstice-game/tests/things.rs new file mode 100644 index 0000000..f3424e4 --- /dev/null +++ b/crates/solstice-game/tests/things.rs @@ -0,0 +1,241 @@ +//! Loose things: what is put in a truck's tray lies in it and rides with it, weighs on the +//! truck, and what is put on the ground lies there. + +use glam::{Mat4, Quat, Vec3}; +use solstice_asset::{Collision, CollisionShape, GameFile}; +use solstice_game::{Devices, Play, GAME_FILE}; +use solstice_physics::vehicle::VehicleSpec; +use solstice_world::STEP_SECONDS; + +const TRUCK: &str = include_str!("../../solstice-vehicle/tests/truck.vehicle"); +const ACTOR: &str = "name truck\nmesh truck.glb 1\nvehicle truck.vehicle\ncamera 0 1.6 0\n"; +const KEYS: &str = "throttle key KeyW\nbrake key KeyS\nsteer key KeyD\nsteer key KeyA -1\n"; +const SCENE: &str = "input keys.input\nactor truck.actor 0 0 0 0 instances=1+5\n"; + +/// A flat floor at height zero, 2 km across. +fn floor() -> Collision { + let far = 1000.0; + Collision { + shapes: vec![CollisionShape { + hull: false, + vertices: vec![ + [-far, 0.0, -far], + [far, 0.0, -far], + [far, 0.0, far], + [-far, 0.0, far], + ], + triangles: vec![[0, 2, 1], [0, 3, 2]], + }], + instance_shapes: vec![0], + heightfield: None, + } +} + +fn truck() -> Play { + truck_with("") +} + +/// The truck on the floor, and whatever else the scene's game is given: its blockers. +fn truck_with(more: &str) -> Play { + let spec = VehicleSpec::parse(TRUCK).expect("the truck's file reads"); + let hubs = spec.hubs(); + let scene = format!("{SCENE}{more}"); + let files: Vec = [ + (GAME_FILE, scene.as_str()), + ("truck.actor", ACTOR), + ("truck.vehicle", TRUCK), + ("keys.input", KEYS), + ] + .iter() + .map(|(name, text)| GameFile { + name: (*name).to_owned(), + text: (*text).to_owned(), + }) + .collect(); + let baked = move |id: u32| match id { + 0 | 1 => Some(Mat4::IDENTITY), + 2..=5 => Some(Mat4::from_translation(hubs[id as usize - 2])), + _ => None, + }; + Play::load(&files, baked, Some(&floor())).unwrap_or_else(|e| panic!("{e:?}")) +} + +fn run(play: &mut Play, devices: &mut Devices, seconds: f64) { + for _ in 0..(seconds / STEP_SECONDS).round() as u32 { + play.frame(STEP_SECONDS, devices, |_, _| {}); + } +} + +/// Where a thing is in the truck's own space. +fn aboard(play: &Play, thing: solstice_world::Entity) -> Vec3 { + let (truck, turned) = play.car_pose().expect("a truck"); + let (at, _) = play.thing(thing).expect("the thing"); + turned.inverse() * (at - truck) +} + +#[test] +fn what_is_put_in_the_tray_rides_in_it_and_weighs_on_the_truck() { + let (size, floor) = VehicleSpec::parse(TRUCK) + .expect("reads") + .tray + .expect("it has a tray"); + let inside = |at: Vec3| { + (at.x - floor.x).abs() < size.x * 0.5 + && (at.z - floor.z).abs() < size.z * 0.5 + && at.y > floor.y - 0.05 + && at.y < floor.y + size.y + 0.4 + }; + + // An empty truck settles on its springs: how high it rides. + let mut empty = truck(); + let mut devices = Devices::new(); + run(&mut empty, &mut devices, 3.0); + let unladen = empty.car_pose().expect("a truck").0.y; + + // The same truck with a third of a tonne of gold put in its tray, a nugget at a time. + let mut play = truck(); + run(&mut play, &mut devices, 1.0); + let mut nuggets = Vec::new(); + for index in 0..24 { + let (across, along, up) = (index % 4, index / 4 % 3, index / 12); + let local = floor + + Vec3::new( + (across as f32 - 1.5) * 0.32, + 0.2 + up as f32 * 0.3, + (along as f32 - 1.0) * 0.45, + ); + let (truck, turned) = play.car_pose().expect("a truck"); + nuggets.push(play.add_thing( + truck + turned * local, + Quat::IDENTITY, + Vec3::new(0.2, 0.14, 0.2), + 14.0, + )); + } + run(&mut play, &mut devices, 3.0); + for &nugget in &nuggets { + let at = aboard(&play, nugget); + assert!(inside(at), "at rest, one lies at {at}"); + } + let laden = play.car_pose().expect("a truck").0.y; + assert!( + unladen - laden > 0.004, + "336 kg in the tray sets it lower on its springs: {unladen} empty, {laden} laden" + ); + + // Driven off as hard as it goes, braked as hard as it stops, and swung through a turn. + devices.key("KeyW", true); + run(&mut play, &mut devices, 5.0); + devices.key("KeyW", false); + devices.key("KeyS", true); + run(&mut play, &mut devices, 4.0); + devices.key("KeyS", false); + devices.key("KeyW", true); + run(&mut play, &mut devices, 3.0); + devices.key("KeyD", true); + run(&mut play, &mut devices, 2.5); + devices.key("KeyD", false); + devices.key("KeyW", false); + devices.key("KeyS", true); + run(&mut play, &mut devices, 5.0); + let (truck, _) = play.car_pose().expect("a truck"); + assert!(truck.length() > 30.0, "it went somewhere: {truck}"); + let kept = nuggets + .iter() + .filter(|&&nugget| inside(aboard(&play, nugget))) + .count(); + assert_eq!(kept, nuggets.len(), "every nugget is still in the tray"); +} + +#[test] +fn what_is_put_down_lies_where_it_is_put_and_can_be_taken_away() { + let mut play = truck(); + let mut devices = Devices::new(); + let size = Vec3::new(0.2, 0.14, 0.2); + // Let go a little above the ground, well clear of the truck. + let thing = play.add_thing(Vec3::new(8.0, 0.6, 3.0), Quat::IDENTITY, size, 5.0); + run(&mut play, &mut devices, 2.0); + let (at, _) = play.thing(thing).expect("it is there"); + assert!( + (at.x - 8.0).abs() < 0.05 && (at.z - 3.0).abs() < 0.05, + "it fell straight: {at}" + ); + assert!( + (at.y - size.y * 0.5).abs() < 0.03, + "and lies on the ground: {at}" + ); + // What is under a place is found from above: the thing, and beside it the ground. + let top = play + .surface_below(Vec3::new(8.0, 3.0, 3.0)) + .expect("something is there"); + assert!((top - size.y).abs() < 0.03, "{top}"); + assert!( + play.surface_below(Vec3::new(9.0, 3.0, 3.0)) + .expect("the ground") + .abs() + < 0.01 + ); + // Moved, it is where it was moved to, at rest; taken away, it is gone. + play.move_thing(thing, Vec3::new(-6.0, 0.08, 2.0), Quat::IDENTITY); + run(&mut play, &mut devices, 1.0); + let (at, _) = play.thing(thing).expect("it is there"); + assert!((at.x + 6.0).abs() < 0.05 && at.y < 0.12, "{at}"); + play.remove_thing(thing); + run(&mut play, &mut devices, 0.1); + assert!(play.thing(thing).is_none()); +} + +#[test] +fn what_is_let_go_over_an_open_chest_lies_in_it() { + // A chest as the shed's is to things: a floor, and four sides round what is in it. + // 0.56 across and 1.15 long, its floor 0.128 up and its rim 0.548, well clear of the truck. + let (x, z, floor, rim, side) = (9.0_f32, 4.0_f32, 0.128_f32, 0.548_f32, 0.05_f32); + let mut chest = format!( + "blocker {x} {} {z} 0.56 {floor} 1.15 0 +", + floor * 0.5 + ); + let (middle, high) = ((floor + rim) * 0.5, rim - floor); + for end in [-1.0_f32, 1.0] { + chest += &format!( + "blocker {} {middle} {z} {side} {high} 1.15 0 +", + x + end * 0.255 + ); + chest += &format!( + "blocker {x} {middle} {} 0.46 {high} {side} 0 +", + z + end * 0.55 + ); + } + let mut play = truck_with(&chest); + let mut devices = Devices::new(); + run(&mut play, &mut devices, 0.5); + // Nuggets are let go over it one after another, each put down on what is under it: + // the floor, and then the nuggets already there. + let size = Vec3::new(0.18, 0.12, 0.18); + let mut nuggets = Vec::new(); + for index in 0..10 { + let over = Vec3::new(x, rim + 0.45, z + (index % 5) as f32 * 0.16 - 0.32); + let top = play.surface_below(over).expect("the chest is under it"); + assert!( + top >= floor - 0.01 && top < rim + 0.4, + "it is put on the floor or on a nugget: {top}" + ); + nuggets.push(play.add_thing( + Vec3::new(over.x, top + size.y * 0.5 + 0.03, over.z), + Quat::IDENTITY, + size, + 3.0, + )); + run(&mut play, &mut devices, 0.4); + } + run(&mut play, &mut devices, 3.0); + for nugget in nuggets { + let (at, _) = play.thing(nugget).expect("it is there"); + assert!( + (at.x - x).abs() < 0.23 && (at.z - z).abs() < 0.53 && at.y > floor && at.y < rim + 0.3, + "one lies outside the chest, at {at}" + ); + } +} diff --git a/crates/solstice-import/src/lib.rs b/crates/solstice-import/src/lib.rs index 173fb48..8563b94 100644 --- a/crates/solstice-import/src/lib.rs +++ b/crates/solstice-import/src/lib.rs @@ -64,6 +64,10 @@ pub struct Imported { /// The instances of each named node, at the node's own origin, for placing the pieces of /// a modular kit one by one. Mesh and material numbers refer to `scene`. pub parts: HashMap>, + /// What the node of each of `scene`'s instances is called, in their order, or nothing + /// for one with no name: so that a thing made of named pieces, as a truck is, can have + /// some shown and some not. + pub names: Vec, /// Things in the file that the result does not reproduce. pub warnings: Vec, } @@ -156,7 +160,9 @@ pub fn import_gltf( let mut keys: Vec = Vec::new(); let mut instances = Vec::with_capacity(placements.len()); let mut parts: HashMap> = HashMap::new(); + let mut names = Vec::with_capacity(placements.len()); for placement in &placements { + names.push(placement.node_name.clone().unwrap_or_default()); let material = materials.slot(&document, placement.material, &mut warnings); // A skinned mesh is drawn as its skeleton says: glTF ignores where its node stands. let skinned = options.skinned && placement.bound; @@ -274,6 +280,7 @@ pub fn import_gltf( ..Default::default() }, parts, + names, warnings, }) } diff --git a/crates/solstice-import/src/material.rs b/crates/solstice-import/src/material.rs index e9e0b53..8c2eb2e 100644 --- a/crates/solstice-import/src/material.rs +++ b/crates/solstice-import/src/material.rs @@ -179,11 +179,6 @@ impl<'a> MaterialTable<'a> { fn convert(&mut self, source: &gltf::Material<'_>, warnings: &mut Vec) -> Material { let name = source.name().unwrap_or("unnamed"); - if source.alpha_mode() == gltf::material::AlphaMode::Blend { - warnings.push(format!( - "material '{name}': alpha mode Blend is drawn as opaque" - )); - } if source.emissive_texture().is_some() { warnings.push(format!( "material '{name}': emissive texture is ignored, only its factor is used" @@ -252,15 +247,22 @@ impl<'a> MaterialTable<'a> { Material { base_color: pbr.base_color_factor(), emissive: [er, eg, eb], - flags: if source.double_sided() { - Material::TWO_SIDED - } else { - 0 - } | if masked.is_some() { - Material::MASKED - } else { - 0 - }, + flags: named_flags(source.name()) + | if source.double_sided() { + Material::TWO_SIDED + } else { + 0 + } + | if masked.is_some() { + Material::MASKED + } else { + 0 + } + | if source.alpha_mode() == gltf::material::AlphaMode::Blend { + Material::GLASS + } else { + 0 + }, roughness: pbr.roughness_factor(), metallic: pbr.metallic_factor(), uv_scale: 1.0, @@ -494,3 +496,17 @@ fn texel(image: &ImageData, x: i64, y: i64) -> [f32; 4] { ], } } + +/// What a material's name says of it: one whose name begins `paint` is the paint of +/// something driven, and one whose name begins `inside` is in its cab or under its bonnet +/// (`Material::PAINT`, `Material::INSIDE`). A model is given such names when it is made ready. +pub(crate) fn named_flags(name: Option<&str>) -> u32 { + let name = name.unwrap_or("").to_ascii_lowercase(); + if name.starts_with("paint") { + Material::PAINT + } else if name.starts_with("inside") { + Material::INSIDE + } else { + 0 + } +} diff --git a/crates/solstice-import/src/streamed.rs b/crates/solstice-import/src/streamed.rs index 7c42d23..e04a9e8 100644 --- a/crates/solstice-import/src/streamed.rs +++ b/crates/solstice-import/src/streamed.rs @@ -1103,11 +1103,6 @@ fn convert_material( }; }; let name = source.name().unwrap_or("unnamed"); - if source.alpha_mode() == gltf::material::AlphaMode::Blend { - warnings.push(format!( - "material '{name}': alpha mode Blend is drawn as opaque" - )); - } let glow_layer = source .emissive_texture() .filter(|_| textures) @@ -1170,11 +1165,18 @@ fn convert_material( 1.0 } }), - flags: if source.double_sided() { - Material::TWO_SIDED - } else { - 0 - } | if masked { Material::MASKED } else { 0 } + flags: crate::material::named_flags(source.name()) + | if source.double_sided() { + Material::TWO_SIDED + } else { + 0 + } + | if masked { Material::MASKED } else { 0 } + | if source.alpha_mode() == gltf::material::AlphaMode::Blend { + Material::GLASS + } else { + 0 + } | glow_layer.map_or(0, |layer| (layer + 1) << Material::GLOW_SHIFT), roughness: pbr.roughness_factor() * if has_roughness_map { 0.5 } else { 1.0 }, metallic: pbr.metallic_factor(), diff --git a/crates/solstice-import/src/tests.rs b/crates/solstice-import/src/tests.rs index 341b691..f3962fd 100644 --- a/crates/solstice-import/src/tests.rs +++ b/crates/solstice-import/src/tests.rs @@ -443,13 +443,18 @@ fn material_sample(image: &ImageData) -> u8 { material::sample(image, 0.3, 0.3, 4)[0] } +/// A material whose alpha is blended is glass: seen through, by its colour's alpha. #[test] -fn unsupported_features_are_reported_not_hidden() { +fn a_blended_material_is_glass() { let dir = TempDir::new(); - let materials = r#", "materials": [{"alphaMode": "BLEND", "doubleSided": true}]"#; + let materials = r#", "materials": [{"alphaMode": "BLEND", "doubleSided": true, + "pbrMetallicRoughness": {"baseColorFactor": [0.1, 0.1, 0.1, 0.25]}}]"#; let path = write_model(&dir, r#"[{"mesh": 0}]"#, r#", "material": 0"#, materials); - let warnings = import(&path).warnings.join("\n"); - assert!(warnings.contains("Blend"), "{warnings}"); + let imported = import(&path); + let glass = &imported.scene.materials[0]; + assert_eq!(glass.flags & Material::GLASS, Material::GLASS); + assert_eq!(glass.base_color[3], 0.25); + assert!(imported.warnings.iter().all(|w| !w.contains("Blend"))); } /// Writes a model with two images, each a flat 2x2 colour, and the given materials over them, @@ -703,6 +708,7 @@ fn small_model(meshes: usize, materials: usize, layers: usize) -> Imported { Imported { scene, parts: HashMap::from([("kit_wall_01".to_string(), vec![piece])]), + names: Vec::new(), warnings: Vec::new(), } } @@ -1158,7 +1164,7 @@ fn what_blends_and_glows_becomes_cards_and_emissive_maps_are_kept() { assert_eq!(leftmost, 1.0); } -/// Without textures there is nothing to draw a card with, so it is left as it was. +/// Without textures there is nothing to draw a card with: it is a surface still, and glass. #[test] fn without_textures_a_blended_material_stays_solid() { let dir = TempDir::new(); @@ -1167,7 +1173,6 @@ fn without_textures_a_blended_material_stays_solid() { let report = streamed::bake_large(&path, &output, &large_options()).unwrap(); assert_eq!((report.glow_maps, report.cards), (0, 0)); assert_eq!(report.instances, 2); - assert!(report.warnings.iter().any(|w| w.contains("Blend"))); assert!(report .warnings .iter() diff --git a/crates/solstice-physics/src/car.rs b/crates/solstice-physics/src/car.rs index 030cf18..6fd3015 100644 --- a/crates/solstice-physics/src/car.rs +++ b/crates/solstice-physics/src/car.rs @@ -13,8 +13,9 @@ use crate::{from_vector, to_pose, to_vector, Physics, GRAVITY}; use glam::{Quat, Vec3}; use rapier3d::prelude::*; -use solstice_vehicle::{Asked, Contact, Controls, Driver, Ground, Surface, Vehicle}; +use solstice_vehicle::{Asked, Contact, Controls, Driver, Ground, Press, Ruts, Surface, Vehicle}; use solstice_world::{Entity, Transform, World, STEP_SECONDS}; +use std::cell::RefCell; /// Makes an actor a car. Its `Transform` is the car's origin: on the ground under its middle. #[derive(Clone, Debug)] @@ -50,12 +51,81 @@ pub(crate) struct CarStep { turned: Vec3, /// Whether its dynamics have once failed, and been said to. failed: bool, + /// What hitting things did to it in the step: see [`Knock`]. + knock: Knock, +} + +/// What hitting things did to a car in one step, in the world: how much it changed the +/// velocity of its centre of mass, in metres a second, and its spin, in radians a second. +/// Nothing of it is the car's own doing: its wheels, springs and engine, and gravity, are +/// its dynamics', and this is what the walls, the ground under its body and whatever else +/// it met added to them. Times its mass and its inertia, it is the blow's impulse. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Knock { + pub velocity: Vec3, + pub spin: Vec3, } /// The scene, as a wheel finds it. struct SceneGround<'a> { queries: QueryPipeline<'a>, surfaces: Option<&'a dyn Fn(Vec3) -> Surface>, + /// What has been pressed into the ground: a tyre stands in the ruts kept here, and + /// presses them deeper. + ruts: &'a RefCell, +} + +/// How near the ground a car's belly must be to drag in it, in metres, and how far down it +/// presses what it drags through. +const BELLY_NEAR: f32 = 0.02; +const BELLY_PRESSES: f32 = 0.025; + +/// Where a car's belly is down on soft ground, between its ruts, it drags the crown flat: +/// a broad, shallow smear of churned soil under its middle, front to back. +fn drag_belly(ground: &SceneGround<'_>, vehicle: &Vehicle, body: &solstice_vehicle::Body) { + let spec = vehicle.spec(); + let (up, forward) = (body.up(), body.forward()); + let along = glam::Vec2::new(forward.x, forward.z).normalize_or_zero(); + if up.y < 0.5 || along == glam::Vec2::ZERO { + return; + } + // The underside of its body, at three places along its middle. + let under = spec.body_at.y - spec.body_size.y * 0.5; + const ABOVE: f32 = 0.4; + for share in [-0.3, 0.0, 0.3] { + let at = body.position + + body.rotation * Vec3::new(0.0, under, spec.body_at.z + share * spec.body_size.z); + let from = at + up * ABOVE; + let Some(contact) = ground.cast(from, -up, ABOVE + BELLY_NEAR) else { + continue; + }; + if !contact.surface.is_soft() { + continue; + } + let point = from - up * contact.distance; + // How far down the belly is against the ground as it was made, and whether the + // ground as it now is has already been pressed out of its way. + let down = ABOVE - contact.distance + BELLY_PRESSES; + if down <= ground.rut(point) { + continue; + } + let soil = contact.surface.soil(vehicle.wetness()); + let place = glam::Vec2::new(point.x, point.z); + ground.press(&Press { + from: place, + to: place, + along, + half_width: spec.body_size.x * 0.3, + half_length: spec.body_size.z * 0.2, + depth: down, + berm: 0.0, + phase: (0.0, 0.0), + print: 0.0, + wet: soil.wet, + stays: soil.stays, + churn: soil.churn, + }); + } } impl Ground for SceneGround<'_> { @@ -76,6 +146,51 @@ impl Ground for SceneGround<'_> { .map_or(Surface::Asphalt, |surface| surface(point)), }) } + + fn rut(&self, at: Vec3) -> f32 { + self.ruts.borrow().depth(at.x, at.z) + } + + fn press(&self, press: &Press) { + self.ruts.borrow_mut().press(press); + } +} + +/// A box with a hollow cut out of it: the boxes that are left, under the hollow and over +/// it, to each side of it, before it and behind. A box the hollow does not reach is left +/// whole. Each box and the hollow are their least corner and their greatest. +pub(crate) fn hollowed(solid: (Vec3, Vec3), hollow: (Vec3, Vec3)) -> Vec<(Vec3, Vec3)> { + let (low, high) = solid; + let (from, to) = (hollow.0.max(low), hollow.1.min(high)); + if from.cmpge(to).any() { + return vec![solid]; + } + let left = [ + // Under it and over it, the whole of the box across and along. + (low, Vec3::new(high.x, from.y, high.z)), + (Vec3::new(low.x, to.y, low.z), high), + // To each side of it, as high as it is. + ( + Vec3::new(low.x, from.y, low.z), + Vec3::new(from.x, to.y, high.z), + ), + ( + Vec3::new(to.x, from.y, low.z), + Vec3::new(high.x, to.y, high.z), + ), + // Before it and behind, as high and as wide as it is. + ( + Vec3::new(from.x, from.y, low.z), + Vec3::new(to.x, to.y, from.z), + ), + ( + Vec3::new(from.x, from.y, to.z), + Vec3::new(to.x, to.y, high.z), + ), + ]; + left.into_iter() + .filter(|(low, high)| (*high - *low).min_element() > 1e-3) + .collect() } impl Physics { @@ -125,18 +240,103 @@ impl Physics { ); // Rounded, so that it slides along a wall's joins rather than catching on them. const ROUNDING: f32 = 0.08; - let half = (spec.body_size * 0.5 - Vec3::splat(ROUNDING)).max(Vec3::splat(0.01)); - let collider = self.colliders.insert_with_parent( - ColliderBuilder::round_cuboid(half.x, half.y, half.z, ROUNDING) - .translation(to_vector(spec.body_at)) - .density(0.0) - .friction(0.35) - .restitution(0.15) - .user_data(crate::entity_data(entity)), - handle, - &mut self.bodies, + // Its boxes: one, or, with a tray, the cab and what is under and round the tray. + // Each its middle, its half size, and whether it is rounded. + let (low, high) = ( + spec.body_at - spec.body_size * 0.5, + spec.body_at + spec.body_size * 0.5, ); - self.owners.insert(collider, (entity, false)); + let boxed = |low: Vec3, high: Vec3, round: bool| { + ((low + high) * 0.5, (high - low) * 0.5, round) + }; + let boxes = match spec.tray { + None => vec![boxed(low, high, true)], + Some((size, floor)) => { + // The tray's inside: from, and to. Its sides are the body's own, its + // front is the cab's back, and its tailgate is as thick as a hand. + const GATE: f32 = 0.1; + let inside_low = floor - Vec3::new(size.x, 0.0, size.z) * 0.5; + let inside_high = floor + Vec3::new(size.x * 0.5, size.y, size.z * 0.5); + let back = inside_high.z + GATE; + let (left, right) = ( + low.x.min(inside_low.x - GATE), + high.x.max(inside_high.x + GATE), + ); + vec![ + boxed(low, Vec3::new(high.x, high.y, inside_low.z), true), + // Under its floor. + boxed( + Vec3::new(low.x, low.y.min(floor.y - GATE), inside_low.z), + Vec3::new(high.x, floor.y, back), + false, + ), + // Its two sides, and its tailgate. + boxed( + Vec3::new(left, floor.y, inside_low.z), + Vec3::new(inside_low.x, inside_high.y, back), + false, + ), + boxed( + Vec3::new(inside_high.x, floor.y, inside_low.z), + Vec3::new(right, inside_high.y, back), + false, + ), + boxed( + Vec3::new(inside_low.x, floor.y, inside_high.z), + Vec3::new(inside_high.x, inside_high.y, back), + false, + ), + ] + } + }; + // Where it has holds it is hollow: each is cut out of whatever boxes it is in, + // with a wall left round it, so that what is put in one is shut in. + let boxes = if spec.holds.is_empty() { + boxes + } else { + const WALL: f32 = 0.04; + let mut solid: Vec<(Vec3, Vec3)> = boxes + .iter() + .map(|(middle, half, _)| (*middle - *half, *middle + *half)) + .collect(); + for (size, floor) in &spec.holds { + let hollow = ( + (*floor - Vec3::new(size.x, 0.0, size.z) * 0.5).max(low + WALL), + (*floor + Vec3::new(size.x * 0.5, size.y, size.z * 0.5)).min(high - WALL), + ); + solid = solid + .into_iter() + .flat_map(|solid| hollowed(solid, hollow)) + .collect(); + } + solid + .into_iter() + .map(|(low, high)| boxed(low, high, false)) + .collect() + }; + let mut colliders = Vec::new(); + for (middle, half, round) in boxes { + let shape = if round { + let half = (half - Vec3::splat(ROUNDING)).max(Vec3::splat(0.01)); + ColliderBuilder::round_cuboid(half.x, half.y, half.z, ROUNDING) + } else { + ColliderBuilder::cuboid(half.x, half.y, half.z) + }; + let collider = self.colliders.insert_with_parent( + shape + .translation(to_vector(middle)) + .density(0.0) + // Two tonnes and more of truck lands and stays; a racing car's shell + // skips off what it touches. + .friction(if spec.mass > 2000.0 { 0.55 } else { 0.35 }) + .restitution(if spec.mass > 2000.0 { 0.02 } else { 0.15 }) + .user_data(crate::entity_data(entity)), + handle, + &mut self.bodies, + ); + self.owners.insert(collider, (entity, false)); + colliders.push(collider); + } self.actors.insert( entity, crate::Body { @@ -145,7 +345,7 @@ impl Physics { character: None, at: transform.translation, rotation: transform.rotation, - colliders: vec![collider], + colliders, }, ); self.cars.insert(entity, CarStep::default()); @@ -190,12 +390,14 @@ impl Physics { filter, ), surfaces: self.surfaces.as_deref(), + ruts: &self.ruts, }; let controls = car .driver .drive(&car.asked, &car.vehicle, &body, GRAVITY, dt); car.vehicle.step(&mut body, &controls, &ground, dt); car.controls = controls; + drag_belly(&ground, &car.vehicle, &body); } if !(body.position.is_finite() && body.velocity.is_finite() && body.spin.is_finite()) { // Its wheels and engine may hold the same nonsense, so the car starts again from @@ -226,6 +428,7 @@ impl Physics { carried: moved / dt, turned: (body.rotation * before.rotation.inverse()).to_scaled_axis() / dt, failed: self.cars.get(&entity).is_some_and(|step| step.failed), + knock: Knock::default(), }; let rigid = self.bodies.get_mut(handle).expect("found above"); rigid.set_linvel(to_vector(step.carried), true); @@ -237,7 +440,7 @@ impl Physics { /// After the physics step: each car's velocity is what its dynamics ended with, and what /// hitting things did to it. pub(crate) fn settle_cars(&mut self) { - for (entity, step) in &self.cars { + for (entity, step) in &mut self.cars { let Some(rigid) = self .actors .get(entity) @@ -249,6 +452,92 @@ impl Physics { let twisted = from_vector(rigid.angvel()) - step.turned; rigid.set_linvel(to_vector(step.velocity + knocked), true); rigid.set_angvel(to_vector(step.spin + twisted), true); + step.knock = Knock { + velocity: knocked, + spin: twisted, + }; + } + } + + /// What hitting things did to a car in the latest step: for what a blow does to it. + pub fn car_knock(&self, entity: Entity) -> Option { + self.cars.get(&entity).map(|step| step.knock) + } + + /// Where a car's body is touching things, as of the latest step: each place on its + /// body, in the car's own space. Between them they are the patch of it a blow lands on: + /// its whole nose against a wall, one corner of it against a post. + pub fn car_touches(&self, entity: Entity) -> Vec { + let mut touches = Vec::new(); + let Some(actor) = self.actors.get(&entity) else { + return touches; + }; + for &handle in &actor.colliders { + let Some(collider) = self.colliders.get(handle) else { + continue; + }; + let within = collider + .position_wrt_parent() + .map_or(Vec3::ZERO, |pose| from_vector(pose.translation)); + for pair in self.narrow_phase.contact_pairs_with(handle) { + let first = pair.collider1 == handle; + // As the solver had them: those are the ones that say what each pushed with. + for manifold in pair.solver_manifolds() { + for point in &manifold.points { + // What pushed the car this step, or is touching it, or all but: not + // what is only near enough to be watched. (A car that arrives fast + // is pushed by places it had not yet reached when they were found.) + if point.data.impulse <= 0.0 && point.dist > 0.03 { + continue; + } + let on = if first { + point.local_p1 + } else { + point.local_p2 + }; + touches.push(within + from_vector(on)); + } + } + } } + touches + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// How much room boxes take up, between them. + fn volume(boxes: &[(Vec3, Vec3)]) -> f32 { + boxes + .iter() + .map(|(low, high)| { + let size = *high - *low; + size.x * size.y * size.z + }) + .sum() + } + + #[test] + fn a_box_hollowed_is_what_is_left_round_the_hollow() { + let solid = (Vec3::new(-1.0, 0.0, -2.0), Vec3::new(1.0, 1.5, 2.0)); + // A hollow in the middle of it leaves six boxes, which with it make up the whole. + let hollow = (Vec3::new(-0.5, 0.4, -0.5), Vec3::new(0.2, 1.0, 0.6)); + let left = hollowed(solid, hollow); + assert_eq!(left.len(), 6); + let hole = (hollow.1 - hollow.0).to_array().iter().product::(); + assert!((volume(&left) + hole - volume(&[solid])).abs() < 1e-4); + // Nothing left is in the hollow: its middle is in none of them. + let middle = (hollow.0 + hollow.1) * 0.5; + assert!(left + .iter() + .all(|(low, high)| !(middle.cmpgt(*low).all() && middle.cmplt(*high).all()))); + // One that reaches the top of the box leaves nothing over it; one outside the box + // leaves the box as it was. + let open = (Vec3::new(-0.5, 0.4, -0.5), Vec3::new(0.2, 2.0, 0.6)); + assert_eq!(hollowed(solid, open).len(), 5); + let away = (Vec3::new(3.0, 0.0, 0.0), Vec3::new(4.0, 1.0, 1.0)); + assert_eq!(hollowed(solid, away), [solid]); } } diff --git a/crates/solstice-physics/src/lib.rs b/crates/solstice-physics/src/lib.rs index d0c9fac..fb1bd62 100644 --- a/crates/solstice-physics/src/lib.rs +++ b/crates/solstice-physics/src/lib.rs @@ -14,7 +14,7 @@ pub mod car; -pub use car::Car; +pub use car::{Car, Knock}; pub use solstice_vehicle as vehicle; use glam::{Mat4, Quat, Vec3}; @@ -34,8 +34,9 @@ use std::sync::mpsc::{channel, Receiver}; pub const GRAVITY: f32 = 9.81; /// The steepest slope, in degrees, a character can walk up. pub const MAX_SLOPE_DEGREES: f32 = 45.0; -/// The highest step, in metres, a character climbs without jumping. -pub const MAX_STEP: f32 = 0.35; +/// The highest step, in metres, a character climbs without jumping: a kerb, a verandah's +/// edge, a ledge of rock on a track. +pub const MAX_STEP: f32 = 0.6; /// How fast a character may fall, in metres a second. pub const TERMINAL_SPEED: f32 = 50.0; @@ -101,6 +102,8 @@ struct CharacterState { collider: ColliderHandle, /// Falling speed, negative downward. vertical: f32, + /// Whether it stood on something at the end of the last step: only then can it jump. + grounded: bool, } /// The simulation of one world. @@ -132,6 +135,8 @@ pub struct Physics { cars: BTreeMap, /// What the ground is made of at a place, for tyres. surfaces: Option solstice_vehicle::Surface>>, + /// What tyres have pressed into the ground: the ruts they stand in, which stay. + ruts: std::cell::RefCell, /// Problems with the scene's shapes, for the viewer to show. pub warnings: Vec, } @@ -205,6 +210,7 @@ impl Physics { _tears: tears, cars: BTreeMap::new(), surfaces: None, + ruts: Default::default(), warnings: Vec::new(), } } @@ -334,6 +340,51 @@ impl Physics { .map(|(_, distance)| from.y - distance) } + /// The height of whatever of the scene itself is under a place: its land, its floors and + /// its walls, and nothing that moves, a car or an actor or a thing lying about. For what + /// falls off a car to come to rest on. From inside something solid, as what comes off + /// against a wall is, it is what that stands on. + pub fn fixed_below(&self, from: Vec3) -> Option { + let queries = self.broad_phase.as_query_pipeline( + self.narrow_phase.query_dispatcher(), + &self.bodies, + &self.colliders, + QueryFilter::only_fixed().exclude_sensors(), + ); + let ray = Ray::new(to_vector(from), -Vector::Y); + queries + .cast_ray(&ray, 10_000.0, false) + .map(|(_, distance)| from.y - distance) + } + + /// The height of the land itself under a place, if the scene has a grid of heights: + /// not of a wall, a tree or a car that stands on it. For a camera to keep above. + pub fn land_below(&self, from: Vec3) -> Option { + let land = + |_: ColliderHandle, collider: &Collider| collider.shape().as_heightfield().is_some(); + let queries = self.broad_phase.as_query_pipeline( + self.narrow_phase.query_dispatcher(), + &self.bodies, + &self.colliders, + QueryFilter::new().exclude_sensors().predicate(&land), + ); + let ray = Ray::new(to_vector(from), -Vector::Y); + queries + .cast_ray(&ray, 10_000.0, true) + .map(|(_, distance)| from.y - distance) + } + + /// What tyres have pressed into the ground, which every car's wheels read and press + /// further (`solstice_vehicle::rut`): for whoever draws it. + pub fn ruts(&self) -> std::cell::Ref<'_, solstice_vehicle::Ruts> { + self.ruts.borrow() + } + + /// The same, to change: to forget every rut, or to lay what was thrown where it landed. + pub fn ruts_mut(&mut self) -> &mut solstice_vehicle::Ruts { + self.ruts.get_mut() + } + /// One fixed step: takes in new actors, moves kinematic ones to where their transforms say, /// steps the simulation, walks the characters, and writes back what physics moved. pub fn step(&mut self, world: &mut World) { @@ -341,6 +392,9 @@ impl Physics { self.take_in_cars(world); self.follow_transforms(world); self.drive_cars(world); + self.ruts + .get_mut() + .advance(solstice_world::STEP_SECONDS as f32); self.pipeline.step( to_vector(Vec3::new(0.0, -GRAVITY, 0.0)), &self.params, @@ -422,7 +476,12 @@ impl Physics { ) { let kind = collider.map_or(BodyKind::Kinematic, |c| c.kind); let builder = match kind { - BodyKind::Dynamic(_) => RigidBodyBuilder::dynamic(), + // What is loose may be small and heavy, and is carried on trucks: it is not to + // pass through a floor in a step, and it comes to rest where it is put. + BodyKind::Dynamic(_) => RigidBodyBuilder::dynamic() + .ccd_enabled(true) + .linear_damping(0.05) + .angular_damping(0.6), _ => RigidBodyBuilder::kinematic_position_based(), }; let handle = self.bodies.insert( @@ -443,7 +502,7 @@ impl Physics { ); } if let BodyKind::Dynamic(mass) = kind { - shape = shape.mass(mass); + shape = shape.mass(mass).friction(0.9).restitution(0.0); } shape }; @@ -485,6 +544,7 @@ impl Physics { CharacterState { collider, vertical: 0.0, + grounded: false, } }); self.actors.insert( @@ -554,11 +614,22 @@ impl Physics { let collider = &self.colliders[state.collider]; let shape = collider.shared_shape().clone(); let pose = *collider.position(); - let walk = world + let wanted = world .entities .get::<&Walk>(entity) - .map_or(Vec3::ZERO, |w| Vec3::new(w.0.x, 0.0, w.0.z)); + .map_or(Vec3::ZERO, |w| w.0); + let walk = Vec3::new(wanted.x, 0.0, wanted.z); + // A jump: what a walk says of going up is the speed to leave the ground with, + // and is heeded only on the ground. + if wanted.y > 0.0 && state.grounded { + state.vertical = wanted.y; + } let falling = (state.vertical - GRAVITY * dt).max(-TERMINAL_SPEED); + // Going up, it is not held down to the ground it has just left. + let mut controller = self.controller; + if falling > 0.0 { + controller.snap_to_ground = None; + } let desired = walk * dt + Vec3::Y * falling * dt; let filter = QueryFilter::new() .exclude_sensors() @@ -569,15 +640,10 @@ impl Physics { &self.colliders, filter, ); - let moved = self.controller.move_shape( - dt, - &queries, - &*shape, - &pose, - to_vector(desired), - |_| {}, - ); - state.vertical = if moved.grounded { 0.0 } else { falling }; + let moved = + controller.move_shape(dt, &queries, &*shape, &pose, to_vector(desired), |_| {}); + state.grounded = moved.grounded && falling <= 0.0; + state.vertical = if state.grounded { 0.0 } else { falling }; let next = rigid.translation() + moved.translation; self.bodies .get_mut(body.handle) @@ -587,6 +653,21 @@ impl Physics { } } + /// Puts a walking character somewhere else: it is not walked there, it is there. + pub fn place(&mut self, entity: Entity, at: Vec3) { + let Some(body) = self.actors.get_mut(&entity) else { + return; + }; + if let Some(rigid) = self.bodies.get_mut(body.handle) { + rigid.set_translation(to_vector(at), true); + rigid.set_next_kinematic_translation(to_vector(at)); + } + body.at = at; + if let Some(state) = body.character.as_mut() { + state.vertical = 0.0; + } + } + /// Writes back to their transforms what physics moved. fn write_back(&mut self, world: &mut World) { for (&entity, body) in &mut self.actors { diff --git a/crates/solstice-physics/tests/walking.rs b/crates/solstice-physics/tests/walking.rs index 9792c48..c7f4792 100644 --- a/crates/solstice-physics/tests/walking.rs +++ b/crates/solstice-physics/tests/walking.rs @@ -131,9 +131,13 @@ fn a_character_walks_as_far_as_it_is_told() { "two metres in a second at 2 m/s: {at}" ); assert!(at.y.abs() < 0.05 && at.z.abs() < 1.0e-3, "{at}"); - // Walking up is not a thing: only across the ground counts. + // What a walk says of going up is a jump: off the ground, and back down onto it. walk(&mut game, hero, Vec3::new(0.0, 5.0, 0.0)); - steps(&mut game, 30); + steps(&mut game, 12); + let up = place(&game, hero).y; + assert!(up > 0.3, "it has left the ground: {up}"); + walk(&mut game, hero, Vec3::ZERO); + steps(&mut game, 120); assert!(place(&game, hero).y.abs() < 0.05, "{}", place(&game, hero)); } diff --git a/crates/solstice-procgen/src/bush.rs b/crates/solstice-procgen/src/bush.rs new file mode 100644 index 0000000..fca4109 --- /dev/null +++ b/crates/solstice-procgen/src/bush.rs @@ -0,0 +1,563 @@ +//! The ground of the Australian bush: what a track through dry eucalypt forest is made of, and +//! what lies either side of it. +//! +//! * [`red_clay`]: a bush track's surface. Hard orange-red clay with ironstone gravel pressed +//! into it, washed fines in its hollows, and a crazing of fine cracks where it has baked. +//! * [`bush_mud`]: the same clay, wet and churned by wheels: dark, slick, in clods and smears, +//! with water standing in its lowest hollows. +//! * [`gum_litter`]: the floor of a eucalypt forest. Gum trees shed all year: long sickle +//! leaves that dry tan, grey and rust, ribbons of bark, twigs and gumnuts, over pale, dry, +//! stony soil. Nothing rots as it does in a damp oak wood, so the litter is pale, not black. +//! * [`tussock`]: the ground of a grassy clearing in summer: straw-pale dead grass lying in +//! swirls over the same soil, bare in patches. +//! +//! Each is built as the surfaces of [`crate::surfaces`] are: its real shape first, in metres, +//! and its colour from that shape. + +use crate::field::{billow, fbm, smoothstep, Blades, Cells, Field, Leaves, Stones}; +use crate::surface::{Shade, Surface, TILE_METRES}; +use glam::Vec3; + +fn mix(a: Vec3, b: Vec3, t: f32) -> Vec3 { + a + (b - a) * t.clamp(0.0, 1.0) +} + +fn mix_f(a: f32, b: f32, t: f32) -> f32 { + a + (b - a) * t.clamp(0.0, 1.0) +} + +/// A linear albedo. +fn tone(r: f32, g: f32, b: f32) -> Vec3 { + Vec3::new(r, g, b) +} + +/// The surfaces of this module, by name. +pub fn by_name(name: &str, seed: u32) -> Option { + Some(match name { + "red_clay" => red_clay(seed), + "bush_mud" => bush_mud(seed), + "gum_litter" => gum_litter(seed), + "tussock" => tussock(seed), + _ => return None, + }) +} + +/// The names [`by_name`] knows. +pub const NAMES: [&str; 4] = ["red_clay", "bush_mud", "gum_litter", "tussock"]; + +/// A bush track's hard clay: orange-red, gravelly, dusty, cracked where it has baked. +pub fn red_clay(seed: u32) -> Surface { + let stones = |period: i32, radius: f32, coverage: f32, offset: u32| Stones { + period, + seed: seed + offset, + radius, + tile_metres: TILE_METRES, + coverage, + }; + // Ironstone gravel, the "buckshot" of lateritic clay: dark red-brown, rounded, mostly + // pressed in level with the surface by the wheels. And a few larger stones standing proud. + let gravel = stones(110, 0.014, 0.42, 300); + let grit = stones(260, 0.0065, 0.7, 301); + let cobbles = stones(22, 0.045, 0.1, 302); + let lay = fbm(2, 4, seed + 303); + let forms = fbm(11, 4, seed + 304); + // Fines washed into the hollows by the last rain, smooth and paler; dust lying on the rest. + let washed = fbm(7, 4, seed + 305).unit().smooth(0.5, 0.68); + let dust = fbm(160, 2, seed + 306); + let crazing = Cells { + period: 46, + seed: seed + 307, + }; + let baked = fbm(4, 4, seed + 308).unit().smooth(0.42, 0.7); + let hue = fbm(3, 5, seed + 309).unit(); + let stain = fbm(9, 4, seed + 310).unit(); + let mottle = fbm(60, 3, seed + 311).unit(); + Surface::shaped( + move |u, v| { + let smooth = washed.at(u, v); + // The clay itself: packed, with shallow forms a wheel's width across. + let clay = lay.at(u, v) * 0.03 + forms.at(u, v) * 0.012; + // Fine cracks, a few millimetres deep, where it has dried hard. + let crack = crazing.sample(u, v).border(); + let cracked = (1.0 - smoothstep(0.0, 0.05, crack)) * baked.at(u, v) * (1.0 - smooth); + let ground = clay - cracked * 0.004 + dust.at(u, v) * 0.0006 * (1.0 - smooth); + let cobble = cobbles.sample(u, v); + if cobble.height > 0.022 { + return ( + ground + (cobble.height - 0.022) * 0.9, + 20.0 + cobble.id.min(0.99), + ); + } + // Gravel is worn in almost flush, and silted over in the washed hollows. + let pebble = gravel.sample(u, v); + if pebble.height > 0.004 && smooth < 0.75 { + return (ground + pebble.height * 0.45, 10.0 + pebble.id.min(0.99)); + } + let speck = grit.sample(u, v); + if speck.height > 0.002 && smooth < 0.5 { + return (ground + speck.height * 0.5, 10.0 + speck.id.min(0.99)); + } + ( + ground, + cracked.min(0.99) + if smooth > 0.5 { 2.0 } else { 0.0 }, + ) + }, + move |u, v, tag, relief| { + let exposure = smoothstep(-0.006, 0.006, relief.medium); + if tag >= 20.0 { + // A stone: grey-brown quartzite or rusty ironstone, dusted with the clay. + let id = tag - 20.0; + let stone = if id < 0.6 { + mix(tone(0.2, 0.16, 0.13), tone(0.34, 0.29, 0.24), id / 0.6) + } else { + mix( + tone(0.17, 0.07, 0.04), + tone(0.26, 0.11, 0.05), + (id - 0.6) / 0.4, + ) + }; + return Shade { + color: mix(stone, tone(0.36, 0.17, 0.07), 0.3 * (1.0 - exposure)) + * (0.75 + exposure * 0.25), + roughness: 0.82, + cavity: 0.55 + exposure * 0.45, + }; + } + if tag >= 10.0 { + // Ironstone gravel: dark red-brown to almost black, with the odd pale quartz. + let id = tag - 10.0; + let pebble = if id > 0.9 { + tone(0.5, 0.45, 0.38) + } else { + mix(tone(0.075, 0.035, 0.022), tone(0.2, 0.085, 0.04), id / 0.9) + }; + return Shade { + color: mix(pebble, tone(0.36, 0.17, 0.07), 0.35) * (0.8 + exposure * 0.2), + roughness: 0.78, + cavity: 0.6 + exposure * 0.4, + }; + } + let washed_here = tag >= 2.0; + let cracked = tag.fract(); + // Orange-red clay, yellower in some stretches and redder in others, darker where + // the damp lingers and paler on the dusty high points. + let clay = mix( + tone(0.33, 0.125, 0.045), + tone(0.42, 0.2, 0.075), + hue.at(u, v), + ); + let stained = mix( + clay, + clay * tone(0.72, 0.66, 0.62), + smoothstep(0.5, 0.85, stain.at(u, v)), + ); + let dusty = mix(stained * 0.86, stained * tone(1.12, 1.1, 1.08), exposure); + let mut color = dusty * (0.9 + mottle.at(u, v) * 0.2); + if washed_here { + // Settled fines: pale, even, very fine. + color = mix(color, tone(0.47, 0.27, 0.13), 0.55); + } + color *= 1.0 - cracked * 0.35; + Shade { + color, + roughness: if washed_here { 0.86 } else { 0.95 }, + cavity: (0.7 + exposure * 0.3) * (1.0 - cracked * 0.4), + } + }, + ) +} + +/// The track's clay wet and churned: dark, slick clods and smears, with water in the hollows. +pub fn bush_mud(seed: u32) -> Surface { + // Clods thrown up by tyres, large and small, on a churned bed; smears where a tyre slid. + let clods = |period: i32, radius: f32, coverage: f32, offset: u32| Stones { + period, + seed: seed + offset, + radius, + tile_metres: TILE_METRES, + coverage, + }; + let lumps = clods(26, 0.06, 0.38, 320); + let crumbs = clods(70, 0.022, 0.5, 321); + let lay = fbm(3, 4, seed + 322); + let churn = billow(14, 4, seed + 323); + let ripple = fbm(45, 3, seed + 324); + let fine = fbm(220, 2, seed + 325); + // The lowest of it holds water. + let hue = fbm(4, 4, seed + 326).unit(); + let drying = fbm(6, 4, seed + 327).unit().smooth(0.55, 0.8); + let stones = clods(34, 0.02, 0.06, 328); + Surface::shaped( + move |u, v| { + let bed = lay.at(u, v) * 0.045 + churn.at(u, v) * 0.03 + ripple.at(u, v) * 0.006; + let lump = lumps.sample(u, v); + let crumb = crumbs.sample(u, v); + let clod = (lump.height * 0.5).max(crumb.height * 0.55); + let height = bed + clod + fine.at(u, v) * 0.0008; + let stone = stones.sample(u, v); + if stone.height > 0.01 { + return (height + stone.height * 0.4, 10.0 + stone.id.min(0.99)); + } + (height, if clod > 0.004 { 1.0 } else { 0.0 }) + }, + move |u, v, tag, relief| { + // Water lies where the mud is lowest over a hand's breadth and more. + let pooled = + smoothstep(-0.012, -0.03, relief.broad) * smoothstep(0.004, -0.004, relief.medium); + let high = smoothstep(-0.01, 0.014, relief.medium); + if tag >= 10.0 { + let id = tag - 10.0; + let stone = mix(tone(0.07, 0.04, 0.03), tone(0.16, 0.1, 0.07), id); + return Shade { + color: stone * (0.7 + high * 0.3), + roughness: 0.4, + cavity: 0.6 + high * 0.4, + }; + } + // Wet clay: a deep red-brown, a little paler and duller where its tops are drying. + let wet = mix( + tone(0.075, 0.032, 0.015), + tone(0.13, 0.058, 0.026), + hue.at(u, v), + ); + let dried = drying.at(u, v) * high; + let mud = mix(wet, tone(0.25, 0.12, 0.055), dried * 0.7); + let shaded = mud * (0.62 + high * 0.38); + // Standing water: brown, and as smooth as water is. + let water = tone(0.085, 0.05, 0.028); + Shade { + color: mix(shaded, water, pooled), + roughness: mix_f(mix_f(0.3, 0.62, dried), 0.05, pooled), + cavity: mix_f(0.45 + high * 0.55, 1.0, pooled), + } + }, + ) +} + +/// The floor of a eucalypt forest: gum leaves, ribbons of bark, twigs and gumnuts on dry soil. +pub fn gum_litter(seed: u32) -> Surface { + // Gum leaves: long, a hand's length, lying flat and dry. + let leaves = Leaves { + period: 44, + seed: seed + 340, + density: 3, + length: 0.13, + depth: 0.014, + tile_metres: TILE_METRES, + }; + // Ribbons of shed bark, as long as a forearm and a thumb wide, curling as they dry. + let ribbons = Blades { + period: 9, + seed: seed + 341, + density: 1, + length: 0.55, + width: 0.03, + rise: 0.014, + flow: fbm(2, 2, seed + 342), + spread: 0.5, + tile_metres: TILE_METRES, + }; + let twigs = Blades { + period: 12, + seed: seed + 343, + density: 1, + length: 0.34, + width: 0.006, + rise: 0.012, + flow: fbm(3, 2, seed + 344), + spread: 0.5, + tile_metres: TILE_METRES, + }; + // Gumnuts and small stones. + let nuts = Stones { + period: 60, + seed: seed + 345, + radius: 0.009, + tile_metres: TILE_METRES, + coverage: 0.16, + }; + let lay = fbm(3, 4, seed + 346); + let crumbs = billow(52, 3, seed + 347); + let grain = fbm(260, 2, seed + 348); + // Where the litter lies thin, the soil shows: on rises, and where the wind has swept it. + let thin = fbm(6, 5, seed + 349).unit().smooth(0.45, 0.7); + let fade = fbm(5, 4, seed + 350).unit(); + let spots = fbm(140, 3, seed + 351); + let soil_hue = fbm(4, 4, seed + 352).unit(); + Surface::shaped( + move |u, v| { + let ground = lay.at(u, v) * 0.03 + crumbs.at(u, v) * 0.006 + grain.at(u, v) * 0.0005; + let twig = twigs.sample(u, v); + if twig.id > 0.55 && twig.height > 0.0 { + return (ground + 0.018 + twig.height * 0.5, 30.0 + twig.id * 0.99); + } + let ribbon = ribbons.sample(u, v); + if ribbon.id > 0.45 && ribbon.height > 0.0 { + // Curled across its width: its edges stand a little higher than its middle. + return ( + ground + 0.012 + ribbon.height * 0.7, + 50.0 + (ribbon.id * 15.0).floor() + ribbon.along.min(0.99), + ); + } + let bare = thin.at(u, v); + let leaf = leaves.sample(u, v); + if leaf.height > 0.0 && leaf.age > bare * 0.9 { + let tag = (leaf.id * 15.0).floor() * 16.0 + + (leaf.age * 15.0).floor() + + leaf.vein.min(0.99); + return (ground + leaf.height, tag + 1000.0); + } + let nut = nuts.sample(u, v); + if nut.height > 0.003 { + return (ground + nut.height * 0.8, 20.0 + nut.id.min(0.99)); + } + (ground, -1.0) + }, + move |u, v, tag, relief| { + let shelter = smoothstep(-0.01, 0.006, relief.medium); + if tag < 0.0 { + // Dry soil: pale grey-brown, a little orange with the clay under it. + let soil = mix( + tone(0.15, 0.105, 0.07), + tone(0.24, 0.15, 0.085), + soil_hue.at(u, v), + ) * (0.85 + grain.at(u, v) * 0.3); + return Shade { + color: soil * (0.6 + shelter * 0.4), + roughness: 0.96, + cavity: 0.4 + shelter * 0.45, + }; + } + if tag < 30.0 { + // A gumnut, or a small stone. + let id = tag - 20.0; + let nut = mix(tone(0.07, 0.05, 0.035), tone(0.2, 0.15, 0.1), id); + return Shade { + color: nut * (0.7 + shelter * 0.3), + roughness: 0.8, + cavity: 0.5 + shelter * 0.5, + }; + } + if tag < 50.0 { + // A twig: grey where it has weathered, red-brown where it is newly fallen. + let id = tag - 30.0; + let twig = mix(tone(0.2, 0.17, 0.14), tone(0.12, 0.06, 0.035), id); + return Shade { + color: twig * (0.8 + spots.at(u, v) * 0.4) * (0.6 + shelter * 0.4), + roughness: 0.85, + cavity: 0.5 + shelter * 0.5, + }; + } + if tag < 1000.0 { + // A ribbon of bark: cream or pinkish inside when new, grey as it weathers, + // with long streaks of rust. + let packed = tag - 50.0; + let (id, along) = (packed.floor() / 15.0, packed.fract()); + let new = mix( + tone(0.42, 0.3, 0.2), + tone(0.3, 0.16, 0.09), + smoothstep(0.3, 0.9, id), + ); + let old = tone(0.27, 0.24, 0.2); + let bark = mix(new, old, smoothstep(0.35, 0.75, fade.at(u + id, v))); + let streak = 0.85 + 0.3 * spots.at(u * 0.3 + id, v * 3.0); + return Shade { + color: bark * streak * (0.7 + shelter * 0.3) * (0.9 + along * 0.15), + roughness: 0.8, + cavity: 0.55 + shelter * 0.45, + }; + } + let packed = tag - 1000.0; + let vein = packed.fract(); + let whole = packed.floor(); + let id = (whole / 16.0).floor() / 15.0; + let age = (whole % 16.0) / 15.0; + // Dry gum leaves: tan and straw, pinkish rust, bleached grey, and a few still olive. + let fresh = if id < 0.4 { + mix(tone(0.27, 0.18, 0.09), tone(0.36, 0.26, 0.13), id / 0.4) + } else if id < 0.68 { + mix( + tone(0.24, 0.1, 0.05), + tone(0.33, 0.15, 0.075), + (id - 0.4) / 0.28, + ) + } else if id < 0.9 { + mix( + tone(0.2, 0.18, 0.15), + tone(0.31, 0.28, 0.23), + (id - 0.68) / 0.22, + ) + } else { + mix( + tone(0.1, 0.12, 0.055), + tone(0.17, 0.18, 0.085), + (id - 0.9) / 0.1, + ) + }; + // The oldest have gone to grey-brown and begun to break up. + let weathered = mix( + fresh, + tone(0.17, 0.135, 0.1), + smoothstep(0.55, 0.0, age) * 0.7, + ); + let blotched = weathered * (0.86 + spots.at(u + id, v - id) * 0.32); + Shade { + color: mix(blotched, blotched * 0.78, vein) * (0.58 + shelter * 0.42), + roughness: 0.74, + cavity: 0.45 + shelter * 0.55, + } + }, + ) +} + +/// A grassy clearing's ground in summer: straw lying in swirls over dry soil. +pub fn tussock(seed: u32) -> Surface { + // Long dead blades, lying over as wind and animals have left them. + let straw = Blades { + period: 64, + seed: seed + 360, + density: 4, + length: 0.24, + width: 0.0048, + rise: 0.02, + flow: fbm(2, 3, seed + 361), + spread: 0.3, + tile_metres: TILE_METRES, + }; + // Shorter, finer thatch under them. + let thatch = Blades { + period: 150, + seed: seed + 362, + density: 2, + length: 0.08, + width: 0.003, + rise: 0.006, + flow: fbm(5, 2, seed + 363), + spread: 0.5, + tile_metres: TILE_METRES, + }; + let lay = fbm(3, 4, seed + 364); + let crumbs = billow(60, 3, seed + 365); + // Bare patches, where the grass has died back to the soil. + let bare = fbm(8, 5, seed + 366).unit().smooth(0.56, 0.74); + let green = fbm(4, 4, seed + 367).unit().smooth(0.6, 0.82); + let hue = fbm(6, 4, seed + 368).unit(); + let grain = fbm(240, 2, seed + 369); + let pebbles = Stones { + period: 48, + seed: seed + 370, + radius: 0.012, + tile_metres: TILE_METRES, + coverage: 0.12, + }; + Surface::shaped( + move |u, v| { + let ground = lay.at(u, v) * 0.03 + crumbs.at(u, v) * 0.005; + let open = bare.at(u, v); + let blade = straw.sample(u, v); + if blade.height > 0.0 && blade.id > open * 0.95 { + let tag = (blade.id * 255.0).floor() + blade.along.min(0.99); + return (ground + 0.01 + blade.height, 1000.0 + tag); + } + let under = thatch.sample(u, v); + if under.height > 0.0 && under.id > open * 0.9 { + return (ground + 0.003 + under.height, 500.0 + under.id.min(0.99)); + } + let pebble = pebbles.sample(u, v); + if pebble.height > 0.004 { + return (ground + pebble.height * 0.6, 10.0 + pebble.id.min(0.99)); + } + (ground + grain.at(u, v) * 0.0006, -1.0) + }, + move |u, v, tag, relief| { + let shade = smoothstep(-0.012, 0.012, relief.medium); + if tag < 0.0 { + let soil = mix( + tone(0.17, 0.11, 0.065), + tone(0.27, 0.15, 0.075), + hue.at(u, v), + ) * (0.85 + grain.at(u, v) * 0.3); + return Shade { + color: soil * (0.6 + shade * 0.4), + roughness: 0.96, + cavity: 0.4 + shade * 0.4, + }; + } + if tag < 500.0 { + let id = tag - 10.0; + let stone = mix(tone(0.11, 0.06, 0.04), tone(0.3, 0.24, 0.19), id); + return Shade { + color: stone * (0.75 + shade * 0.25), + roughness: 0.82, + cavity: 0.6 + shade * 0.4, + }; + } + if tag < 1000.0 { + // Thatch: old, grey straw. + let id = tag - 500.0; + let old = mix(tone(0.2, 0.165, 0.11), tone(0.3, 0.25, 0.16), id); + return Shade { + color: old * (0.5 + shade * 0.5), + roughness: 0.9, + cavity: 0.4 + shade * 0.5, + }; + } + let packed = tag - 1000.0; + let (id, along) = (packed.floor() / 255.0, packed.fract()); + // Straw: pale gold to bleached, a few blades still green at the root in the + // damper patches. + let dead = mix(tone(0.36, 0.28, 0.13), tone(0.52, 0.44, 0.25), id); + let alive = mix(tone(0.1, 0.14, 0.04), tone(0.2, 0.22, 0.07), id); + let living = green.at(u, v) * smoothstep(0.55, 0.1, along) * 0.8; + let body = mix(dead, alive, living); + let lit = mix(body * 0.7, body * 1.08, smoothstep(0.0, 0.6, along)); + Shade { + color: lit * (0.55 + shade * 0.45), + roughness: 0.72 + id * 0.15, + cavity: 0.45 + shade * 0.55, + } + }, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A surface's mean albedo, linear, from its smallest mip but one. + fn mean(name: &str) -> Vec3 { + let layer = by_name(name, 0).unwrap().bake(128); + let mip = &layer.color_mips[layer.color_mips.len() - 1]; + let linear = |c: u8| (c as f32 / 255.0).powf(2.2); + Vec3::new(linear(mip[0]), linear(mip[1]), linear(mip[2])) + } + + #[test] + fn every_name_is_a_surface() { + for name in NAMES { + assert!(by_name(name, 3).is_some(), "{name}"); + } + assert!(by_name("bitumen", 0).is_none()); + } + + #[test] + fn the_clay_is_red_and_the_mud_is_dark() { + let clay = mean("red_clay"); + assert!(clay.x > clay.y * 1.6 && clay.y > clay.z * 1.5, "{clay}"); + assert!((0.2..0.45).contains(&clay.x), "{clay}"); + let mud = mean("bush_mud"); + assert!(mud.x < clay.x * 0.5, "mud {mud}, clay {clay}"); + assert!(mud.x > mud.z, "{mud}"); + } + + #[test] + fn dry_litter_and_straw_are_pale_not_green() { + for name in ["gum_litter", "tussock"] { + let color = mean(name); + assert!(color.x > color.y && color.y > color.z, "{name}: {color}"); + assert!((0.12..0.45).contains(&color.x), "{name}: {color}"); + } + // Straw is paler than leaf litter. + assert!(mean("tussock").y > mean("gum_litter").y); + } +} diff --git a/crates/solstice-procgen/src/foliage/bark.rs b/crates/solstice-procgen/src/foliage/bark.rs index 09fffcc..c50eae9 100644 --- a/crates/solstice-procgen/src/foliage/bark.rs +++ b/crates/solstice-procgen/src/foliage/bark.rs @@ -39,16 +39,29 @@ pub enum Bark { /// Weeping willow: grey-brown and deeply furrowed like an oak's, its corky ridges paler and /// yellower, with tan inner bark showing in the furrows and moss where it stays damp. Willow, + /// A smooth-barked gum, such as a manna gum: bark shed each year in long plates, leaving + /// a patchwork of cream, grey, salmon and olive, streaked down the stem, with the dark + /// edges of plates not yet let go. + Gum, + /// A stringybark, such as messmate: thick, soft and fibrous, in long strings that run up + /// the stem between deep furrows, grey-brown outside and red-brown within. + Stringybark, + /// An ironbark: hard, deeply furrowed and nearly black, never shed, with dark red kino + /// in its furrows. A tree that has been through a fire looks much the same. + Ironbark, } impl Bark { - pub const ALL: [Self; 6] = [ + pub const ALL: [Self; 9] = [ Self::Oak, Self::Birch, Self::Fir, Self::Pine, Self::Beech, Self::Willow, + Self::Gum, + Self::Stringybark, + Self::Ironbark, ]; /// The name of this bark in the surface library. @@ -60,6 +73,9 @@ impl Bark { Self::Pine => "pine_bark", Self::Beech => "beech_bark", Self::Willow => "willow_bark", + Self::Gum => "gum_bark", + Self::Stringybark => "stringybark", + Self::Ironbark => "ironbark", } } @@ -76,6 +92,9 @@ impl Bark { Self::Pine => pine(seed), Self::Beech => beech(seed), Self::Willow => willow(seed), + Self::Gum => gum(seed), + Self::Stringybark => stringybark(seed), + Self::Ironbark => ironbark(seed), } .with_tile_metres(BARK_TILE_METRES) } @@ -193,6 +212,113 @@ fn willow(seed: u32) -> Surface { ) } +fn stringybark(seed: u32) -> Surface { + furrowed( + seed + 500, + Furrowed { + // Weathered grey-brown strings, warmer where they are newly split. + ridge: (Vec3::new(0.15, 0.115, 0.085), Vec3::new(0.25, 0.165, 0.1)), + // Red-brown inner bark deep in the furrows. + fissure: Vec3::new(0.1, 0.04, 0.018), + lichen: 0.12, + moss: 0.0, + }, + ) +} + +fn ironbark(seed: u32) -> Surface { + furrowed( + seed + 600, + Furrowed { + // Charcoal, a little brown where the light catches a ridge. + ridge: ( + Vec3::new(0.028, 0.025, 0.024), + Vec3::new(0.07, 0.056, 0.048), + ), + // Kino, the dark red gum that bleeds into the furrows and sets hard. + fissure: Vec3::new(0.05, 0.012, 0.008), + lichen: 0.06, + moss: 0.0, + }, + ) +} + +/// A smooth gum's bark: blotches of different ages, as the old bark comes away in sheets of +/// no particular shape and bares the new under it. +/// +/// Nothing in it is regular. Where each blotch ends is where a broad, soft noise crosses a +/// level, so the patches are the shapes of a map's contours, long along the stem, each inside +/// or beside the next, as on a manna gum or a snow gum. A grid of plates, however jittered, +/// lines up into stripes round a thin stem. +fn gum(seed: u32) -> Surface { + // How long ago the bark here was bared: broad shapes a hand wide and a forearm long, with + // smaller ones on them, and the whole pushed about so that no edge runs straight. + let broad = noise(2, 2, 3, seed + 701); + let lesser = noise(4, 5, 3, seed + 702); + let push = noise(3, 3, 2, seed + 703); + let age = move |u: f32, v: f32| { + let (du, dv) = (push.at(u, v) * 0.012, push.at(v + 0.31, u + 0.67) * 0.05); + broad.at(u + du, v + dv) * 0.68 + lesser.at(u + du, v + dv) * 0.32 + }; + // The levels the blotches end at, youngest bark first. + const LEVELS: [f32; 4] = [-0.3, -0.04, 0.2, 0.42]; + let fine = noise(60, 40, 3, seed + 704); + let grain = noise(160, 500, 2, seed + 705); + let weather = noise(1, 1, 3, seed + 706); + // Faint long streaks where rain runs down the stem, and darker stains below a wound. + let runs = noise(5, 1, 3, seed + 707); + let stains = noise(3, 1, 4, seed + 708); + let specks = noise(40, 60, 2, seed + 709); + Surface::shaped( + move |u, v| { + let a = age(u, v); + // Which blotch, and how near its edge: there the older bark still overlaps. + let band = LEVELS.iter().filter(|&&level| a > level).count(); + let edge = LEVELS + .iter() + .map(|&level| (a - level).abs()) + .fold(f32::MAX, f32::min); + let lip = 1.0 - smoothstep(0.0, 0.035, edge); + // Each older layer stands a fraction of a millimetre proud of the one it covers. + let height = band as f32 * 0.0005 - 0.0007 * lip + + 0.0004 * fine.at(u, v) + + 0.0001 * grain.at(u, v); + (height, band as f32 + lip.min(0.99)) + }, + move |u, v, tag, relief: Relief| { + let band = tag.floor() as usize; + let lip = tag.fract(); + // Newly bared bark is cream, nearly white; it greys in the weather; the oldest + // still on the tree is salmon and tan, and what is about to fall, grey-brown. + let color = [ + Vec3::new(0.63, 0.58, 0.47), + Vec3::new(0.52, 0.5, 0.43), + Vec3::new(0.42, 0.41, 0.37), + Vec3::new(0.47, 0.32, 0.22), + Vec3::new(0.3, 0.27, 0.23), + ][band.min(4)]; + let mut color = color + * (1.0 + 0.1 * weather.at(u, v)) + * (1.0 + 0.06 * fine.at(u, v)) + * (1.0 + 0.05 * runs.at(u, v)); + let stain = smoothstep(0.45, 0.85, stains.at(u, v)); + color = color.lerp(color * Vec3::new(0.62, 0.54, 0.47), stain * 0.5); + // Flecks of dark where insects and lichen have been. + let fleck = smoothstep(0.55, 0.8, specks.at(u, v)) * 0.18; + color = color.lerp(Vec3::new(0.14, 0.11, 0.09), fleck); + // An edge is the shadowed underside of the sheet above it. + color = color.lerp(color * 0.55, lip * 0.5); + color *= 1.0 + (relief.fine * 150.0).clamp(-0.12, 0.12); + Shade { + color, + // Smooth, with a faint waxy sheen where it is newest. + roughness: 0.6 + 0.07 * band as f32, + cavity: 1.0 - 0.35 * lip, + } + }, + ) +} + fn furrowed(seed: u32, tones: Furrowed) -> Surface { let shape = oak_shape(seed); let shade_shape = oak_shape(seed); diff --git a/crates/solstice-procgen/src/foliage/leaf.rs b/crates/solstice-procgen/src/foliage/leaf.rs index 7b34cde..9089b72 100644 --- a/crates/solstice-procgen/src/foliage/leaf.rs +++ b/crates/solstice-procgen/src/foliage/leaf.rs @@ -29,15 +29,31 @@ pub enum LeafKind { /// An oak's leaf: leathery, deep green and glossy above, with a strong pale midrib, widest /// beyond its middle. Oak, + /// A eucalypt's adult leaf: a long, narrow sickle that hangs edge-on to the sun, leathery, + /// a dull grey-green the same on both faces, with the new growth bronze. + Gum, + /// A wattle's: feathery sprays of tiny grey-green leaflets, with its blossom among them, + /// balls of gold. Built as sprays, as needles are. + Wattle, + /// A fern's frond: leaflets either side of a long arching stalk, fresh green. Built as a + /// spray, the whole frond one. + Fern, + /// A grass tree's: a blade as long as an arm and thin as a skewer, arching out of the + /// crown, grey-green, with the old ones straw. + GrassTree, } impl LeafKind { - pub const ALL: [Self; 5] = [ + pub const ALL: [Self; 9] = [ Self::Broadleaf, Self::Birch, Self::Needles, Self::Willow, Self::Oak, + Self::Gum, + Self::Wattle, + Self::Fern, + Self::GrassTree, ]; /// The name of this kind's atlas. @@ -48,9 +64,19 @@ impl LeafKind { Self::Needles => "fir_needles", Self::Willow => "willow_leaves", Self::Oak => "oak_leaves", + Self::Gum => "gum_leaves", + Self::Wattle => "wattle_leaves", + Self::Fern => "fern_fronds", + Self::GrassTree => "grass_tree_leaves", } } + /// Whether this kind is built as a spray: small leaves splayed either side of a shoot, as + /// a fir's needles are, rather than as one leaf. + pub fn is_spray(self) -> bool { + matches!(self, Self::Needles | Self::Wattle | Self::Fern) + } + pub fn by_name(name: &str) -> Option { Self::ALL.into_iter().find(|kind| kind.name() == name) } @@ -68,6 +94,11 @@ impl LeafKind { Self::Willow => (0.6, 0.95), // Widest beyond the middle, where an oak leaf's largest lobes are. Self::Oak => (0.75, 0.6), + // A lance: widest a quarter of the way along, then a long, fine point. + Self::Gum => (0.5, 1.35), + Self::Wattle | Self::Fern => (0.2, 0.25), + // A blade: as wide all the way, drawn to a point only at its very end. + Self::GrassTree => (0.1, 0.45), }; let peak = a / (a + b); let max = peak.powf(a) * (1.0 - peak).powf(b); @@ -78,7 +109,8 @@ impl LeafKind { /// its tip. A narrow leaf needs one; a broad one two, to round its outline. pub fn rows(self) -> &'static [f32] { match self { - Self::Willow => &[0.42], + Self::Willow | Self::Gum => &[0.42], + Self::GrassTree => &[0.35, 0.7], _ => &[0.32, 0.68], } } @@ -92,6 +124,11 @@ impl LeafKind { // Long leaves arc over under their own weight. Self::Willow => 0.3, Self::Oak => 0.14, + Self::Gum => 0.34, + Self::Wattle => 0.12, + // A frond arches right over, and a grass tree's blade further still. + Self::Fern => 0.42, + Self::GrassTree => 0.6, } } @@ -99,9 +136,10 @@ impl LeafKind { pub fn fold(self) -> f32 { match self { Self::Broadleaf | Self::Birch | Self::Oak => 0.25, - Self::Willow => 0.35, + Self::Willow | Self::Gum => 0.35, // A shoot's needles splay out in a shallow V on either side. - Self::Needles => 0.45, + Self::Needles | Self::Wattle | Self::Fern => 0.45, + Self::GrassTree => 0.6, } } @@ -109,9 +147,15 @@ impl LeafKind { match self { Self::Broadleaf => veined(seed, BROADLEAF, 7.0, 0.45), Self::Birch => veined(seed, BIRCH, 9.0, 0.4), - Self::Needles => needles(seed), + Self::Needles => needles(seed, NEEDLES), Self::Willow => veined(seed, WILLOW, 13.0, 0.42), Self::Oak => veined(seed, OAK, 6.0, 0.36), + // A gum leaf's side veins are fine and close, and run at a slant to a vein inside + // its edge; its surface is waxy. + Self::Gum => veined(seed, GUM, 22.0, 0.48), + Self::Wattle => needles(seed, WATTLE), + Self::Fern => needles(seed, FERN), + Self::GrassTree => veined(seed, GRASS_TREE, 1.0, 0.55), } } } @@ -155,6 +199,36 @@ const OAK: [Vec3; LEAF_VARIANTS as usize] = [ Vec3::new(0.150, 0.125, 0.035), ]; +/// Gum leaves are a dull grey-green, olive in shade and bluer in the open, and the new growth +/// at the shoots' ends is bronze-red. +const GUM: [Vec3; LEAF_VARIANTS as usize] = [ + Vec3::new(0.040, 0.066, 0.034), + Vec3::new(0.056, 0.084, 0.044), + Vec3::new(0.075, 0.098, 0.060), + Vec3::new(0.150, 0.085, 0.045), +]; +/// A wattle's leaflets are a soft blue-grey green, and its blossom is gold. +const WATTLE: [Vec3; LEAF_VARIANTS as usize] = [ + Vec3::new(0.038, 0.070, 0.045), + Vec3::new(0.052, 0.088, 0.058), + Vec3::new(0.070, 0.105, 0.062), + Vec3::new(0.620, 0.420, 0.030), +]; +/// Fern fronds are a fresh, clear green, the old ones going bronze. +const FERN: [Vec3; LEAF_VARIANTS as usize] = [ + Vec3::new(0.030, 0.080, 0.018), + Vec3::new(0.045, 0.105, 0.022), + Vec3::new(0.062, 0.125, 0.028), + Vec3::new(0.160, 0.110, 0.040), +]; +/// A grass tree's blades are grey-green, and the dead ones in its skirt are straw. +const GRASS_TREE: [Vec3; LEAF_VARIANTS as usize] = [ + Vec3::new(0.050, 0.085, 0.034), + Vec3::new(0.066, 0.100, 0.040), + Vec3::new(0.085, 0.115, 0.045), + Vec3::new(0.300, 0.240, 0.110), +]; + /// Column and position across it at `u`: (variant, -1..1 across the leaf). fn column(u: f32) -> (usize, f32) { let variant = ((u * LEAF_VARIANTS as f32) as usize).min(LEAF_VARIANTS as usize - 1); @@ -196,18 +270,20 @@ fn veined( /// Fans of needles, each from where it leaves the shoot (v = 0) to its tip (v = 1): several /// needles converging on the tip, dark in the gaps between them and browner at the base, with /// a paler, waxier tip on young growth. -fn needles(seed: u32) -> Surface { +fn needles(seed: u32, colors: [Vec3; LEAF_VARIANTS as usize]) -> Surface { let shade = fbm(16, 3, seed + 1); Surface::new(0.004, move |u, v| { let (variant, across) = column(u); // Five needles across the fan, closing up towards its tip. let needle = 0.5 + 0.5 * (across * 2.5 * TAU / (1.0 - v * 0.85)).cos(); let gap = smoothstep(0.35, 0.0, needle) * (1.0 - smoothstep(0.75, 1.0, v)); - let mut color = NEEDLES[variant] * (1.0 + 0.2 * shade.at(u, v)); + let mut color = colors[variant] * (1.0 + 0.2 * shade.at(u, v)); color *= 0.8 + 0.35 * needle; + // Browner where it leaves the shoot, but for blossom, which is gold all through. + let woody = if colors[variant].x > 0.4 { 0.0 } else { 0.5 }; color = color.lerp( Vec3::new(0.05, 0.045, 0.025), - (1.0 - smoothstep(0.0, 0.25, v)) * 0.5, + (1.0 - smoothstep(0.0, 0.25, v)) * woody, ); color *= 1.0 - 0.55 * gap; Texel { @@ -252,10 +328,12 @@ mod tests { for kind in LeafKind::ALL { let layer = kind.atlas(0).bake(64); let top = layer.color_mips.last().unwrap(); - // Real leaves reflect about 0.05 to 0.2 in green. + // Real leaves reflect about 0.05 to 0.2 in green. A wattle's gold blossom, a + // quarter of its atlas, lifts its mean. let green = (top[1] as f32 / 255.0).powf(2.2); + let most = if kind == LeafKind::Wattle { 0.3 } else { 0.22 }; assert!( - (0.03..0.22).contains(&green), + (0.03..most).contains(&green), "{kind:?}: green albedo {green}" ); } diff --git a/crates/solstice-procgen/src/foliage/tree.rs b/crates/solstice-procgen/src/foliage/tree.rs index 80714d6..93001a4 100644 --- a/crates/solstice-procgen/src/foliage/tree.rs +++ b/crates/solstice-procgen/src/foliage/tree.rs @@ -13,7 +13,7 @@ //! the outline each leaf is built with. use super::bark::BARK_REPEAT; -use super::leaf::{LeafKind, LEAF_VARIANTS}; +use super::leaf::LEAF_VARIANTS; pub use super::species::{Crown, Leaves, Level, Species}; use super::Rng; use crate::field::smoothstep; @@ -471,7 +471,7 @@ fn add_leaf( ) { let kind = leaves.kind; let crown_normals = leaves.crown_normals; - if kind == LeafKind::Needles { + if kind.is_spray() { add_needle_spray(mesh, base, axis, length, leaves, roll, variant, crown); return; } diff --git a/crates/solstice-procgen/src/lib.rs b/crates/solstice-procgen/src/lib.rs index fb64ac3..a0b07df 100644 --- a/crates/solstice-procgen/src/lib.rs +++ b/crates/solstice-procgen/src/lib.rs @@ -7,10 +7,12 @@ //! * [`cracks`] grows a crack network the way drying really cracks a surface. //! * [`surface`] turns fields into material textures. //! * [`surfaces`] is a library of ready-made surfaces, each fully described by a name and a seed. +//! * [`bush`] adds the ground of the Australian bush to it: clay, mud, gum litter and straw. //! //! Nothing here touches files or threads directly, and the same seed gives the same result on //! every platform, so a scene can hold a recipe in place of the data it produces. +pub mod bush; pub mod cracks; pub mod field; pub mod foliage; diff --git a/crates/solstice-procgen/src/surfaces.rs b/crates/solstice-procgen/src/surfaces.rs index e0af4f5..ac6d653 100644 --- a/crates/solstice-procgen/src/surfaces.rs +++ b/crates/solstice-procgen/src/surfaces.rs @@ -55,7 +55,10 @@ pub fn by_name(name: &str, seed: u32) -> Option { "marble" => marble(seed), "basalt" => basalt(seed), - _ => return Bark::by_name(name).map(|bark| bark.surface(seed)), + _ => { + return crate::bush::by_name(name, seed) + .or_else(|| Bark::by_name(name).map(|bark| bark.surface(seed))) + } }) } diff --git a/crates/solstice-render/shaders/common/frame.wgsl b/crates/solstice-render/shaders/common/frame.wgsl index 442a0af..be4b34a 100644 --- a/crates/solstice-render/shaders/common/frame.wgsl +++ b/crates/solstice-render/shaders/common/frame.wgsl @@ -1,5 +1,14 @@ // Per-frame constants for the main view. Twin of `FrameUniform` in frame.rs. +// A run of instances in a colour of their own (`Respray` in frame.rs): a truck that stands +// about, which nobody drives. None of them when `count` is 0. +struct Respray { + paint: vec3f, + first: u32, + was: vec3f, + count: u32, +} + struct Frame { view_proj: mat4x4f, // Includes the temporal jitter. inv_view_proj: mat4x4f, // Inverse of the jittered matrix. @@ -42,6 +51,43 @@ struct Frame { sea_level: f32, moon_disc: vec3f, _pad2: f32, + // The lamps of whatever is driven, as one beam: where it shines from and how far it + // reaches (no lamp when that is 0), the way it points and the cosine of half its spread, + // and how bright it is. + lamp_position: vec3f, + lamp_range: f32, + lamp_direction: vec3f, + lamp_spread: f32, + lamp_intensity: vec3f, + _pad3: f32, + // The coat of whatever is driven (`Coat` in frame.rs): its paint's colour, and its rust, + // dust and mud. The rows that take a place in the world to the car's own space, metres + // from the ground under its middle, x to its right, y up, z to its back; nothing wears + // a coat when `coat_count` is 0. + coat_x: vec4f, + coat_y: vec4f, + coat_z: vec4f, + coat_paint: vec3f, + coat_rust: f32, + coat_soil: vec3f, + coat_mud: f32, + coat_was: vec3f, + coat_dust: f32, + coat_first: u32, + coat_count: u32, + coat_seed: u32, + coat_wet: f32, + // Where its front and rear axles are along z, half its track, and its wheels' radius. + coat_axles: vec4f, + // Trucks that stand about, each in its own colour. + resprays: array, + // The ruts pressed into the ground (ruts.rs, ground/ruts.wgsl): the middle of the square + // of them that is held, in the world's x and z; half its width in metres, 0 when nothing + // is held; and one over the width of ground the map of them wraps round in. + rut_window: vec4f, + // The colour of churned soil, and the width of a cell of that map, in metres. + rut_soil: vec3f, + rut_cell: f32, } const DEBUG_NONE: u32 = 0u; diff --git a/crates/solstice-render/shaders/common/scene.wgsl b/crates/solstice-render/shaders/common/scene.wgsl index 1a0ca19..5229ac4 100644 --- a/crates/solstice-render/shaders/common/scene.wgsl +++ b/crates/solstice-render/shaders/common/scene.wgsl @@ -97,6 +97,12 @@ const MATERIAL_MASKED: u32 = 4u; // Twin of Material::BLENDS: ground of three kinds, this material's and the next two's, // blended by the shares the mesh's texture coordinates hold (land.rs). const MATERIAL_BLENDS: u32 = 32u; +// Twins of Material::PAINT and Material::INSIDE: the paint of something driven, and what is +// in its cab or under its bonnet (vg/resolve.wgsl, `coat`). +const MATERIAL_PAINT: u32 = 64u; +const MATERIAL_INSIDE: u32 = 128u; +// Twin of Material::GLASS: seen through, by being drawn in a share of its pixels (vg/mask.wgsl). +const MATERIAL_GLASS: u32 = 256u; // Twins of the INSTANCE_ flags in scene.rs. const INSTANCE_TWO_SIDED: u32 = 0x80000000u; const INSTANCE_MOVABLE: u32 = 0x40000000u; diff --git a/crates/solstice-render/shaders/gi/voxelize.wgsl b/crates/solstice-render/shaders/gi/voxelize.wgsl index 81b3e5a..7e77bd1 100644 --- a/crates/solstice-render/shaders/gi/voxelize.wgsl +++ b/crates/solstice-render/shaders/gi/voxelize.wgsl @@ -278,7 +278,7 @@ fn voxelize_speck(entry: VisibleCluster) { let data = VoxelData( pack4x8unorm(vec4f(albedo, 1.0)), pack2x16snorm(oct_encode(normal)), - encode_emissive(material.emissive * instance.glow), + encode_emissive(material.emissive * abs(instance.glow)), ); let inv_voxel = 1.0 / params.voxel_size; @@ -324,7 +324,7 @@ fn voxelize_cluster_triangle(item: u32, t: u32) { let data = VoxelData( pack4x8unorm(vec4f(albedo, 1.0)), pack2x16snorm(oct_encode(face / face_length)), - encode_emissive(material.emissive * instance.glow), + encode_emissive(material.emissive * abs(instance.glow)), ); let p0 = (world0 - params.origin) * inv_voxel; let p1 = (world1 - params.origin) * inv_voxel; diff --git a/crates/solstice-render/shaders/ground/ruts.wgsl b/crates/solstice-render/shaders/ground/ruts.wgsl new file mode 100644 index 0000000..1cebebc --- /dev/null +++ b/crates/solstice-render/shaders/ground/ruts.wgsl @@ -0,0 +1,407 @@ +// The ground as tyres have left it, and mud as it lies (docs/ruts.md). +// +// The land is baked: its points are half a metre apart, an eighth along a track, and none of +// them move. A rut is a hand deep and a tyre wide, and its tread's print a centimetre, so a +// rut is not made of the land's points. It is kept as a map of how far the ground has been +// pressed down or heaped up at each place (ruts.rs), and drawn here, where each pixel's +// material is worked out: +// +// 1. The eye's ray is followed through the pressed ground to where it meets it +// (`rut_trace`): relief mapping, with the land's own surface as the level nothing has +// been pressed from. So a rut is seen into, its near wall hides its floor, and a berm +// stands in front of what is behind it. +// 2. There the ground's textures are laid, its facing is the pressed ground's, and it is +// shaded as what it is (`rut_shade`): churned soil where the ground was broken, the +// tread's print on the floor, darker where it lies low and where the sun does not +// reach in, wet where it is wet and under water where water stands. +// +// And mud nobody has driven on is drawn as mud (`mud_lies`): wet clay with a sheen and +// water standing in its hollows at its heart, drying to a pale cracked crust at its rim. +// +// The including shader declares `frame: Frame`, `material_sampler`, `rut_map` (a +// texture_2d_array: ruts.rs) and includes common/noise.wgsl. + +// Twins of HEIGHT_UNIT, HEIGHT_ZERO and ACROSS_REACH in solstice-vehicle's rut.rs. +const RUT_HEIGHT_UNIT: f32 = 0.00002; +const RUT_HEIGHT_ZERO: f32 = 32768.0; +const RUT_ACROSS_REACH: f32 = 0.32; +// The smallest size the map is kept at, which is where it is asked whether anything is near. +const RUT_LAST_LEVEL: f32 = 5.0; +// How far above the ground as it was made, and below it, the eye's ray is followed, in +// metres: the highest berm and all but the deepest rut. +const RUT_ABOVE: f32 = 0.13; +const RUT_BELOW: f32 = 0.42; +// How far along the ground it is followed at most, in metres, either way of the pixel. +const RUT_REACH: f32 = 1.6; +// How far off ruts are still seen into, in metres: beyond it they are shaded where they lie. +const RUT_TRACED_TO: f32 = 45.0; +// How deep a tread's print is, in metres, and how far off it is still drawn. +const RUT_PRINT_DEPTH: f32 = 0.007; +const RUT_PRINT_TO: f32 = 14.0; +// How far over its last metres the held square of ruts fades into ground nobody pressed. +const RUT_EDGE: f32 = 3.0; + +// Twin of Material::MUD: ground that is mud, to be drawn as mud. +const MATERIAL_MUD: u32 = 512u; + +// The pressed ground where the eye's ray meets it. +struct Rut { + // Whether anything pressed is near: if not, nothing else here means anything. + near: bool, + // Where the ray meets it, in the world. + at: vec3f, + // Its height there against the ground as it was made: below zero in a rut. + height: f32, + // The way it faces. + normal: vec3f, + // How much of the sky and of the sun reach it, from 0 to 1. + open: f32, + lit: f32, + // How far across the tyre that pressed it the place is, in metres. + across: f32, + // How wet it is and how much churned soil shows, from 0 to 1. + wet: f32, + churn: f32, + // The tread's print: how crisp, from 0 to 1, and where in the tread's pattern, in turns. + print: f32, + phase: f32, + // The size the map was read at, and how much of all this there is this far off and + // this near the edge of what is held. + lod: f32, + fade: f32, +} + +fn rut_uv(xz: vec2f) -> vec2f { + return xz * frame.rut_window.w; +} + +// How much of the map counts at a place: all of it well inside the square that is held, +// none of it at its edge, where what the texture holds is from the far side. +fn rut_fade(xz: vec2f) -> f32 { + let from_edge = frame.rut_window.z - max(abs(xz.x - frame.rut_window.x), abs(xz.y - frame.rut_window.y)); + return clamp(from_edge / RUT_EDGE, 0.0, 1.0); +} + +// The ground's height at a place against how it was made, in metres. +fn rut_height(xz: vec2f, lod: f32) -> f32 { + let t = textureSampleLevel(rut_map, material_sampler, rut_uv(xz), 0, lod); + // The height's two bytes are blended apart and put together here. + return ((t.r * 65280.0 + t.g * 255.0) - RUT_HEIGHT_ZERO) * RUT_HEIGHT_UNIT; +} + +// A tyre's tread as it prints: how far a place is pressed in, from 0, a groove's ridge, to +// 1, under a lug. `turns` counts lugs along the way the tyre rolled, and `across` is metres +// from its middle. A mud tyre's: blocks down the middle, staggered side to side, and +// lugs at each shoulder that reach in between them. +fn rut_tread(turns: f32, across: f32) -> f32 { + let v = across / 0.15; + let side = select(0.5, 0.0, v > 0.0); + let a = abs(v); + // The blocks down the middle lean back from the centre line; the shoulder's lean + // forward, and sit in the gaps. + let middle = fract(turns + side + 0.3 * a); + let shoulder = fract(turns + side + 0.5 - 0.45 * a); + let block = smoothstep(0.0, 0.1, middle) * (1.0 - smoothstep(0.56, 0.66, middle)); + let lug = smoothstep(0.0, 0.1, shoulder) * (1.0 - smoothstep(0.5, 0.6, shoulder)); + // The grooves that run round the tyre: one down its middle, one between the blocks + // and the lugs. + let rings = smoothstep(0.03, 0.09, a) * smoothstep(0.035, 0.09, abs(a - 0.5)); + return mix(block, lug, smoothstep(0.46, 0.54, a)) * rings * (1.0 - smoothstep(0.95, 1.1, a)); +} + +// What the tread printed at a place: how deep, in metres, and how crisp. +fn rut_print(xz: vec2f, lod: f32) -> vec2f { + let uv = rut_uv(xz); + let ground = textureSampleLevel(rut_map, material_sampler, uv, 0, lod); + let marks = textureSampleLevel(rut_map, material_sampler, uv, 1, lod); + let wave = (marks.rg * 255.0 - vec2f(128.0)) / 127.0; + let crisp = min(length(wave), 1.0); + if crisp < 0.02 { + return vec2f(0.0); + } + let turns = atan2(wave.y, wave.x) / 6.2831853; + let across = (ground.b * 2.0 - 1.0) * RUT_ACROSS_REACH; + return vec2f(rut_tread(turns, across) * crisp * RUT_PRINT_DEPTH, crisp); +} + +// Follows the eye's ray to the pressed ground. `world` is the pixel's place on the land as +// it was made, `n` the way the land faces there, and `footprint` a pixel's width on it. +fn rut_trace(world: vec3f, n: vec3f, footprint: f32) -> Rut { + var rut = Rut(false, world, 0.0, n, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); + let fade = rut_fade(world.xz); + if fade <= 0.0 || n.y < 0.5 { + return rut; + } + // Whether anything pressed is within a metre or so: one look at the map at its + // smallest, where a square with one rut in it still says so. + let near = textureSampleLevel(rut_map, material_sampler, rut_uv(world.xz), 1, RUT_LAST_LEVEL).a; + if near <= 0.0 { + return rut; + } + let cell = frame.rut_cell; + let to_eye = frame.camera_position - world; + let range = length(to_eye); + let v = -to_eye / max(range, 1.0e-4); + let lod = clamp(log2(max(footprint / cell, 1.0)), 0.0, RUT_LAST_LEVEL - 1.0); + rut.near = true; + rut.lod = lod; + rut.fade = fade; + + // The land near the pixel is taken as flat, facing `n`. Along the ray, `t` metres on + // from the pixel, the ray stands `-t * fall` above it, straight up. + let fall = -dot(v, n) / n.y; + var at = world; + if fall > 0.02 && range < RUT_TRACED_TO { + let level = v.xz; + let per_metre = max(length(level), 1.0e-3); + // From where the ray comes down through the highest a berm stands to where it + // would go under the deepest rut, and no further along the ground than its reach. + let first = -min(RUT_ABOVE / fall, RUT_REACH / per_metre); + let last = min(RUT_BELOW / fall, RUT_REACH / per_metre); + // Fewer steps far off, where a step is under a pixel anyway. + let steps = u32(mix(22.0, 8.0, clamp(range / RUT_TRACED_TO, 0.0, 1.0))); + // Each pixel starts a little differently along its first step, which turns the + // steps' banding into grain the temporal filter clears. + let jitter = interleaved_gradient_noise(world.xz * 173.0, frame.frame_index % 8u); + let stride = (last - first) / f32(steps); + var before = first; + var t = first + stride * jitter; + var hit = false; + for (var k = 0u; k <= steps; k++) { + let p = world + v * t; + let above = -t * fall - rut_height(p.xz, lod) * fade; + if above <= 0.0 { + hit = true; + break; + } + before = t; + t += stride; + } + if hit { + // Between the last step above the ground and the first below it, by halves. + var low = before; + var high = t; + for (var k = 0u; k < 5u; k++) { + let middle = 0.5 * (low + high); + let p = world + v * middle; + if -middle * fall - rut_height(p.xz, lod) * fade <= 0.0 { + high = middle; + } else { + low = middle; + } + } + at = world + v * (0.5 * (low + high)); + } + } + rut.at = at; + rut.height = rut_height(at.xz, lod) * fade; + + // The way it faces: the land's own facing, tilted by how the pressed ground slopes. + let reach = max(cell, footprint) * 0.75; + let slope = vec2f( + rut_height(at.xz + vec2f(reach, 0.0), lod) - rut_height(at.xz - vec2f(reach, 0.0), lod), + rut_height(at.xz + vec2f(0.0, reach), lod) - rut_height(at.xz - vec2f(0.0, reach), lod), + ) * fade / (2.0 * reach); + rut.normal = normalize(vec3f(n.x - slope.x * n.y, n.y, n.z - slope.y * n.y)); + + // How much of the sky reaches it: less the lower it lies below the ground about it. + let about = rut_height(at.xz, min(lod + 3.0, RUT_LAST_LEVEL)) * fade; + rut.open = 1.0 - 0.45 * smoothstep(0.01, 0.16, about - rut.height); + // And of the sun: a few steps towards it over the ground, for what stands in its way. + let sun = frame.sun_direction; + if sun.y > 0.02 && range < RUT_TRACED_TO * 0.6 { + let level = length(sun.xz); + // As far as the highest berm could still shade the deepest rut, and no further. + let far = min(0.9, (RUT_ABOVE - rut.height) * level / max(sun.y, 0.05)); + var shade = 0.0; + for (var k = 1u; k <= 6u; k++) { + let s = far * f32(k) / 6.0; + let p = at.xz + sun.xz / max(level, 1.0e-3) * s; + let ray = rut.height + s * sun.y / max(level, 1.0e-3); + let over = rut_height(p, lod) * fade - ray; + // What stands well over the ray shades wholly; what just reaches it, softly. + shade = max(shade, smoothstep(0.0, 0.015 + 0.03 * s, over)); + } + rut.lit = 1.0 - shade; + } + + let uv = rut_uv(at.xz); + let ground = textureSampleLevel(rut_map, material_sampler, uv, 0, lod); + let marks = textureSampleLevel(rut_map, material_sampler, uv, 1, lod); + rut.across = (ground.b * 2.0 - 1.0) * RUT_ACROSS_REACH; + rut.wet = ground.a * fade; + rut.churn = marks.b * fade; + let wave = (marks.rg * 255.0 - vec2f(128.0)) / 127.0; + rut.print = min(length(wave), 1.0) * fade * (1.0 - smoothstep(RUT_PRINT_TO * 0.5, RUT_PRINT_TO, range)); + rut.phase = atan2(wave.y, wave.x) / 6.2831853; + return rut; +} + +// A surface of the ground before it meets the light, and the water on it. +struct Ground { + albedo: vec3f, + roughness: f32, + cavity: f32, + // The way it faces with its fine bumps, and without them. + normal: vec3f, + surface_normal: vec3f, + // How wet it is, from 0 to 1, and how much of it is under standing water. + wet: f32, + pool: f32, + // How much of the light that falls on the ground about it reaches it, from 0 to 1: laid + // on its colour once that is as wet as it is, since wetting darkens what is dark most. + shade: f32, +} + +// The ground where it has been pressed: churned soil, the tread's print, and the shade of +// lying low. `mud` is how much of the ground here is mud already, and `rain` how full the +// rain has left the puddles, each from 0 to 1. +fn rut_shade(surface: Ground, rut: Rut, mud: f32, rain: f32) -> Ground { + var out = surface; + if !rut.near { + return out; + } + let depth = max(-rut.height, 0.0); + let heaped = max(rut.height, 0.0); + let p = vec3f(rut.at.x, 0.0, rut.at.z); + + // Churned soil in place of whatever covered the ground: clods and smears of it, never + // one flat colour. + if rut.churn > 0.004 { + let clods = gradient_noise(p * 9.0, 0x51a3u); + let smears = gradient_noise(p * 2.3, 0x51a4u); + let grit = gradient_noise(p * 37.0, 0x51a5u); + let shows = clamp(rut.churn * (1.15 + 0.5 * clods.x + 0.3 * smears.x), 0.0, 1.0); + // What is churned up is what the ground is made of: mud's own colour where it is + // mud, and under anything else the soil of the country. + let made_of = mix(frame.rut_soil, out.albedo * 0.92, clamp(mud, 0.0, 1.0)); + let soil = made_of * (0.86 + 0.26 * smears.x + 0.2 * clods.x + 0.12 * grit.x); + // A berm is crumbs of what was pressed out: drier and paler at its crest. + let crest = smoothstep(0.01, 0.07, heaped); + out.albedo = mix(out.albedo, soil * (1.0 + 0.1 * crest), shows); + out.roughness = mix(out.roughness, 0.92, shows); + out.cavity = mix(out.cavity, clamp(0.72 + 0.5 * clods.x, 0.0, 1.0), shows * 0.6); + // Lumps: more of them on the berm, fewer on a floor a tyre has smoothed. + let lumps = (clods.yw * 0.11 + grit.yw * 0.035) * shows * (0.55 + 3.0 * crest); + out.normal = normalize(out.normal + vec3f(-lumps.x, 0.0, -lumps.y)); + } + + // The tread's print on the floor: each lug pressed in, each groove a ridge. + if rut.print > 0.03 { + let nudge = max(frame.rut_cell * 0.3, 0.008); + let here = rut_print(rut.at.xz, rut.lod); + let east = rut_print(rut.at.xz + vec2f(nudge, 0.0), rut.lod); + let south = rut_print(rut.at.xz + vec2f(0.0, nudge), rut.lod); + let slope = vec2f(east.x - here.x, south.x - here.x) / nudge * rut.print; + out.normal = normalize(out.normal + vec3f(slope.x, 0.0, slope.y)); + // Under a lug the soil is packed, and darker for it; a ridge catches the light. + let pressed = here.x / RUT_PRINT_DEPTH; + out.albedo *= 1.0 - 0.3 * rut.print * (pressed - 0.45); + out.cavity *= 1.0 - 0.35 * rut.print * pressed; + out.roughness = mix(out.roughness, out.roughness * 0.8, rut.print * pressed); + } + + // The geometry is the pressed ground's: water lies level in it, not on the land above. + out.surface_normal = rut.normal; + // Low ground sees less of the sky; and less of the sun where a wall stands in its way. + out.cavity *= rut.open; + out.shade = mix(0.62, 1.0, rut.lit) * mix(0.9, 1.0, rut.open); + + // Wet where it was churned wet, or a wet tyre ran. + out.wet = max(out.wet, rut.wet); + // Water stands in what is deep enough: the wetter the ground, and the fuller the rain + // has left the puddles, the shallower a rut need be to hold it. + let soaked = clamp((rut.wet - 0.55) / 0.45 + rain, 0.0, 1.0); + if soaked > 0.0 && depth > 0.0 { + let brim = mix(0.22, 0.025, soaked); + // Its edge wanders, as a puddle's does. + let wander = gradient_noise(p * 3.1, 0x51a6u).x * 0.012; + out.pool = max(out.pool, smoothstep(0.0, 0.012, depth - brim + wander) * rut.fade); + } + return out; +} + +// The distance from a place to the nearest crack in dried mud, in cells, and a number for +// the plate it is on: the plates are the cells of points scattered one to a square. +fn mud_cracks(at: vec2f) -> vec2f { + let square = floor(at); + let within = at - square; + var nearest = 8.0; + var next = 8.0; + var plate = 0.0; + for (var j = -1; j <= 1; j++) { + for (var i = -1; i <= 1; i++) { + let other = vec2f(f32(i), f32(j)); + let key = vec2i(square + other); + let h = pcg((u32(key.x) * 0x9e3779b1u) ^ pcg(u32(key.y) * 0x85ebca77u)); + let point = other + vec2f(f32(h & 0xffffu), f32(h >> 16u)) / 65535.0 * 0.8 + vec2f(0.1); + let d = length(point - within); + if d < nearest { + next = nearest; + nearest = d; + plate = f32(h & 0xffu) / 255.0; + } else if d < next { + next = d; + } + } + } + return vec2f(next - nearest, plate); +} + +// Mud as it lies where nobody has driven: `share` of the surface is mud. At its heart it +// is wet clay, dark, with a sheen, and water standing in its hollows; towards its rim it +// has dried to a paler crust that has cracked into plates. `rained` is how wet the rain has +// left the ground, and `rain` how full its puddles are, each from 0 to 1. +fn mud_lies(surface: Ground, share: f32, at: vec3f, footprint: f32, rained: f32, rain: f32) -> Ground { + var out = surface; + if share <= 0.02 { + return out; + } + let p = vec3f(at.x, 0.0, at.z); + let broad = gradient_noise(p * 0.21, 0x6d01u).x; + let patches = gradient_noise(p * 0.9, 0x6d02u).x; + // How wet: mud is wet where there is most of it, which is where the water gathers, + // and after rain all of it is. + let heart = smoothstep(0.5, 0.95, share + 0.45 * broad + 0.2 * patches); + let damp = max(heart, rained); + + // The dried rim: paler, and cracked into plates a hand or two across. + let crust = share * (1.0 - damp); + if crust > 0.01 { + // Far off the cracks are finer than a pixel: they fade out before they sparkle. + let seen = 1.0 - smoothstep(0.02, 0.07, footprint); + let warp = vec2f(gradient_noise(p * 2.7, 0x6d03u).x, gradient_noise(p * 2.7 + 9.0, 0x6d04u).x) * 0.35; + let cells = mud_cracks(at.xz * 6.5 + warp); + let fine = mud_cracks(at.xz * 17.0 - warp); + let crack = (1.0 - smoothstep(0.02, 0.09, cells.x)) * seen; + let hair = (1.0 - smoothstep(0.015, 0.06, fine.x)) * seen * 0.45; + // Each plate its own shade, bleached by the sun, a little curled at its edges. + let pale = out.albedo * (1.4 + 0.28 * cells.y) + vec3f(0.05, 0.043, 0.034); + out.albedo = mix(out.albedo, mix(pale, out.albedo * 0.4, max(crack, hair)), crust); + out.roughness = mix(out.roughness, 0.95, crust); + out.cavity *= 1.0 - 0.7 * max(crack, hair) * crust; + let curl = (1.0 - smoothstep(0.05, 0.3, cells.x)) * 0.12 * seen; + let lean = gradient_noise(vec3f(cells.y * 91.0, 0.0, 0.0), 0x6d05u).yw; + out.normal = normalize(out.normal + vec3f(lean.x, 0.0, lean.y) * (curl + 0.5 * crack) * crust); + } + + // The wet heart: clay that has taken up all the water it can, with a sheen that comes + // and goes across it, and water standing in its hollows. + let wet = share * damp * clamp(0.62 + 0.42 * patches + 0.2 * broad, 0.42, 0.86); + out.wet = max(out.wet, wet); + // Wet clay is smooth under its sheen: its grain is filled. + out.roughness = mix(out.roughness, out.roughness * 0.82, share * damp); + let hollows = gradient_noise(p * 1.45, 0x6d06u).x + 0.35 * gradient_noise(p * 4.3, 0x6d07u).x; + // The hollows of the texture's own relief fill first. + let low = hollows + 0.45 * (0.6 - out.cavity); + let brim = mix(0.4, 0.05, clamp(0.25 * heart + rain, 0.0, 1.0)); + out.pool = max(out.pool, smoothstep(brim, brim + 0.05, low) * share * smoothstep(0.55, 0.9, damp)); + return out; +} + +// Standing water on the ground: muddy, level and smooth. `pool` of the surface is under it. +fn pooled(albedo: vec3f, pool: f32) -> vec3f { + // Water with clay in it: the ground under it shows through darker and browner. + let silt = frame.rut_soil * 0.34; + return mix(albedo, mix(albedo, silt, 0.65), pool); +} diff --git a/crates/solstice-render/shaders/lighting/deferred.wgsl b/crates/solstice-render/shaders/lighting/deferred.wgsl index 8efff37..6af7109 100644 --- a/crates/solstice-render/shaders/lighting/deferred.wgsl +++ b/crates/solstice-render/shaders/lighting/deferred.wgsl @@ -76,6 +76,30 @@ fn contact_shadow(world: vec3f, normal: vec3f, view: vec3f, distance: f32, noise return 1.0; } +// The lamps of what is driven: one beam, brightest along its middle and gone at its edge, +// falling off with the square of the distance. It casts no shadows. +fn lamp_light(s: Surface, view: vec3f, world: vec3f) -> vec3f { + let to_lamp = frame.lamp_position - world; + let distance = length(to_lamp); + if distance >= frame.lamp_range { + return vec3f(0.0); + } + let direction = to_lamp / distance; + if dot(s.normal, direction) <= 0.0 { + return vec3f(0.0); + } + let along = dot(-direction, frame.lamp_direction); + let beam = smoothstep(frame.lamp_spread, mix(frame.lamp_spread, 1.0, 0.85), along); + if beam <= 0.0 { + return vec3f(0.0); + } + let window = sq(clamp(1.0 - sq(sq(distance / frame.lamp_range)), 0.0, 1.0)); + // Two lamps a little apart, each with a reflector, are not a point: close to, their light + // is spread, and what is under the car's nose is not burnt white. + let falloff = window / (distance * distance + 55.0); + return shade_light(s, view, direction) * frame.lamp_intensity * falloff * beam; +} + fn local_light(index: u32, s: Surface, view: vec3f, world: vec3f) -> vec3f { let light = lights[index]; let to_light = light.position - world; @@ -230,6 +254,9 @@ fn main(@builtin(global_invocation_id) id: vec3u) { for (var i = 0u; i < tile_lights; i++) { color += local_light(light_tiles[tile + 1u + i], surface, view, world); } + if frame.lamp_range > 0.0 { + color += lamp_light(surface, view, world); + } // Indirect diffuse. Cavity darkens crevices the probes are too coarse to resolve. let gi = textureLoad(gi_tex, pixel, 0); diff --git a/crates/solstice-render/shaders/vg/cover_mask.wgsl b/crates/solstice-render/shaders/vg/cover_mask.wgsl index cdb2e88..e4bb4cf 100644 --- a/crates/solstice-render/shaders/vg/cover_mask.wgsl +++ b/crates/solstice-render/shaders/vg/cover_mask.wgsl @@ -11,6 +11,8 @@ var triangle_inv_w: vec3f; var triangle_tier: u32; var triangle_slot: u32; var triangle_level: f32; +// For glass, the share of its pixels it is drawn in; below zero for anything else. +var triangle_glass: f32; fn software_list_first() -> u32 { return state.opaque_end + state.masked_sw_base; @@ -33,6 +35,7 @@ fn cover_triangle(v0: u32, v1: u32, v2: u32, a: vec3f, b: vec3f, c: vec3f, insta triangle_inv_w = vec3f(corner_inv_w[v0], corner_inv_w[v1], corner_inv_w[v2]); triangle_tier = material.texture_tier; triangle_slot = material.texture_slot; + triangle_glass = glass_share(material); let ab = b.xy - a.xy; let ac = c.xy - a.xy; @@ -44,7 +47,10 @@ fn cover_triangle(v0: u32, v1: u32, v2: u32, a: vec3f, b: vec3f, c: vec3f, insta triangle_level = mask_level(triangle_tier, max(dot(per_x, per_x), dot(per_y, per_y))); } -fn covered(weight_a: f32, weight_b: f32, weight_c: f32) -> bool { +fn covered(weight_a: f32, weight_b: f32, weight_c: f32, pixel: vec2f) -> bool { + if triangle_glass >= 0.0 { + return glass_kept(triangle_glass, pixel, glass_turn(view.raster_view_proj)); + } let weighted = vec3f(weight_a, weight_b, weight_c) * triangle_inv_w; let weights = weighted / (weighted.x + weighted.y + weighted.z); let uv = triangle_uv[0] * weights.x + triangle_uv[1] * weights.y + triangle_uv[2] * weights.z; diff --git a/crates/solstice-render/shaders/vg/cover_none.wgsl b/crates/solstice-render/shaders/vg/cover_none.wgsl index 2c295a3..b07fc80 100644 --- a/crates/solstice-render/shaders/vg/cover_none.wgsl +++ b/crates/solstice-render/shaders/vg/cover_none.wgsl @@ -13,6 +13,6 @@ fn cover_vertex(vertex: u32, packed: PackedVertex, instance: u32, w: f32) {} fn cover_triangle(v0: u32, v1: u32, v2: u32, a: vec3f, b: vec3f, c: vec3f, instance: u32) {} -fn covered(weight_a: f32, weight_b: f32, weight_c: f32) -> bool { +fn covered(weight_a: f32, weight_b: f32, weight_c: f32, pixel: vec2f) -> bool { return true; } diff --git a/crates/solstice-render/shaders/vg/mask.wgsl b/crates/solstice-render/shaders/vg/mask.wgsl index 3ba9ac3..c6230e0 100644 --- a/crates/solstice-render/shaders/vg/mask.wgsl +++ b/crates/solstice-render/shaders/vg/mask.wgsl @@ -35,6 +35,26 @@ fn mask_level(tier: u32, uv_per_pixel_squared: f32) -> f32 { return clamp(floor(lod + 0.5), 0.0, f32(levels - 1u)); } +// Glass is seen through. Of the pixels it covers it is drawn in a share, and what is behind it +// shows in the rest: which pixels, by a pattern that is even over any few of them, moved each +// frame as the view is jittered, so that the frames blended show the glass and what is behind +// it together. `share` is below zero for a material that is not glass. +fn glass_share(material: Material) -> f32 { + return select(-1.0, material.base_color.a, (material.flags & MATERIAL_GLASS) != 0u); +} + +// A number that differs from frame to frame, from what of the view does: its jitter. +fn glass_turn(view_proj: mat4x4f) -> f32 { + let moved = abs(view_proj[2].xy) + abs(view_proj[3].xy) + abs(view_proj[0].xy); + return floor(fract(dot(moved, vec2f(1237.0, 3571.0))) * 64.0); +} + +fn glass_kept(share: f32, pixel: vec2f, turn: f32) -> bool { + // Interleaved gradient noise. + let at = floor(pixel) + turn * vec2f(5.588238, 5.588238); + return fract(52.9829189 * fract(dot(at, vec2f(0.06711056, 0.00583715)))) < share; +} + // Whether a material's surface is solid at `uv`, at a level from `mask_level`. fn mask_solid(tier: u32, slot: u32, uv: vec2f, level: f32) -> bool { var alpha: f32; diff --git a/crates/solstice-render/shaders/vg/raster_hw_masked.wgsl b/crates/solstice-render/shaders/vg/raster_hw_masked.wgsl index c20ade0..6609159 100644 --- a/crates/solstice-render/shaders/vg/raster_hw_masked.wgsl +++ b/crates/solstice-render/shaders/vg/raster_hw_masked.wgsl @@ -36,10 +36,14 @@ fn vs_masked(@builtin(vertex_index) v: u32, @builtin(instance_index) i: u32) -> return out; } -fn solid_here(uv: vec2f, material_index: u32) -> bool { +fn solid_here(uv: vec2f, material_index: u32, pixel: vec2f) -> bool { let per_x = dpdx(uv); let per_y = dpdy(uv); let material = materials[material_index]; + let share = glass_share(material); + if share >= 0.0 { + return glass_kept(share, pixel, glass_turn(view.raster_view_proj)); + } let level = mask_level(material.texture_tier, max(dot(per_x, per_x), dot(per_y, per_y))); return mask_solid(material.texture_tier, material.texture_slot, uv, level); } @@ -51,7 +55,7 @@ fn fs_masked( @location(1) uv: vec2f, @location(2) @interpolate(flat) material: u32, ) { - if !solid_here(uv, material) { + if !solid_here(uv, material, position.xy) { return; } let pixel = vec2u(position.xy); @@ -61,8 +65,12 @@ fn fs_masked( // For depth maps. @fragment -fn fs_masked_depth(@location(1) uv: vec2f, @location(2) @interpolate(flat) material: u32) { - if !solid_here(uv, material) { +fn fs_masked_depth( + @builtin(position) position: vec4f, + @location(1) uv: vec2f, + @location(2) @interpolate(flat) material: u32, +) { + if !solid_here(uv, material, position.xy) { discard; } } diff --git a/crates/solstice-render/shaders/vg/raster_sw_body.wgsl b/crates/solstice-render/shaders/vg/raster_sw_body.wgsl index 28311bc..6140183 100644 --- a/crates/solstice-render/shaders/vg/raster_sw_body.wgsl +++ b/crates/solstice-render/shaders/vg/raster_sw_body.wgsl @@ -185,7 +185,7 @@ fn rasterize_triangle( let w2 = f32(e2 - bias2) * inv_area; let depth = w0 * z0 + w1 * z1 + w2 * z2; // Tested before the bias, as the hardware clips before it biases. - if depth > 0.0 && covered(w0, w2, w1) { + if depth > 0.0 && covered(w0, w2, w1, vec2f(f32(x), f32(y))) { write_visibility(u32(y) * width + u32(x), depth + bias, id); } } diff --git a/crates/solstice-render/shaders/vg/resolve.wgsl b/crates/solstice-render/shaders/vg/resolve.wgsl index bcba5b4..8ff3233 100644 --- a/crates/solstice-render/shaders/vg/resolve.wgsl +++ b/crates/solstice-render/shaders/vg/resolve.wgsl @@ -13,6 +13,7 @@ #include "common/frame.wgsl" #include "common/wetness.wgsl" #include "rain/surface.wgsl" +#include "ground/ruts.wgsl" @group(0) @binding(0) var frame: Frame; @group(0) @binding(1) var vis_depth: array; @@ -56,9 +57,11 @@ fn triangle_word(word: u32) -> u32 { @group(1) @binding(12) var top_color: texture_2d_array; @group(1) @binding(13) var top_normal: texture_2d_array; @group(1) @binding(14) var top_material: texture_2d_array; +// The ruts tyres have pressed into the ground, round the camera: ground/ruts.wgsl. +@group(1) @binding(15) var rut_map: texture_2d_array; // glow:begin // The emissive maps, for a scene that has any. Compiled out of one that hasn't. -@group(1) @binding(15) var glow_maps: texture_2d_array; +@group(1) @binding(16) var glow_maps: texture_2d_array; // `flags` above this bit: one more than the material's layer among the emissive maps, or zero. const MATERIAL_GLOW_SHIFT: u32 = 16u; // `Material.emissive` of a material with a map is the map's light taken over its surface, as this @@ -202,6 +205,120 @@ fn layer_of(m: Material, uv: vec2f, duv_dx: vec2f, duv_dy: vec2f) -> Layer { ); } +// A surface of whatever is driven, in its coat (`Coat` in frame.rs). +struct Coated { + albedo: vec3f, + roughness: f32, + metallic: f32, + normal: vec3f, +} + +// A paint's new colour, where the texture is the colour the paint was made in: by its +// colour and not its shade, so that a shadow painted into it is still there. +fn resprayed(albedo: vec3f, was: vec3f, paint: vec3f) -> vec3f { + let value = max(albedo.r, max(albedo.g, albedo.b)); + let was_value = max(was.r, max(was.g, was.b)); + if was_value <= 0.0 { + return albedo; + } + let hue = albedo / max(value, 1.0e-4); + let was_hue = was / was_value; + let share = (1.0 - smoothstep(0.18, 0.5, distance(hue, was_hue))) * smoothstep(0.015, 0.06, value); + return mix(albedo, paint * clamp(value / was_value, 0.0, 1.5), share); +} + +// Gives a surface of whatever is driven the colour its paint is to be, and lays on it its +// rust, its dust and its mud. `world` is where the point is and `local` where it is in its +// own mesh, which for a wheel turns with the wheel. +fn coat(material: Material, surface: Coated, world: vec3f, local: vec3f) -> Coated { + var out = surface; + // Where the point is in the car, and how far its surface faces up, as the car lies. + let p = vec3f( + dot(frame.coat_x.xyz, world) + frame.coat_x.w, + dot(frame.coat_y.xyz, world) + frame.coat_y.w, + dot(frame.coat_z.xyz, world) + frame.coat_z.w, + ); + let up = dot(frame.coat_y.xyz, surface.normal); + let seed = frame.coat_seed; + let half_track = frame.coat_axles.z; + let radius = frame.coat_axles.w; + // How far the point is from the nearer axle, seen from the side; and whether it is a + // wheel's, out at the track and within a wheel's radius of an axle. + let behind_front = p.z - frame.coat_axles.x; + let behind_rear = p.z - frame.coat_axles.y; + let from_axle = min(length(vec2f(p.y - radius, behind_front)), length(vec2f(p.y - radius, behind_rear))); + let outboard = smoothstep(half_track - 0.42, half_track - 0.16, abs(p.x)); + let wheel = outboard * (1.0 - smoothstep(radius + 0.01, radius + 0.05, from_axle)); + // What is on a wheel stays on it as it turns: its noise is read in the wheel's own space. + let q = select(p, local + vec3f(7.0), wheel > 0.5); + let broad = gradient_noise(q * 2.1, seed); + let fine = gradient_noise(q * 8.5, seed + 1u); + let speck = gradient_noise(q * 27.0, seed + 2u); + // A gradient in the car's space, as a direction in the world: to roughen a surface by. + let rough_way = frame.coat_x.xyz * (fine.y + speck.y * 0.6) + + frame.coat_y.xyz * (fine.z + speck.z * 0.6) + + frame.coat_z.xyz * (fine.w + speck.w * 0.6); + + if (material.flags & MATERIAL_PAINT) != 0u { + out.albedo = resprayed(out.albedo, frame.coat_was, frame.coat_paint); + // Rust, where water sits: low on the panels and round the wheel arches, in blotches + // that spread as it gets worse, and run down from where they begin. + if frame.coat_rust > 0.0 { + let arch = (1.0 - smoothstep(0.05, 0.3, abs(from_axle - (radius + 0.13)))) * outboard; + let low = 1.0 - smoothstep(0.3, 1.1, p.y); + let prone = clamp(0.22 + 0.6 * low + 0.7 * arch, 0.0, 1.25); + let runs = gradient_noise(vec3f(q.x * 6.5, q.y * 1.1, q.z * 6.5), seed + 3u).x; + let blotch = broad.x * 1.1 + fine.x * 0.55 + runs * 0.5 + speck.x * 0.15; + let edge = 0.95 - 1.75 * frame.coat_rust * prone; + let rusted = smoothstep(edge, edge + 0.07, blotch); + // Paint lifts and dulls round the edge of it before it goes. + let lifting = smoothstep(edge - 0.16, edge, blotch) * (1.0 - rusted); + let rust_colour = mix(vec3f(0.16, 0.055, 0.02), vec3f(0.4, 0.16, 0.045), clamp(speck.x * 1.4 + 0.5 + fine.x * 0.5, 0.0, 1.0)); + out.albedo = mix(out.albedo * (1.0 - 0.35 * lifting), rust_colour, rusted); + out.roughness = mix(mix(out.roughness, 0.6, lifting), 0.93, rusted); + out.metallic = mix(out.metallic, 0.0, rusted); + out.normal = normalize(out.normal + rough_way * 0.22 * rusted); + } + } + if (material.flags & MATERIAL_INSIDE) != 0u { + return out; + } + + // Dust: a film over everything, thickest on what faces up and towards the back, and + // never quite even. + if frame.coat_dust > 0.0 { + let lies = 0.5 + 0.5 * max(up, 0.0) + 0.22 * smoothstep(-1.0, 2.5, p.z) + 0.3 * broad.x; + let film = clamp(frame.coat_dust * lies * (0.9 + 0.5 * fine.x), 0.0, 1.0); + let dust_colour = mix(frame.coat_soil, vec3f(0.72, 0.64, 0.53), 0.4); + out.albedo = mix(out.albedo, dust_colour, film * 0.85); + out.roughness = mix(out.roughness, 0.93, film); + out.metallic = out.metallic * (1.0 - 0.92 * film); + } + + // Mud: caked from the ground up, the higher the more of it there is; thrown up along the + // flanks behind each wheel; spattered above that; and all over the wheels themselves. + if frame.coat_mud > 0.0 { + let mud = frame.coat_mud; + let rise = 0.28 + 1.2 * mud; + let low = 1.0 - smoothstep(0.12 * rise, rise, p.y); + let flank = smoothstep(half_track - 0.5, half_track - 0.12, abs(p.x)) * (1.0 - smoothstep(0.45, 1.55, p.y)); + let thrown = max(exp(-pow((behind_front - 0.8) / 0.85, 2.0)), exp(-pow((behind_rear - 0.8) / 0.85, 2.0))) * flank; + let cover = mud * (low + 0.75 * thrown) + wheel * min(mud * 1.6, 1.0); + let edge = 0.6 - (broad.x * 0.55 + fine.x * 0.36 + speck.x * 0.12); + var caked = smoothstep(edge, edge + 0.07, cover * 1.25); + let spots = gradient_noise(q * 19.0, seed + 5u).x; + let spatter = mud * (1.0 - smoothstep(rise * 0.7, rise + 0.9, p.y)) * smoothstep(0.2, 0.27, spots + 0.12 * mud); + caked = max(caked, spatter); + let fresh = frame.coat_wet; + let mud_colour = frame.coat_soil * mix(0.92, 0.5, fresh) * (0.86 + 0.28 * (speck.x + 0.5)); + out.albedo = mix(out.albedo, mud_colour, caked); + out.roughness = mix(out.roughness, mix(0.96, 0.42, fresh), caked); + out.metallic = out.metallic * (1.0 - caked); + out.normal = normalize(out.normal + rough_way * 0.3 * caked); + } + return out; +} + fn hash_color(value: u32) -> vec3f { let h = pcg(value); return vec3f(f32(h & 255u), f32((h >> 8u) & 255u), f32((h >> 16u) & 255u)) / 255.0 * 0.8 + 0.2; @@ -330,7 +447,23 @@ fn main(@builtin(global_invocation_id) id: vec3u) { normal = -normal; } // The geometry's own normal, before any normal map, for water to pool against. - let surface_normal = normal; + var surface_normal = normal; + // Ground that tyres have pressed is seen where the eye's ray meets it as it is now, + // not as the land was made (ground/ruts.wgsl): there its textures are laid, and that + // way it faces. `ground` is that place; `world` stays the land's own, for what moves. + let is_ground = (material.flags & MATERIAL_BLENDS) != 0u && material.texture_layer >= 0; + var ground = world; + var rut = Rut(false, world, 0.0, normal, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); + let footprint = sqrt(length(dp_dx) * length(dp_dy)); + if is_ground && frame.rut_window.z > 0.0 { + rut = rut_trace(world, normal, footprint); + if rut.near { + ground = rut.at; + normal = rut.normal; + } + } + // How much of the ground here is mud, to be drawn as mud. + var mud_share = 0.0; var albedo = material.base_color.rgb; var roughness = material.roughness; @@ -351,7 +484,7 @@ fn main(@builtin(global_invocation_id) id: vec3u) { // across, as sand blows over a path and grass creeps onto it, not one smooth line. var breakup = vec3f(0.0); if max(shares.x, max(shares.y, shares.z)) < 0.999 { - let p = vec3f(world.x, 0.0, world.z); + let p = vec3f(ground.x, 0.0, ground.z); let sand = gradient_noise(p * 0.45, 811u).x + 0.5 * gradient_noise(p * 1.3, 812u).x; let dirt = gradient_noise(p * 0.45 + 17.0, 813u).x + 0.5 * gradient_noise(p * 1.3 + 17.0, 814u).x; // Faded out with each share, so a kind leaves off smoothly before it is skipped. @@ -366,7 +499,7 @@ fn main(@builtin(global_invocation_id) id: vec3u) { } let m = materials[index + k]; let scale = m.uv_scale; - layers[k] = layer_of(m, world.xz * scale, dp_dx.xz * scale, dp_dy.xz * scale); + layers[k] = layer_of(m, ground.xz * scale, dp_dx.xz * scale, dp_dy.xz * scale); // Each texture's relief, from its cavity: what stands proud shows first where // two kinds meet, so grass shows on the bumps and sand settles in the hollows. scores[k] = shares[k] + breakup[k] + layers[k].cavity * BLEND_RELIEF; @@ -382,6 +515,9 @@ fn main(@builtin(global_invocation_id) id: vec3u) { surface.roughness += layers[k].roughness * blend[k]; surface.metallic += layers[k].metallic * blend[k]; surface.tangent += layers[k].tangent * blend[k]; + if (materials[index + k].flags & MATERIAL_MUD) != 0u { + mud_share += blend[k]; + } } } // The tangent frame follows the world's x and z, as all three are laid. @@ -410,6 +546,63 @@ fn main(@builtin(global_invocation_id) id: vec3u) { let inv = 1.0 / sqrt(scale); normal = normalize(tangent * inv * tangent_xy.x + bitangent * inv * tangent_xy.y + normal * tangent_z); } + } else if (material.flags & MATERIAL_BLENDS) != 0u { + // A thing of three plain materials with no texture, this one and the two after it: a + // nugget's gold, say, the clay in its hollows and the rock in it. + // The mesh's texture coordinates hold how much of the second and third there is at + // each point. Between points each share is drawn to one side or the other, so that + // where two kinds meet there is an edge, which wanders across the triangles as the + // shares do, and not a smear a triangle wide. + let index = instance_material(instance); + let raw = uv / max(material.uv_scale, 1.0e-6); + let third = smoothstep(0.42, 0.58, raw.y); + let second = smoothstep(0.38, 0.62, raw.x) * (1.0 - third); + let first = 1.0 - second - third; + let m1 = materials[index + 1u]; + let m2 = materials[index + 2u]; + albedo = material.base_color.rgb * first + m1.base_color.rgb * second + m2.base_color.rgb * third; + roughness = material.roughness * first + m1.roughness * second + m2.roughness * third; + metallic = material.metallic * first + m1.metallic * second + m2.metallic * third; + } + + // The ground as it lies and as tyres have left it: mud drawn as mud, wet at its heart + // and cracked at its rim, and where it was pressed, churned soil with the tread's + // print in it and water standing in the ruts (ground/ruts.wgsl). + var ground_wet = 0.0; + var ground_pool = 0.0; + var ground_shade = 1.0; + if is_ground && (mud_share > 0.02 || rut.near) { + let rain_state = rain.rain; + var lies = Ground(albedo, roughness, cavity, normal, surface_normal, 0.0, 0.0, 1.0); + lies = mud_lies(lies, mud_share, ground, footprint, rain_state.z, rain_state.w); + lies = rut_shade(lies, rut, mud_share, rain_state.w); + albedo = lies.albedo; + roughness = lies.roughness; + cavity = lies.cavity; + normal = lies.normal; + surface_normal = lies.surface_normal; + ground_wet = lies.wet; + ground_pool = lies.pool; + ground_shade = lies.shade; + } + + // Trucks that stand about are each in a colour of their own. + if (material.flags & MATERIAL_PAINT) != 0u { + for (var run = 0u; run < 8u; run++) { + let respray = frame.resprays[run]; + if entry.instance - respray.first < respray.count { + albedo = resprayed(albedo, respray.was, respray.paint); + } + } + } + + // What is driven wears its coat: its paint's colour, and its rust, dust and mud. + if entry.instance - frame.coat_first < frame.coat_count { + let coated = coat(material, Coated(albedo, roughness, metallic, normal), world, interp3(b, local0, local1, local2)); + albedo = coated.albedo; + roughness = coated.roughness; + metallic = coated.metallic; + normal = coated.normal; } // Water on the surface, where the sea has been (docs/wetness.md). @@ -424,8 +617,19 @@ fn main(@builtin(global_invocation_id) id: vec3u) { 0.0, 1.0, ); - var wet = wet_material(albedo, roughness, metallic, normal, surface_normal, max(sea.x, rain_wet), sea.y); + var wet = wet_material(albedo, roughness, metallic, normal, surface_normal, max(max(sea.x, rain_wet), ground_wet), sea.y); wet = under_puddle(wet, surface_normal, rained); + // The shade of lying low in a rut, on the colour as wet as it has come out. + wet.albedo *= ground_shade; + // Water standing in a rut or a hollow of mud: brown with clay, level, and smooth. + if ground_pool > 0.0 { + wet.albedo = pooled(wet.albedo, ground_pool); + wet.roughness = mix(wet.roughness, PUDDLE_ROUGHNESS * 2.0, ground_pool); + wet.normal = normalize(mix(wet.normal, vec3f(0.0, 1.0, 0.0), ground_pool)); + // The water's own surface is open to the sky, however deep the rut it lies in. + cavity = mix(cavity, 1.0, ground_pool); + wet.wetness = max(wet.wetness, ground_pool); + } albedo = wet.albedo; roughness = wet.roughness; normal = wet.normal; @@ -440,13 +644,17 @@ fn main(@builtin(global_invocation_id) id: vec3u) { let current_ndc = current_clip.xy / current_clip.w; let motion = (prev_ndc - current_ndc) * vec2f(0.5, -0.5); - var emissive = material.emissive * instance.glow; + var emissive = material.emissive * abs(instance.glow); // glow:begin let glow_layer = material.flags >> MATERIAL_GLOW_SHIFT; if glow_layer != 0u { emissive *= textureSampleGrad(glow_maps, material_sampler, uv, i32(glow_layer - 1u), duv_dx * frame.mip_scale, duv_dy * frame.mip_scale).rgb / MATERIAL_GLOW_AVERAGE; } // glow:end + // A lamp behind red glass: an instance told to glow less than nothing. + if instance.glow < 0.0 { + emissive = dot(emissive, vec3f(0.6)) * vec3f(1.0, 0.035, 0.012); + } switch frame.debug_mode { case DEBUG_CLUSTERS: { diff --git a/crates/solstice-render/src/frame.rs b/crates/solstice-render/src/frame.rs index cd8d77d..7e0564c 100644 --- a/crates/solstice-render/src/frame.rs +++ b/crates/solstice-render/src/frame.rs @@ -1,7 +1,7 @@ //! The camera and the per-frame constants derived from it. use bytemuck::{Pod, Zeroable}; -use glam::{Mat4, Vec2, Vec3}; +use glam::{Mat4, Vec2, Vec3, Vec4}; /// A perspective camera with reversed depth and an infinite far plane. /// @@ -192,6 +192,21 @@ impl DebugView { /// is under water or wet from it. pub const NO_SEA: f32 = -1.0e30; +/// How many trucks that stand about can each be in a colour of their own. +pub const RESPRAYS: usize = 8; + +/// A run of instances in a colour of their own: a truck that stands about, which nobody +/// drives. Its paint is `paint` wherever it was made `was`, as a [`Coat`]'s is. Twin of +/// `Respray` in `common/frame.wgsl`; none of them when `count` is 0. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)] +pub struct Respray { + pub paint: Vec3, + pub first: u32, + pub was: Vec3, + pub count: u32, +} + /// Twin of `Frame` in `common/frame.wgsl`. #[repr(C)] #[derive(Clone, Copy, Pod, Zeroable)] @@ -235,6 +250,90 @@ pub struct FrameUniform { pub sea_level: f32, pub moon_disc: Vec3, pub _pad2: f32, + /// The lamps of whatever is driven: see [`Lamp`]. No lamp when the range is 0. + pub lamp_position: Vec3, + pub lamp_range: f32, + pub lamp_direction: Vec3, + pub lamp_spread: f32, + pub lamp_intensity: Vec3, + pub _pad3: f32, + /// The coat of whatever is driven: see [`Coat`]. Nothing wears one when `coat_count` is 0. + /// The rows that take a place in the world to the car's own space. + pub coat_x: Vec4, + pub coat_y: Vec4, + pub coat_z: Vec4, + pub coat_paint: Vec3, + pub coat_rust: f32, + pub coat_soil: Vec3, + pub coat_mud: f32, + pub coat_was: Vec3, + pub coat_dust: f32, + pub coat_first: u32, + pub coat_count: u32, + pub coat_seed: u32, + pub coat_wet: f32, + /// Where its axles are along it, half its track, and its wheels' radius. + pub coat_axles: Vec4, + /// Trucks that stand about, each in its own colour. + pub resprays: [Respray; RESPRAYS], + /// The ruts pressed into the ground (`crate::ruts::RutMap::window`): the middle of the + /// square of them that is held, half its width, 0 when nothing is held, and one over + /// the width of ground the map wraps round in. + pub rut_window: Vec4, + /// The colour of churned soil, and the width of a cell of that map, in metres. + pub rut_soil: Vec3, + pub rut_cell: f32, +} + +/// What whatever is driven wears: the colour of its paint, and what the country has put on +/// it. All of it is worked out where the car is drawn, from where each point of it is in +/// the car's own space, so none of it is a texture and any of it can change from one frame +/// to the next. +/// +/// - **Paint.** A material marked `Material::PAINT` is given `paint` in place of the colour +/// it was made in, `was`, keeping its shade: what in its texture is some other colour +/// (a stripe, a badge) is left alone. +/// - **Rust**, from 0 to 1, on the paint: low on the panels and round the wheel arches +/// first, in blotches that spread and run. +/// - **Dust**, from 0 to 1: a film over everything out in the weather, thickest on what +/// faces up and towards the back. +/// - **Mud**, from 0 to 1: caked from the ground up, thrown up behind each wheel, spattered +/// above that; `wet` says how fresh it is, from 0, dried, to 1. +/// +/// A material marked `Material::INSIDE` takes no dust or mud. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Coat { + /// Where the car is: its own space is metres from the ground under its middle, x to + /// its right, y up, z to its back. + pub car: Mat4, + pub paint: Vec3, + /// The colour its paint was made in, to tell paint from what is painted on it. + pub was: Vec3, + pub rust: f32, + pub dust: f32, + pub mud: f32, + pub wet: f32, + /// The colour of the ground it has been driven on: its mud's, and its dust's. + pub soil: Vec3, + /// Makes one car's rust and mud its own. + pub seed: u32, + /// Where its front and rear axles are along z, half its track, and its wheels' radius. + pub axles: [f32; 4], +} + +/// The lamps of whatever is driven, as one beam: a car's headlights. It moves with the car, +/// and casts no shadows. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Lamp { + pub position: Vec3, + /// The way it points: a unit vector. + pub direction: Vec3, + /// Half the beam's spread, in radians: it is brightest along its middle and gone here. + pub half_angle: f32, + /// How far it reaches, in metres. + pub range: f32, + /// Linear RGB intensity, in candela, as a scene's lights are. + pub intensity: Vec3, } /// Sub-pixel offset for frame `index`, from the Halton (2, 3) sequence, in `-0.5..0.5`. @@ -319,7 +418,12 @@ mod tests { frame_seconds, sun_disc, sea_level, - moon_disc + moon_disc, + coat_axles, + resprays, + rut_window, + rut_soil, + rut_cell ); for (name, offset) in rust { let member = members diff --git a/crates/solstice-render/src/lib.rs b/crates/solstice-render/src/lib.rs index b8da7cb..fe532bf 100644 --- a/crates/solstice-render/src/lib.rs +++ b/crates/solstice-render/src/lib.rs @@ -35,6 +35,7 @@ pub mod profiler; pub mod rain; pub mod regions; pub mod renderer; +pub mod ruts; pub mod scene; pub mod shaders; pub mod shadow; @@ -47,11 +48,12 @@ pub mod vg; pub mod wind; pub use clouds::{Observation, Weather, WeatherCycle}; -pub use frame::{Camera, DebugView, Environment}; +pub use frame::{Camera, Coat, DebugView, Environment, Lamp}; pub use gpu::{Fallbacks, Gpu, GpuError}; pub use lightning::Thunder; pub use ocean::{Ocean, Pond, Swell}; pub use particles::{Effect, EffectId, ParticleStats}; pub use renderer::{FrameStats, Quality, Renderer, RendererSettings, SceneMemory, StreamingBudget}; +pub use ruts::RutSource; pub use streaming::{StreamRequest, StreamingStats}; pub use time_of_day::{Place, TimeOfDay}; diff --git a/crates/solstice-render/src/motion.rs b/crates/solstice-render/src/motion.rs index b99d67c..d8b16cd 100644 --- a/crates/solstice-render/src/motion.rs +++ b/crates/solstice-render/src/motion.rs @@ -91,6 +91,11 @@ impl InstanceTable { self.gpu_index.is_empty() } + /// Which of the instances on the GPU one of the scene's is, if it is drawn at all. + pub fn gpu_number(&self, instance: u32) -> Option { + self.index(instance).map(|index| index as u32) + } + fn index(&self, instance: u32) -> Option { self.gpu_index .get(instance as usize) @@ -183,7 +188,6 @@ impl InstanceTable { let Some(i) = self.index(instance) else { return false; }; - let glow = glow.max(0.0); if self.data[i].glow() != glow { self.data[i].set_glow(glow); self.changed.push(i as u32); @@ -547,10 +551,10 @@ mod tests { } #[test] - fn negative_glow_is_dark() { + fn glow_below_zero_is_kept_for_a_lamp_that_glows_red() { let mut table = table(); table.set_glow(0, -3.0); - assert_eq!(table.data[0].glow(), 0.0); + assert_eq!(table.data[0].glow(), -3.0); } #[test] diff --git a/crates/solstice-render/src/renderer.rs b/crates/solstice-render/src/renderer.rs index 31e7787..b31b2de 100644 --- a/crates/solstice-render/src/renderer.rs +++ b/crates/solstice-render/src/renderer.rs @@ -314,6 +314,18 @@ struct History { /// Renders a scene with virtualized geometry and global illumination. pub struct Renderer { + /// The lamps of whatever is driven, when they are on. + lamp: Option, + /// What whatever is driven wears, and which of the scene's instances are it: the first + /// of them as the GPU numbers them, and how many. + coat: Option<(crate::Coat, u32, u32)>, + /// Trucks that stand about, each in a colour of its own: the colour, the colour it was + /// made in, and the instances that draw it. + resprays: Vec<(Vec3, Vec3, Vec)>, + /// The ruts tyres have pressed into the ground, round the camera, and the colour of + /// the soil they churn up. + ruts: crate::ruts::RutMap, + rut_soil: Vec3, streamer: Streamer, settings: RendererSettings, scene: GpuScene, @@ -377,6 +389,11 @@ pub struct Renderer { time: f32, /// Seconds since the previous frame. frame_seconds: f32, + /// What is to be written over in installed pages before the next frame is drawn: the + /// page, how far into it, and the bytes. See [`Self::rewrite_page`]. + rewrites: Vec<(u32, u32, Vec)>, + /// Materials to be changed before the next frame is drawn. See [`Self::set_material`]. + recoloured: Vec<(u32, solstice_asset::Material)>, } impl Renderer { @@ -452,6 +469,24 @@ impl Renderer { .with_still_water(&paged.still_water) } + /// Writes over part of a page from the next frame on: `data` in place of what is + /// `offset` bytes into it, both whole words. This is how a thing is made as the game is + /// played: the scene holds a mesh for it, built with nothing coarser made from it + /// (`solstice_builder::BuildOptions::flat`) so that it is all in pages that are always + /// loaded, with bounds wide enough for whatever it will be, and its points are written + /// here when they are known. Its triangles stay as they are. An instance of it should + /// be movable ([`Self::set_instance_movable`]), so that it is drawn afresh each frame + /// rather than kept in a view drawn before. + pub fn rewrite_page(&mut self, page: u32, offset: u32, data: Vec) { + self.rewrites.push((page, offset, data)); + } + + /// Makes one of the scene's materials this one from the next frame on. For materials + /// with no texture alone: one with a texture is refused, and stays as it is. + pub fn set_material(&mut self, index: u32, material: solstice_asset::Material) { + self.recoloured.push((index, material)); + } + /// For a scene that keeps its tables outside its manifest: takes a pinned page and its /// cluster records, in order. All must arrive before the first frame. pub fn install_pinned(&mut self, gpu: &Gpu, page: u32, data: &[u8], clusters: &[u8]) { @@ -584,6 +619,9 @@ impl Renderer { self.scene.instance_table.set_hidden(instance, hidden) } + /// Below zero, it glows red, as brightly as it would have glowed above: a tail lamp, whose + /// model has a white lamp behind what should be red glass. + /// /// Scales how brightly an instance's material glows, as a lamp is lit or put out: 1 as the /// material says, 0 dark. pub fn set_instance_glow(&mut self, instance: u32, glow: f32) -> bool { @@ -766,6 +804,11 @@ impl Renderer { particles, profiler: Profiler::new(gpu), scene, + lamp: None, + coat: None, + resprays: Vec::new(), + ruts: crate::ruts::RutMap::new(gpu), + rut_soil: Vec3::new(0.33, 0.15, 0.075), streamer, frame_uniform, view_slots, @@ -795,6 +838,8 @@ impl Renderer { frame_index: 0, time: 0.0, frame_seconds: 1.0 / 60.0, + rewrites: Vec::new(), + recoloured: Vec::new(), } } @@ -940,6 +985,55 @@ impl Renderer { self.clouds.weather() } + /// Says what whatever is driven wears from now on (see [`crate::Coat`]), and which of + /// the scene's instances are it; or, with `None`, that nothing wears anything. The + /// instances are taken as one run of the scene's: a car's are, as a bake places them. + /// Set each frame the car moves, as its lamp is. + pub fn set_coat(&mut self, coat: Option<(crate::Coat, &[u32])>) { + self.coat = coat.and_then(|(coat, instances)| { + let numbered = instances + .iter() + .filter_map(|&instance| self.scene.instance_table.gpu_number(instance)); + let (first, last) = numbered.fold((u32::MAX, 0), |(first, last), number| { + (first.min(number), last.max(number)) + }); + (first <= last).then(|| (coat, first, last - first + 1)) + }); + } + + /// Says which trucks stand about in colours of their own: for each, its colour, the + /// colour its paint was made in, and the instances that draw it, which are taken as one + /// run of the scene's. Only the first [`crate::frame::RESPRAYS`] of them are painted. + /// It holds until it is set again. + pub fn set_resprays(&mut self, resprays: &[(Vec3, Vec3, Vec)]) { + self.resprays = resprays.to_vec(); + } + + /// Brings the ruts that are drawn up to date with the map of them that `source` keeps + /// (see [`crate::ruts`]), round `centre`: the world's x and z of what is looked at. Call + /// each frame something may have been driven; on ground nobody has pressed it does + /// nothing. Returns how many squares of the map were copied to the GPU. + pub fn sync_ruts(&mut self, centre: glam::Vec2, source: &dyn crate::ruts::RutSource) -> usize { + self.ruts.sync(centre, source) + } + + /// Says what colour the soil is that tyres churn up: red clay, unless told. + pub fn set_rut_soil(&mut self, soil: Vec3) { + self.rut_soil = soil; + } + + /// Turns on the lamps of whatever is driven, where they are now, or turns them off. Set + /// each frame as the car moves. + pub fn set_lamp(&mut self, lamp: Option) { + self.lamp = lamp; + } + + /// What the rain has done so far: how hard it falls now, how wet it has left what is open + /// to the sky, and how full the puddles are. For a game whose ground the rain changes. + pub fn rain_state(&self) -> crate::rain::RainState { + self.rain.state + } + /// Whether this scene has cut-out materials, and so the passes that draw them. pub fn draws_masked(&self) -> bool { self.rasterizer.draws_masked() @@ -1044,6 +1138,19 @@ impl Renderer { // Everything below draws what's installed from here on, with instances where they are // this frame. + for (page, offset, data) in std::mem::take(&mut self.rewrites) { + if !self.streamer.rewrite(gpu, &self.scene, page, offset, &data) { + log::warn!("page {page} could not be written over at {offset}: it is not installed, or is shorter"); + } + } + for (index, material) in std::mem::take(&mut self.recoloured) { + if !self + .streamer + .set_material(gpu, &self.scene, index, material) + { + log::warn!("material {index} could not be changed: it has a texture, or there is none such"); + } + } self.streamer.update(gpu, &self.scene, delta_seconds); let changes = self.scene.update_instances(gpu); let streamed = self.streamer.should_refresh_cached_views(); @@ -1536,6 +1643,7 @@ impl Renderer { &visibility, &self.main_work, &gbuffer, + &self.ruts.view, ); let history = PostProcess::history_targets(gpu, output_size); @@ -1642,6 +1750,30 @@ impl Renderer { }; let previous = self.history.unwrap_or(current); + // The coat of what is driven: the world as its own space sees it, a row a line. + let coat = self.coat; + let coat_rows = coat.map_or([glam::Vec4::ZERO; 3], |(coat, ..)| { + let to_car = coat.car.inverse(); + [to_car.row(0), to_car.row(1), to_car.row(2)] + }); + // And of what stands about: each where its instances are numbered now. + let mut resprays = [crate::frame::Respray::default(); crate::frame::RESPRAYS]; + for (slot, (paint, was, instances)) in resprays.iter_mut().zip(&self.resprays) { + let numbered = instances + .iter() + .filter_map(|&instance| self.scene.instance_table.gpu_number(instance)); + let (first, last) = numbered.fold((u32::MAX, 0), |(first, last), number| { + (first.min(number), last.max(number)) + }); + if first <= last { + *slot = crate::frame::Respray { + paint: *paint, + first, + was: *was, + count: last - first + 1, + }; + } + } let frame = FrameUniform { view_proj: jittered, inv_view_proj: jittered.inverse(), @@ -1682,6 +1814,32 @@ impl Renderer { }, moon_disc: environment.moon_disc.unwrap_or(Vec3::NEG_Y), _pad2: 0.0, + lamp_position: self.lamp.map_or(Vec3::ZERO, |lamp| lamp.position), + lamp_range: self.lamp.map_or(0.0, |lamp| lamp.range), + lamp_direction: self.lamp.map_or(Vec3::NEG_Z, |lamp| lamp.direction), + lamp_spread: self.lamp.map_or(1.0, |lamp| lamp.half_angle.cos()), + lamp_intensity: self.lamp.map_or(Vec3::ZERO, |lamp| lamp.intensity), + _pad3: 0.0, + coat_x: coat_rows[0], + coat_y: coat_rows[1], + coat_z: coat_rows[2], + coat_paint: coat.map_or(Vec3::ZERO, |(coat, ..)| coat.paint), + coat_rust: coat.map_or(0.0, |(coat, ..)| coat.rust.clamp(0.0, 1.0)), + coat_soil: coat.map_or(Vec3::ZERO, |(coat, ..)| coat.soil), + coat_mud: coat.map_or(0.0, |(coat, ..)| coat.mud.clamp(0.0, 1.0)), + coat_was: coat.map_or(Vec3::ZERO, |(coat, ..)| coat.was), + coat_dust: coat.map_or(0.0, |(coat, ..)| coat.dust.clamp(0.0, 1.0)), + coat_first: coat.map_or(0, |(_, first, _)| first), + coat_count: coat.map_or(0, |(_, _, count)| count), + coat_seed: coat.map_or(0, |(coat, ..)| coat.seed), + coat_wet: coat.map_or(0.0, |(coat, ..)| coat.wet.clamp(0.0, 1.0)), + coat_axles: coat.map_or(glam::Vec4::ZERO, |(coat, ..)| { + glam::Vec4::from_array(coat.axles) + }), + resprays, + rut_window: self.ruts.window(), + rut_soil: self.rut_soil, + rut_cell: self.ruts.cell(), daylight_illuminance: environment.daylight(), }; gpu.queue diff --git a/crates/solstice-render/src/ruts.rs b/crates/solstice-render/src/ruts.rs new file mode 100644 index 0000000..440965b --- /dev/null +++ b/crates/solstice-render/src/ruts.rs @@ -0,0 +1,259 @@ +//! The ruts tyres have pressed into the ground, as the resolve pass draws them +//! (`ground/ruts.wgsl`, `docs/ruts.md`). +//! +//! Whoever keeps the map of them, a game's physics, keeps it as squares of cells, made only +//! where something has been driven, and hands them over through [`RutSource`]. This holds +//! the squares round the camera in one texture, which the resolve pass samples for every +//! pixel of ground: the height the ground has been pressed to, the tread's print, and how +//! wet and how churned it is. +//! +//! * **The texture wraps.** A square of ground always goes to the same place in it, its +//! own numbers taken round the texture's width, so that nothing moves when the camera +//! does: squares coming into reach are copied in over the ones that went out of it on the +//! far side. The shader reads it with a repeating sampler, straight from the world's x +//! and z. +//! * **Only what changed is copied.** Each place in the texture remembers which square it +//! holds and how many times that square had changed when it was copied; a frame copies +//! the few that differ, and none on a map nobody has driven on. +//! * **Two layers of four bytes a cell,** as the map keeps them, and each square at six +//! sizes, so that ruts far off thin out and do not sparkle. + +use crate::gpu::Gpu; +use glam::{Vec2, Vec4}; + +/// Cells a side in each square of the map, and how many sizes each square is kept at. +pub const TILE: u32 = 64; +pub const LEVELS: u32 = 6; +/// Squares a side that are held round the camera: with cells of 4 cm, 61 m of ground on a +/// desktop and 31 m in a browser or on a phone. +#[cfg(not(any(target_arch = "wasm32", target_os = "android")))] +pub const TILES: u32 = 24; +#[cfg(any(target_arch = "wasm32", target_os = "android"))] +pub const TILES: u32 = 12; +/// The most squares copied to the GPU in one frame: the rest wait for the next. +const COPIES_A_FRAME: usize = 24; +/// A cell nothing has touched, in each layer: twins of `Tile::new` in solstice-vehicle's +/// `rut.rs`. +const UNTOUCHED: [[u8; 4]; 2] = [[128, 0, 128, 0], [128, 128, 0, 0]]; + +/// Who keeps the map of ruts: `solstice_vehicle::Ruts`, through whoever joins the two. +pub trait RutSource { + /// The width of a cell, in metres. + fn cell(&self) -> f32; + /// Whether nothing has been pressed anywhere. + fn is_empty(&self) -> bool; + /// A count that changes whenever a square does: 0 for one nothing has pressed. + fn version(&self, tile: (i32, i32)) -> u32; + /// One layer of a square at every size, the largest first: [`TILE`] rows of [`TILE`] + /// cells of four bytes, then half that a side, [`LEVELS`] in all. + fn levels(&self, tile: (i32, i32), layer: usize) -> Option>>; +} + +/// The squares of ruts round the camera, on the GPU. +pub struct RutMap { + queue: wgpu::Queue, + texture: wgpu::Texture, + pub view: wgpu::TextureView, + /// Which square of ground each place in the texture holds, and that square's count of + /// changes when it was copied. `None` is untouched ground. + held: Vec>, + /// The width of a cell, in metres, as the source last said. + cell: f32, + /// The square the window is centred on. + middle: (i32, i32), + /// How many places hold a square. + filled: usize, +} + +impl RutMap { + pub fn new(gpu: &Gpu) -> Self { + let side = TILES * TILE; + let texture = gpu.device.create_texture(&wgpu::TextureDescriptor { + label: Some("ruts"), + size: wgpu::Extent3d { + width: side, + height: side, + depth_or_array_layers: 2, + }, + mip_level_count: LEVELS, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + // Untouched ground is not all zeros: its height is the middle of the range. + for level in 0..LEVELS { + let side = side >> level; + for (layer, cell) in UNTOUCHED.iter().enumerate() { + let texels = cell.repeat((side * side) as usize); + write( + &gpu.queue, + &texture, + level, + layer as u32, + (0, 0), + side, + &texels, + ); + } + } + let view = texture.create_view(&wgpu::TextureViewDescriptor { + dimension: Some(wgpu::TextureViewDimension::D2Array), + ..Default::default() + }); + Self { + queue: gpu.queue.clone(), + texture, + view, + held: vec![None; (TILES * TILES) as usize], + cell: 0.04, + middle: (0, 0), + filled: 0, + } + } + + /// Brings the texture up to date with the map, round `centre`: the world's x and z of + /// what is looked at. Returns how many squares were copied. + pub fn sync(&mut self, centre: Vec2, source: &dyn RutSource) -> usize { + // Nothing driven on, and nothing held: nothing to do, which is most frames of most + // maps. + if source.is_empty() && self.filled == 0 { + return 0; + } + self.cell = source.cell(); + let metres = TILE as f32 * self.cell; + self.middle = ( + (centre.x / metres).round() as i32, + (centre.y / metres).round() as i32, + ); + let half = (TILES / 2) as i32; + let mut copied = 0; + // The squares nearest the middle first, so that what is underfoot never waits. + let mut order: Vec<(i32, i32)> = (-half..half) + .flat_map(|dj| (-half..half).map(move |di| (di, dj))) + .collect(); + order.sort_by_key(|(di, dj)| (2 * di + 1).pow(2) + (2 * dj + 1).pow(2)); + for (di, dj) in order { + let tile = (self.middle.0 + di, self.middle.1 + dj); + let slot = ( + tile.0.rem_euclid(TILES as i32) as u32, + tile.1.rem_euclid(TILES as i32) as u32, + ); + let held = &mut self.held[(slot.1 * TILES + slot.0) as usize]; + let version = source.version(tile); + let wanted = (version != 0).then_some((tile, version)); + if *held == wanted { + continue; + } + if copied >= COPIES_A_FRAME { + continue; + } + let levels = [0, 1].map(|layer| wanted.and_then(|_| source.levels(tile, layer))); + for (layer, levels) in levels.iter().enumerate() { + for level in 0..LEVELS { + let side = TILE >> level; + let at = (slot.0 * side, slot.1 * side); + match levels + .as_ref() + .and_then(|levels| levels.get(level as usize)) + { + Some(texels) if texels.len() == (side * side * 4) as usize => { + write( + &self.queue, + &self.texture, + level, + layer as u32, + at, + side, + texels, + ); + } + _ => { + let texels = UNTOUCHED[layer].repeat((side * side) as usize); + write( + &self.queue, + &self.texture, + level, + layer as u32, + at, + side, + &texels, + ); + } + } + } + } + let now = wanted.filter(|_| levels.iter().all(Option::is_some)); + self.filled = self.filled + usize::from(now.is_some()) - usize::from(held.is_some()); + *held = now; + copied += 1; + } + copied + } + + /// What the shader is told of it (`rut_window` in `common/frame.wgsl`): the middle of + /// the square of ground that is held, in the world's x and z; half its width, in + /// metres, or 0 when nothing is held, which skips all of it; and one over the width of + /// the ground the texture wraps round in. + pub fn window(&self) -> Vec4 { + let metres = TILE as f32 * self.cell; + let half = if self.filled == 0 { + 0.0 + } else { + // Half a square short of the edge: the window moves a square at a time. + ((TILES / 2) as f32 - 0.5) * metres + }; + Vec4::new( + self.middle.0 as f32 * metres, + self.middle.1 as f32 * metres, + half, + 1.0 / (TILES as f32 * metres), + ) + } + + /// The width of a cell, in metres. + pub fn cell(&self) -> f32 { + self.cell + } + + /// How many squares of ruts are held. + pub fn filled(&self) -> usize { + self.filled + } +} + +/// Copies a square of texels into one size of one layer. +fn write( + queue: &wgpu::Queue, + texture: &wgpu::Texture, + level: u32, + layer: u32, + at: (u32, u32), + side: u32, + texels: &[u8], +) { + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture, + mip_level: level, + origin: wgpu::Origin3d { + x: at.0, + y: at.1, + z: layer, + }, + aspect: wgpu::TextureAspect::All, + }, + texels, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(side * 4), + rows_per_image: Some(side), + }, + wgpu::Extent3d { + width: side, + height: side, + depth_or_array_layers: 1, + }, + ); +} diff --git a/crates/solstice-render/src/scene.rs b/crates/solstice-render/src/scene.rs index fa861d4..cc32acf 100644 --- a/crates/solstice-render/src/scene.rs +++ b/crates/solstice-render/src/scene.rs @@ -492,7 +492,10 @@ fn gpu_instances(scene: &PagedScene) -> (Vec, Vec>) { } else { 0 } - | if source.is_some_and(|m| m.flags & Material::MASKED != 0) { + // Glass is drawn where a cut-out is: by the rasterizers that leave pixels out. + | if source + .is_some_and(|m| m.flags & (Material::MASKED | Material::GLASS) != 0) + { INSTANCE_MASKED } else { 0 diff --git a/crates/solstice-render/src/shaders.rs b/crates/solstice-render/src/shaders.rs index 4d39d01..09e51b3 100644 --- a/crates/solstice-render/src/shaders.rs +++ b/crates/solstice-render/src/shaders.rs @@ -37,6 +37,7 @@ pub const SOURCES: &[(&str, &str)] = shader_table![ "common/skin_vertex.wgsl", "common/frame.wgsl", "common/wetness.wgsl", + "ground/ruts.wgsl", "common/brdf.wgsl", "common/atmosphere.wgsl", "clouds/params.wgsl", @@ -458,7 +459,7 @@ mod tests { #[test] fn resolve_without_glow_binds_and_mentions_none_of_it() { let source = without_glow(&expand("vg/resolve.wgsl")); - for gone in ["glow_maps", "glow:begin", "MATERIAL_GLOW", "binding(15)"] { + for gone in ["glow_maps", "glow:begin", "MATERIAL_GLOW", "binding(16)"] { assert!(!source.contains(gone), "{gone} is still there"); } let module = naga::front::wgsl::parse_str(&source).expect("the shader parses"); diff --git a/crates/solstice-render/src/streaming/mod.rs b/crates/solstice-render/src/streaming/mod.rs index f04443b..866cc9b 100644 --- a/crates/solstice-render/src/streaming/mod.rs +++ b/crates/solstice-render/src/streaming/mod.rs @@ -491,6 +491,66 @@ impl Streamer { self.apply_install(gpu, scene, page, slot, data, clusters); } + /// Writes over part of a page that is installed: `data` in place of what is `offset` + /// bytes into it. For a thing whose points are made as the game is played, in a page + /// that is always loaded. Both are whole words. False, and nothing is written, if the + /// page is not installed or the bytes are not all within it. + pub fn rewrite( + &self, + gpu: &Gpu, + scene: &GpuScene, + page: u32, + offset: u32, + data: &[u8], + ) -> bool { + let (Some(&slot), Some(info)) = + (self.slots.get(page as usize), self.pages.get(page as usize)) + else { + return false; + }; + let within = offset as usize + data.len() <= info.raw_bytes(); + if slot == u32::MAX || !offset.is_multiple_of(4) || !data.len().is_multiple_of(4) || !within + { + return false; + } + let (band, local) = locate_slot(self.regions.as_ref(), slot); + gpu.queue.write_buffer( + scene.pool(band), + u64::from(local) * u64::from(PAGE_WORDS) * 4 + u64::from(offset), + data, + ); + true + } + + /// Makes one of the scene's materials this one from now on: for a material with no + /// texture, whose colour is decided as the game is played. + pub fn set_material( + &mut self, + gpu: &Gpu, + scene: &GpuScene, + index: u32, + material: Material, + ) -> bool { + let size = std::mem::size_of::() as u64; + if (u64::from(index) + 1) * size > scene.materials.size() || material.texture_layer >= 0 { + return false; + } + // What moves textures between tiers writes every material when one changes. + if let Some(kept) = self + .textures + .as_mut() + .and_then(|textures| textures.materials.get_mut(index as usize)) + { + *kept = material; + } + gpu.queue.write_buffer( + &scene.materials, + u64::from(index) * size, + bytemuck::bytes_of(&material), + ); + true + } + /// Records the requests read back, and returns the pages the host should start fetching. fn plan(&mut self, requests: &[u32], max_fetching: u32) -> Vec { let pages = self.pages.len().min(requests.len()); diff --git a/crates/solstice-render/src/vg/raster_stress.rs b/crates/solstice-render/src/vg/raster_stress.rs index 46ebfec..44b3bf5 100644 --- a/crates/solstice-render/src/vg/raster_stress.rs +++ b/crates/solstice-render/src/vg/raster_stress.rs @@ -26,7 +26,7 @@ struct Triangle { a: vec4f, b: vec4f, c: vec4f } @group(0) @binding(1) var pixels: array; fn depth_bias(a: vec3f, b: vec3f, c: vec3f) -> f32 { return 0.0; } fn cover_triangle(x: u32, y: u32, z: u32, a: vec3f, b: vec3f, c: vec3f, instance: u32) {} -fn covered(a: f32, b: f32, c: f32) -> bool { return true; } +fn covered(a: f32, b: f32, c: f32, pixel: vec2f) -> bool { return true; } fn write_visibility(pixel: u32, depth: f32, id: u32) { pixels[id * 256u + pixel] = bitcast(depth); } diff --git a/crates/solstice-render/src/vg/resolve.rs b/crates/solstice-render/src/vg/resolve.rs index a052024..7cc181c 100644 --- a/crates/solstice-render/src/vg/resolve.rs +++ b/crates/solstice-render/src/vg/resolve.rs @@ -115,6 +115,8 @@ impl Resolve { .texture_array() .texture_array() .texture_array() + .texture_array() + // The ruts pressed into the ground. .texture_array(); if glow { output_layout = output_layout.texture_array(); @@ -162,6 +164,7 @@ impl Resolve { } } + #[allow(clippy::too_many_arguments)] pub fn bindings( &self, gpu: &Gpu, @@ -170,6 +173,7 @@ impl Resolve { visibility: &VisibilityBuffer, work: &CullWork, gbuffer: &GBuffer, + ruts: &wgpu::TextureView, ) -> ResolveBindings { ResolveBindings { data: { @@ -218,6 +222,7 @@ impl Resolve { wgpu::BindingResource::TextureView(&scene.textures.top.color_view), wgpu::BindingResource::TextureView(&scene.textures.top.normal_view), wgpu::BindingResource::TextureView(&scene.textures.top.material_view), + wgpu::BindingResource::TextureView(ruts), ]); if let Some(glow) = &scene.glow_maps { resources.push(wgpu::BindingResource::TextureView(glow)); diff --git a/crates/solstice-script/src/api.rs b/crates/solstice-script/src/api.rs index c2cff7a..d0286aa 100644 --- a/crates/solstice-script/src/api.rs +++ b/crates/solstice-script/src/api.rs @@ -10,7 +10,7 @@ use crate::host::{ScriptEvent, RESERVED_EVENTS}; use crate::value::{number, EntityValue, ScriptValue, Vec3Value}; -use solstice_world::{Entity, Input, Name, Played, TimerId, World}; +use solstice_world::{Entity, Idle, Input, Name, Played, TimerId, World}; use starlark::any::ProvidesStaticType; use starlark::environment::GlobalsBuilder; use starlark::eval::Evaluator; @@ -93,7 +93,10 @@ fn context<'a, 'e>(eval: &Evaluator<'_, 'a, 'e>) -> anyhow::Result<&'a Context<' /// while they are away flying the camera, so the keys that fly it don't walk who was left. fn heard<'a>(context: &'a Context) -> Option<&'a Input> { let input = context.world.input(); - let left = input.away() && context.world.entities.get::<&Played>(context.actor).is_ok(); + let entities = &context.world.entities; + // Nor for one the player could play and is not playing: the driver while they drive. + let left = entities.get::<&Idle>(context.actor).is_ok() + || (input.away() && entities.get::<&Played>(context.actor).is_ok()); (!left).then_some(input) } diff --git a/crates/solstice-vehicle/src/driver.rs b/crates/solstice-vehicle/src/driver.rs index 2b2a325..005890a 100644 --- a/crates/solstice-vehicle/src/driver.rs +++ b/crates/solstice-vehicle/src/driver.rs @@ -126,10 +126,13 @@ impl Driver { if wanted != 0.0 { self.stick = wanted.abs() < 0.999; } + // A heavy car's wheel is turned more slowly, and a heavy car's pedals pressed more + // gently: its driver has more to move. + let quick = vehicle.spec().steering_quick; self.steer = if self.stick { - ease(self.steer, wanted, STEER_STICK, STEER_STICK) + ease(self.steer, wanted, STEER_STICK * quick, STEER_STICK * quick) } else { - ease(self.steer, wanted, STEER_IN, STEER_BACK) + ease(self.steer, wanted, STEER_IN * quick, STEER_BACK * quick) }; let mut steer = self.steer * Self::lock_share(vehicle, speed.abs(), gravity); // Following a slide: the wheel turns towards the way the car is going. @@ -154,7 +157,7 @@ impl Driver { go = 0.0; } } - self.throttle = ease(self.throttle, go, PEDAL_DOWN, PEDAL_UP); + self.throttle = ease(self.throttle, go, PEDAL_DOWN * quick.min(1.0), PEDAL_UP); self.brake = ease(self.brake, stop, PEDAL_DOWN * 1.6, PEDAL_UP); Controls { @@ -213,19 +216,41 @@ impl Driver { let gears = &spec.gearbox.gears; let (rpm, limit) = (vehicle.rpm(), spec.engine.limit); let top = gears.len() as i32; - // Up, just before the limiter, unless the wheels are spinning the revs up. - let driven = if spec.front.driven { [0, 1] } else { [2, 3] }; - let gripping = driven - .iter() - .all(|&index| vehicle.wheels[index].slip_ratio.abs() < 0.2); - if gear < top && rpm > limit - 330.0 && go > 0.05 && gripping { + // Up, just before the limiter, unless the wheels are spinning the revs up. On loose + // ground a tyre that is gripping slips more, so it is held to what the ground allows. + let driven: &[usize] = match (spec.front.driven, spec.rear.driven) { + (true, true) => &[0, 1, 2, 3], + (true, false) => &[0, 1], + _ => &[2, 3], + }; + let gripping = driven.iter().all(|&index| { + let wheel = &vehicle.wheels[index]; + wheel.slip_ratio.abs() < 0.2 * wheel.surface.grip().slip + }); + // A gearbox that cruises changes up early on a light throttle, and later the further + // the pedal is down. + let cruise = spec.gearbox.cruise; + let up_at = (limit - 330.0) * (cruise + (1.0 - cruise) * go.powf(1.5)); + // A gearbox that cruises goes by the road's speed, as a road car's does, not the + // engine's: with a wheel spinning in mud, or the clutch slipping against a ledge, the + // engine's speed says nothing of what gear the car should be in. + let on_road = |gear: i32| speed.abs() / speed_in_gear(vehicle, gear as usize, 1.0); + let rpm = if cruise < 1.0 { on_road(gear) } else { rpm }; + if gear < top && rpm > up_at && go > 0.05 && gripping { return change(true); } // Down, when the engine has fallen out of its power, sooner under braking or with the // throttle flat, and never to where it would over-rev. if gear > 1 { let lower = rpm * gears[gear as usize - 2] / gears[gear as usize - 1]; - let below = if stop > 0.1 { + let below = if cruise < 1.0 { + // Well under where it would change straight back up, so that it never hunts. + if stop > 0.1 { + up_at.max(limit * 0.5) * 0.7 + } else { + up_at * 0.7 + } + } else if stop > 0.1 { limit * 0.76 } else if go > 0.9 { limit * 0.70 @@ -248,6 +273,6 @@ pub fn speed_in_gear(vehicle: &Vehicle, gear: usize, rpm: f32) -> f32 { } else { &spec.rear }; - let ratio = spec.gearbox.gears[gear - 1] * spec.gearbox.final_drive; + let ratio = spec.gearbox.gears[gear - 1] * spec.gearbox.final_drive * vehicle.range(); rpm * RPM_TO_RADIANS / ratio * axle.radius } diff --git a/crates/solstice-vehicle/src/drivetrain.rs b/crates/solstice-vehicle/src/drivetrain.rs index 015ff3b..5b5c054 100644 --- a/crates/solstice-vehicle/src/drivetrain.rs +++ b/crates/solstice-vehicle/src/drivetrain.rs @@ -281,6 +281,240 @@ fn solve3(mut a: [[f64; 3]; 3], mut b: [f64; 3]) -> [f64; 3] { x } +/// How stiff the lock between the two propshafts of a four-wheel drive is, held. +const CENTRE_STIFFNESS: f64 = 20_000.0; +/// The most passes the four-wheel solve makes: it has twice the joints. +const PASSES_ALL: usize = 24; + +/// Both axles and what drives them: a four-wheel drive. +/// +/// Five things turn: the engine and four wheels. The clutch joins the engine to the transfer +/// case, which shares the drive between the two propshafts. A lock between the propshafts +/// holds the two axles to one speed, as a part-time transfer case does once engaged; without +/// it, and with nothing sent forward, the front wheels roll free and the car is a rear-wheel +/// drive. Each axle has a differential, and each wheel a brake. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Driveline { + pub engine_speed: f32, + pub engine_inertia: f32, + pub engine_torque: f32, + /// From the engine to the wheels, with the final drive and the transfer case's range: + /// below zero in reverse, and zero in neutral. + pub ratio: f32, + pub efficiency: f32, + pub clutch: Coupling, + /// The share of the drive the front axle is sent: none in two-wheel drive. + pub front_share: f32, + /// The lock between the front and rear propshafts. + pub centre: Coupling, + /// Each axle's differential. + pub front: Coupling, + pub rear: Coupling, + /// Front left, front right, rear left, rear right. + pub wheels: [Wheel; 4], +} + +/// The speeds at the end of the step, for a four-wheel drive. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SolvedAll { + pub engine: f32, + pub wheels: [f32; 4], + /// The torque the clutch carried, from the engine to the gearbox. + pub clutch_torque: f32, +} + +/// A four-wheel drive's speeds after `dt`: [`solve`], with both axles and what joins them. +pub fn solve_all(line: &Driveline, dt: f32) -> SolvedAll { + let dt = f64::from(dt); + let ratio = f64::from(line.ratio); + let front_share = f64::from(line.front_share.clamp(0.0, 1.0)); + // How much of the propshafts' speed, and of the drive, each wheel is. + let weight = [ + front_share * 0.5, + front_share * 0.5, + (1.0 - front_share) * 0.5, + (1.0 - front_share) * 0.5, + ]; + let drive = ratio * f64::from(line.efficiency); + // The joints: the clutch, the lock between the axles, each differential, each brake. + let mut limits = [ + f64::from(line.clutch.limit), + f64::from(line.centre.limit), + f64::from(line.front.limit), + f64::from(line.rear.limit), + f64::from(line.wheels[0].brake), + f64::from(line.wheels[1].brake), + f64::from(line.wheels[2].brake), + f64::from(line.wheels[3].brake), + ]; + let stiffness = [ + CLUTCH_STIFFNESS, + CENTRE_STIFFNESS, + DIFFERENTIAL_STIFFNESS, + DIFFERENTIAL_STIFFNESS, + BRAKE_STIFFNESS, + BRAKE_STIFFNESS, + BRAKE_STIFFNESS, + BRAKE_STIFFNESS, + ]; + let mut joints = limits.map(|limit| { + if limit > 0.0 { + Joint::Held + } else { + Joint::Slipping(0.0) + } + }); + if line.ratio == 0.0 { + joints[0] = Joint::Slipping(0.0); + limits[0] = 0.0; + } + // What each joint's two sides pass each other by, as weights on the five speeds: the + // engine, then the wheels. + let across: [[f64; 5]; 8] = [ + [ + 1.0, + -ratio * weight[0], + -ratio * weight[1], + -ratio * weight[2], + -ratio * weight[3], + ], + [0.0, 0.5, 0.5, -0.5, -0.5], + [0.0, 1.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0, -1.0], + [0.0, 1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 1.0], + ]; + // And what a joint's torque does to each of the five: the clutch slows the engine and + // turns the wheels through the gears; the centre lock slows the faster axle and speeds + // the slower; a differential, its faster wheel; a brake, its wheel. + let applied: [[f64; 5]; 8] = [ + [ + -1.0, + drive * weight[0], + drive * weight[1], + drive * weight[2], + drive * weight[3], + ], + [0.0, -0.5, -0.5, 0.5, 0.5], + [0.0, -1.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, -1.0, 1.0], + [0.0, -1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, -1.0, 0.0], + [0.0, 0.0, 0.0, 0.0, -1.0], + ]; + + let mut speeds = [0.0_f64; 5]; + let mut torques = [0.0_f64; 8]; + for _ in 0..PASSES_ALL { + let mut a = [[0.0_f64; 5]; 5]; + let mut b = [0.0_f64; 5]; + let engine_inertia = f64::from(line.engine_inertia); + a[0][0] = engine_inertia / dt; + b[0] = engine_inertia / dt * f64::from(line.engine_speed) + f64::from(line.engine_torque); + for (index, wheel) in line.wheels.iter().enumerate() { + let row = index + 1; + let (inertia, radius) = (f64::from(wheel.inertia), f64::from(wheel.radius)); + let slope = radius * f64::from(wheel.stiffness); + a[row][row] = inertia / dt + slope; + b[row] = inertia / dt * f64::from(wheel.speed) - radius * f64::from(wheel.force) + + slope * f64::from(wheel.speed); + } + for joint in 0..8 { + match joints[joint] { + // torque = stiffness * across, and it acts on each row as `applied` says: on + // the left of the equations, with its sign turned. + Joint::Held => { + for row in 0..5 { + if applied[joint][row] == 0.0 { + continue; + } + for column in 0..5 { + a[row][column] -= + applied[joint][row] * stiffness[joint] * across[joint][column]; + } + } + } + Joint::Slipping(torque) => { + for row in 0..5 { + b[row] += applied[joint][row] * torque; + } + } + } + } + speeds = solve_n(a, b); + + let mut worst: Option<(usize, f64)> = None; + let mut caught = false; + for joint in 0..8 { + let passing: f64 = (0..5).map(|k| across[joint][k] * speeds[k]).sum(); + match joints[joint] { + Joint::Held => { + torques[joint] = stiffness[joint] * passing; + let over = torques[joint].abs() / limits[joint]; + if over > 1.0 && worst.is_none_or(|(_, most)| over > most) { + worst = Some((joint, over)); + } + } + Joint::Slipping(torque) => { + torques[joint] = torque; + if limits[joint] > 0.0 && torque * passing < 0.0 { + joints[joint] = Joint::Held; + caught = true; + } + } + } + } + if caught { + continue; + } + match worst { + Some((joint, _)) => { + joints[joint] = Joint::Slipping(limits[joint] * torques[joint].signum()); + } + None => break, + } + } + SolvedAll { + engine: speeds[0] as f32, + wheels: [ + speeds[1] as f32, + speeds[2] as f32, + speeds[3] as f32, + speeds[4] as f32, + ], + clutch_torque: torques[0] as f32, + } +} + +/// Solves five equations in five unknowns, as [`solve3`] does three. +#[allow(clippy::needless_range_loop)] +fn solve_n(mut a: [[f64; 5]; 5], mut b: [f64; 5]) -> [f64; 5] { + const N: usize = 5; + for column in 0..N { + let pivot = (column..N) + .max_by(|&x, &y| a[x][column].abs().total_cmp(&a[y][column].abs())) + .unwrap_or(column); + a.swap(column, pivot); + b.swap(column, pivot); + for row in column + 1..N { + let factor = a[row][column] / a[column][column]; + for k in column..N { + a[row][k] -= factor * a[column][k]; + } + b[row] -= factor * b[column]; + } + } + let mut x = [0.0; N]; + for row in (0..N).rev() { + let known: f64 = (row + 1..N).map(|k| a[row][k] * x[k]).sum(); + x[row] = (b[row] - known) / a[row][row]; + } + x +} + #[cfg(test)] mod tests { use super::*; @@ -477,4 +711,158 @@ mod tests { assert!(next < 10.0 && next > 9.99); assert!(force_after > 0.0 && force_after < 5.0, "{force_after}"); } + + fn line(engine_speed: f32, wheel_speed: f32) -> Driveline { + Driveline { + engine_speed, + engine_inertia: 0.13, + engine_torque: 0.0, + ratio: 3.15 * 3.7, + efficiency: 1.0, + clutch: Coupling::new(900.0), + front_share: 0.5, + centre: Coupling::new(30_000.0), + front: Coupling::new(0.0), + rear: Coupling::new(0.0), + wheels: [wheel(wheel_speed); 4], + } + } + + #[test] + fn with_nothing_sent_forward_a_four_wheel_drive_is_a_rear_wheel_drive() { + // Two-wheel drive: the same answer as the one driven axle's own solve. + let ratio = 3.15 * 3.7; + let mut all = line(100.0 * ratio, 100.0); + all.front_share = 0.0; + all.centre = Coupling::new(0.0); + all.engine_torque = 400.0; + all.wheels[2].force = 900.0; + all.wheels[3].brake = 300.0; + let mut one = axle(100.0 * ratio, 100.0); + one.engine_torque = 400.0; + one.left.force = 900.0; + one.right.brake = 300.0; + let (both, rear) = (solve_all(&all, DT), solve(&one, DT)); + assert!((both.engine - rear.engine).abs() < 1.0e-3); + assert!((both.wheels[2] - rear.left).abs() < 1.0e-4); + assert!((both.wheels[3] - rear.right).abs() < 1.0e-4); + assert!((both.clutch_torque - rear.clutch_torque).abs() < 0.05); + // The front wheels roll on, untouched. + assert!((both.wheels[0] - 100.0).abs() < 1.0e-5); + assert!((both.wheels[1] - 100.0).abs() < 1.0e-5); + } + + #[test] + fn in_four_wheel_drive_all_four_wheels_speed_up_together() { + let ratio = 3.15 * 3.7; + let mut all = line(100.0 * ratio, 100.0); + all.engine_torque = 400.0; + let mut seconds = 0.0; + for _ in 0..600 { + let solved = solve_all(&all, DT); + all.engine_speed = solved.engine; + for (wheel, speed) in all.wheels.iter_mut().zip(solved.wheels) { + wheel.speed = speed; + } + seconds += DT; + } + let together = 4.0 * 1.9 + 0.13 * ratio * ratio; + let expected = 100.0 + 400.0 * ratio / together * seconds; + for wheel in &all.wheels { + assert!( + (wheel.speed - expected).abs() < 0.02 * expected, + "{} against {expected}", + wheel.speed + ); + } + } + + #[test] + fn the_locked_centre_keeps_an_axle_on_ice_from_spinning_away() { + // The rear wheels have nothing under them; the front are held by the road. With the + // propshafts locked together, the rear cannot run away from the front. + let ratio = 3.15 * 3.7; + let pull = |locked: bool| { + let mut all = line(30.0 * ratio, 30.0); + all.engine_torque = 500.0; + all.centre = Coupling::new(if locked { 30_000.0 } else { 0.0 }); + for _ in 0..300 { + for index in 0..2 { + // A tyre gripping a road that passes at 30: it pushes back the faster the + // wheel turns than that. + all.wheels[index].stiffness = 4.0e4; + all.wheels[index].force = 4.0e4 * (all.wheels[index].speed - 30.0); + } + let solved = solve_all(&all, DT); + all.engine_speed = solved.engine; + for (wheel, speed) in all.wheels.iter_mut().zip(solved.wheels) { + wheel.speed = speed; + } + } + (all.wheels[0].speed, all.wheels[2].speed) + }; + let (front, rear) = pull(true); + assert!((rear - front).abs() < 0.5, "locked: {front} and {rear}"); + assert!(front < 31.5, "the road held them: {front}"); + // Open, the drive all goes to the axle that takes least to turn. + let (front, rear) = pull(false); + assert!(rear > front + 20.0, "open: {front} and {rear}"); + } + + #[test] + fn a_locked_differential_turns_both_its_wheels_with_one_in_the_air() { + let ratio = 3.15 * 3.7; + let cross = |locker: f32| { + let mut all = line(20.0 * ratio, 20.0); + all.engine_torque = 450.0; + all.front = Coupling::new(locker); + all.rear = Coupling::new(locker); + let mut pushed = 0.0; + for _ in 0..300 { + // Opposite corners on the ground, the other two in the air. + for index in [0, 3] { + all.wheels[index].stiffness = 4.0e4; + all.wheels[index].force = 4.0e4 * (all.wheels[index].speed - 20.0); + } + let solved = solve_all(&all, DT); + all.engine_speed = solved.engine; + for (wheel, speed) in all.wheels.iter_mut().zip(solved.wheels) { + wheel.speed = speed; + } + pushed = 4.0e4 * (all.wheels[0].speed + all.wheels[3].speed - 40.0); + } + (pushed, all.wheels[1].speed - all.wheels[0].speed) + }; + let (locked_push, locked_apart) = cross(30_000.0); + let (open_push, open_apart) = cross(0.0); + assert!(locked_apart.abs() < 0.5, "{locked_apart}"); + assert!( + open_apart > 10.0, + "the wheel in the air spins: {open_apart}" + ); + assert!( + locked_push > open_push * 3.0, + "locked pushes {locked_push}, open {open_push}" + ); + } + + #[test] + fn five_equations_are_solved() { + let mut a = [[0.0; 5]; 5]; + let mut b = [0.0; 5]; + let expected = [2.0, -1.0, 0.5, 4.0, -3.0]; + for row in 0..5 { + for column in 0..5 { + a[row][column] = if row == column { + 6.0 + } else { + ((row * 5 + column) % 7) as f64 * 0.3 - 0.8 + }; + b[row] += a[row][column] * expected[column]; + } + } + for (found, expected) in solve_n(a, b).iter().zip(expected) { + assert!((found - expected).abs() < 1.0e-10); + } + } } diff --git a/crates/solstice-vehicle/src/lib.rs b/crates/solstice-vehicle/src/lib.rs index b8c84fc..69d0b48 100644 --- a/crates/solstice-vehicle/src/lib.rs +++ b/crates/solstice-vehicle/src/lib.rs @@ -7,6 +7,7 @@ //! rigid body they move. //! * [`driver`]: what a key or a stick is turned into at the wheel and pedals. //! * [`surface`]: asphalt, kerb, grass and gravel, as a tyre feels them. +//! * [`rut`]: the ruts tyres press into soft ground, which stay. //! //! Nothing here touches the GPU, the physics engine or the world: a car is stepped against a //! [`Ground`] it casts rays at, so it runs headless, and a run repeats exactly. `solstice-physics` @@ -20,13 +21,18 @@ pub mod driver; pub mod drivetrain; +pub mod rut; pub mod spec; pub mod surface; pub mod tyre; pub mod vehicle; pub use driver::{Asked, Driver}; +pub use rut::{Press, Ruts}; +pub use spec::Transfer; pub use spec::{SpecError, VehicleSpec}; pub use surface::Surface; pub use tyre::Tyre; -pub use vehicle::{Body, Contact, Controls, Flat, Ground, Telemetry, Vehicle, Wheel, SUBSTEPS}; +pub use vehicle::{ + Body, Contact, Controls, DriveMode, Flat, Ground, Telemetry, Vehicle, Wheel, SUBSTEPS, +}; diff --git a/crates/solstice-vehicle/src/rut.rs b/crates/solstice-vehicle/src/rut.rs new file mode 100644 index 0000000..0b16c16 --- /dev/null +++ b/crates/solstice-vehicle/src/rut.rs @@ -0,0 +1,921 @@ +//! Ruts: ground that stays where a tyre has pressed it. +//! +//! Soft ground does not spring back. A tyre that sinks into mud leaves a rut as deep as it +//! sank, heaps what it pushed aside into a berm either side, and prints its tread on the +//! floor of it; the next wheel along rides in that rut, and the next car finds it there. This +//! is the map of all that: how far the ground has been pressed down or heaped up at each +//! place, what the tread printed, and how wet what was churned is. +//! +//! * **One map for the wheels and for the eye.** A wheel reads its depth here +//! ([`Ruts::depth`], through [`crate::Ground::rut`]) and presses it deeper +//! ([`Ruts::press`]); the renderer draws the same cells, byte for byte +//! ([`Ruts::layer`]). So a tyre sits in the rut that is drawn. +//! * **Only where something has been driven.** The map is squares of [`TILE`] cells a side, +//! each made when it is first pressed: a map nobody has driven on holds nothing, and +//! reading it costs one look in an empty table. +//! * **Cells of [`CELL`] metres**, each eight bytes in two layers, laid out as the renderer +//! samples them: +//! +//! | Layer | Byte | Holds | +//! | --- | --- | --- | +//! | 0 | 0, 1 | The ground's height against how it was made, in steps of [`HEIGHT_UNIT`], high byte first: [`HEIGHT_ZERO`] is untouched, less is a rut. | +//! | 0 | 2 | How far across the tyre that printed it the cell is, over [`ACROSS_REACH`] either way. | +//! | 0 | 3 | How wet it is, from 0 to 255. | +//! | 1 | 0, 1 | The tread's print: where in the tread's pattern the cell was pressed, as that angle's cosine and sine, times how crisp the print is: 128 is none, 127 either way of it is 1. | +//! | 1 | 2 | How much churned soil shows, in place of whatever covered the ground. | +//! | 1 | 3 | 255 if anything has touched the cell. | +//! +//! Every value is one a sampler can blend between cells: the height's two bytes blend +//! apart and are put together after, which comes to the same as blending the height. +//! +//! Nothing here knows about the GPU, the physics engine or a car: it is pressed with a +//! [`Press`], and read. + +use glam::Vec2; +use std::collections::HashMap; + +/// The width of a cell, in metres: a tyre's tread is seven or eight across. +pub const CELL: f32 = 0.04; +/// Cells a side in each square of the map that is made at once: 2.56 m. +pub const TILE: usize = 64; +/// How many sizes each square is kept at for the renderer: its cells, then halved five times. +pub const LEVELS: usize = 6; +/// One step of a cell's height, in metres, and the value that is untouched ground: heights +/// run 65 cm either way. +pub const HEIGHT_UNIT: f32 = 1.0 / 50_000.0; +pub const HEIGHT_ZERO: u16 = 32_768; +/// How far either side of a tyre's middle a cell's place across it can be kept, in metres. +pub const ACROSS_REACH: f32 = 0.32; +/// How long churned ground takes to lose most of what made it wetter than it stays, in +/// seconds: a fresh rut's sheen is gone in a few minutes. +pub const DRY_SECONDS: f32 = 150.0; +/// How often a square that is drying is dried, in seconds, and how many are in one go. +const DRY_EVERY: f32 = 6.0; +const DRY_AT_ONCE: usize = 6; +/// The deepest a rut and the highest a berm can be, in metres. +pub const DEEPEST: f32 = 0.6; +const HIGHEST: f32 = 0.2; + +const CELLS: usize = TILE * TILE; +/// A tile's width, in metres. +const TILE_METRES: f32 = TILE as f32 * CELL; + +/// A tyre's contact with the ground over one step, or anything else that presses it: a +/// strip from where the middle of the contact was to where it is. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Press { + /// The middle of the contact as the step began and as it ended: world x and z. + pub from: Vec2, + pub to: Vec2, + /// The way the tyre points along the ground: a unit vector. What it presses is laid out + /// along this, however the tyre slid. + pub along: Vec2, + /// Half the tyre's width, and half the length of its contact, in metres. + pub half_width: f32, + pub half_length: f32, + /// How far below the ground as it was made the bottom of the tyre is, in metres. + pub depth: f32, + /// The share of what is pressed out of the rut that is heaped up beside it, from 0 to + /// 1: the rest is packed down. + pub berm: f32, + /// Where in the tread's pattern the contact was at each end, in radians: a lug passes + /// with each full turn of it. + pub phase: (f32, f32), + /// How crisp a print the tread leaves, from 0 to 1: a rolling tyre prints, a spinning + /// one smears. + pub print: f32, + /// How wet what is pressed is now, and how wet it stays once it has dried, from 0 to 1. + pub wet: f32, + pub stays: f32, + /// How much churned soil is left showing, from 0 to 1. + pub churn: f32, +} + +/// One square of the map. +struct Tile { + /// The two layers the renderer samples, four bytes a cell. + layers: [Box<[u8]>; 2], + /// How wet each cell stays, to dry towards. + stays: Box<[u8]>, + /// Counts each change, for whoever keeps a copy. + version: u32, + /// Whether any cell is wetter than it stays, and when it was last dried. + damp: bool, + dried_at: f32, + /// Whether it is on the list of squares changed since they were last asked for. + listed: bool, +} + +impl Tile { + fn new(clock: f32) -> Self { + let mut first = vec![0_u8; CELLS * 4].into_boxed_slice(); + let zero = HEIGHT_ZERO.to_be_bytes(); + for cell in first.chunks_exact_mut(4) { + cell.copy_from_slice(&[zero[0], zero[1], 128, 0]); + } + let mut second = vec![0_u8; CELLS * 4].into_boxed_slice(); + for cell in second.chunks_exact_mut(4) { + cell.copy_from_slice(&[128, 128, 0, 0]); + } + Self { + layers: [first, second], + stays: vec![0_u8; CELLS].into_boxed_slice(), + version: 0, + damp: false, + dried_at: clock, + listed: false, + } + } + + fn height(&self, cell: usize) -> f32 { + let raw = u16::from_be_bytes([self.layers[0][cell * 4], self.layers[0][cell * 4 + 1]]); + (f32::from(raw) - f32::from(HEIGHT_ZERO)) * HEIGHT_UNIT + } + + fn set_height(&mut self, cell: usize, height: f32) { + let raw = (height.clamp(-DEEPEST, HIGHEST) / HEIGHT_UNIT).round() + f32::from(HEIGHT_ZERO); + let bytes = (raw as u16).to_be_bytes(); + self.layers[0][cell * 4] = bytes[0]; + self.layers[0][cell * 4 + 1] = bytes[1]; + } +} + +/// From 0 to 1 as a byte, and back. +fn byte(share: f32) -> u8 { + (share.clamp(0.0, 1.0) * 255.0).round() as u8 +} + +fn smoothstep(low: f32, high: f32, x: f32) -> f32 { + let t = ((x - low) / (high - low)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// The shape of a rut across the tyre that made it, and of the berm beside it: the height +/// of the ground `across` metres from the tyre's middle, for a tyre `half_width` wide sunk +/// `depth`, with a berm `berm` high and `berm_width` wide. Flat under the tread, rounded at +/// the shoulders, heaped just outside them. +fn profile(across: f32, half_width: f32, depth: f32, berm: f32, berm_width: f32) -> f32 { + let u = across.abs() / half_width; + let rut = depth * (1.0 - smoothstep(0.72, 1.0, u)); + let v = (across.abs() - 0.9 * half_width) / berm_width; + let heap = if (0.0..1.0).contains(&v) { + berm * smoothstep(0.0, 0.35, v) * (1.0 - smoothstep(0.35, 1.0, v)) + } else { + 0.0 + }; + heap - rut +} + +/// How high and how wide the berm beside a rut is, in metres: what was pressed out of half +/// the rut, less what was packed down, heaped in a ridge. +fn berm_of(press: &Press) -> (f32, f32) { + let depth = press.depth.max(0.0); + let width = 0.1 + 0.5 * depth; + let height = press.berm.clamp(0.0, 1.0) * depth * press.half_width / (0.5 * width); + (height.min(0.6 * depth).min(0.12), width) +} + +/// The map of what has been pressed into the ground. +#[derive(Default)] +pub struct Ruts { + tiles: HashMap<(i32, i32), Tile>, + /// Seconds it has been kept for. + clock: f32, + /// The squares changed since [`Ruts::take_changed`] was last called. + changed: Vec<(i32, i32)>, + /// When squares were last dried, and which was dried last. + dried_at: f32, + drying_from: usize, +} + +impl Ruts { + pub fn new() -> Self { + Self::default() + } + + /// Whether nothing has been pressed anywhere. + pub fn is_empty(&self) -> bool { + self.tiles.is_empty() + } + + /// How many squares of ground have been pressed. + pub fn tiles(&self) -> usize { + self.tiles.len() + } + + /// Forgets every rut: the ground is as it was made. + pub fn clear(&mut self) { + // Whoever keeps a copy is told each square is gone. + for (key, _) in self.tiles.drain() { + self.changed.push(key); + } + } + + /// The square a place is in, and the cell of that square. + fn cell_at(i: i32, j: i32) -> ((i32, i32), usize) { + let tile = (i.div_euclid(TILE as i32), j.div_euclid(TILE as i32)); + let cell = j.rem_euclid(TILE as i32) as usize * TILE + i.rem_euclid(TILE as i32) as usize; + (tile, cell) + } + + fn cell_height(&self, i: i32, j: i32) -> f32 { + let (key, cell) = Self::cell_at(i, j); + self.tiles.get(&key).map_or(0.0, |tile| tile.height(cell)) + } + + /// The ground's height at a place against how it was made, in metres: below zero in a + /// rut, above it on a berm. Between cells' middles it is blended, as it is drawn. + pub fn height(&self, x: f32, z: f32) -> f32 { + if self.tiles.is_empty() { + return 0.0; + } + let (u, v) = (x / CELL - 0.5, z / CELL - 0.5); + let (i, j) = (u.floor(), v.floor()); + let (fu, fv) = (u - i, v - j); + let (i, j) = (i as i32, j as i32); + // All four in one square, as nearly always: one look. + let (key, cell) = Self::cell_at(i, j); + let (column, row) = (cell % TILE, cell / TILE); + if column + 1 < TILE && row + 1 < TILE { + let Some(tile) = self.tiles.get(&key) else { + return 0.0; + }; + let low = tile.height(cell) + (tile.height(cell + 1) - tile.height(cell)) * fu; + let high = tile.height(cell + TILE) + + (tile.height(cell + TILE + 1) - tile.height(cell + TILE)) * fu; + return low + (high - low) * fv; + } + let low = + self.cell_height(i, j) + (self.cell_height(i + 1, j) - self.cell_height(i, j)) * fu; + let high = self.cell_height(i, j + 1) + + (self.cell_height(i + 1, j + 1) - self.cell_height(i, j + 1)) * fu; + low + (high - low) * fv + } + + /// How deep the rut at a place is, in metres: below zero on a berm. + pub fn depth(&self, x: f32, z: f32) -> f32 { + -self.height(x, z) + } + + /// Which way the pressed ground slopes at a place, and how steeply: its height's rise + /// for each metre along x and along z, measured over `reach` metres either way. + pub fn slope(&self, x: f32, z: f32, reach: f32) -> Vec2 { + if self.tiles.is_empty() { + return Vec2::ZERO; + } + let reach = reach.max(CELL); + Vec2::new( + self.height(x + reach, z) - self.height(x - reach, z), + self.height(x, z + reach) - self.height(x, z - reach), + ) / (2.0 * reach) + } + + /// How wet the pressed ground at a place is, from 0 to 1: the nearest cell's. + pub fn wet(&self, x: f32, z: f32) -> f32 { + let (key, cell) = Self::cell_at((x / CELL).floor() as i32, (z / CELL).floor() as i32); + self.tiles + .get(&key) + .map_or(0.0, |tile| f32::from(tile.layers[0][cell * 4 + 3]) / 255.0) + } + + /// The tread's print at a place: how crisp it is, from 0 to 1, and where in the + /// tread's pattern the cell was pressed, in radians. The nearest cell's. + pub fn print(&self, x: f32, z: f32) -> (f32, f32) { + let (key, cell) = Self::cell_at((x / CELL).floor() as i32, (z / CELL).floor() as i32); + self.tiles.get(&key).map_or((0.0, 0.0), |tile| { + let c = (f32::from(tile.layers[1][cell * 4]) - 128.0) / 127.0; + let s = (f32::from(tile.layers[1][cell * 4 + 1]) - 128.0) / 127.0; + (c.hypot(s).min(1.0), s.atan2(c)) + }) + } + + fn touch(&mut self, key: (i32, i32)) -> &mut Tile { + let clock = self.clock; + let tile = self.tiles.entry(key).or_insert_with(|| Tile::new(clock)); + if !tile.listed { + tile.listed = true; + self.changed.push(key); + } + tile.version = tile.version.wrapping_add(1).max(1); + tile + } + + /// Presses the ground along a strip: a tyre's contact over one step. + /// + /// * Under the tread the ground goes down to the tyre's depth, and never comes back up: + /// a rut is as deep as the deepest wheel that made it. + /// * Beside it what was pressed out is heaped in a berm. A berm heaped where a rut + /// already is fills some of it. + /// * The floor takes the tread's print wherever the tyre reaches it, and what is + /// pressed is as wet and as churned as the press says. + /// + /// Pressing the same strip twice leaves what pressing it once did. + pub fn press(&mut self, press: &Press) { + let finite = press.from.is_finite() + && press.to.is_finite() + && press.depth.is_finite() + && press.half_width.is_finite() + && press.half_length.is_finite(); + if !finite || press.half_width <= 0.0 { + return; + } + let depth = press.depth.clamp(0.0, DEEPEST); + // Nothing to leave: firm, dry ground under a clean tyre. + if depth < 2.0 * HEIGHT_UNIT && press.wet <= 0.0 && press.churn <= 0.0 { + return; + } + let along = press.along.try_normalize().unwrap_or(Vec2::NEG_Y); + let side = along.perp(); + // How far the contact went along the way the tyre points. What it slid sideways + // widens the strip: a tyre pushed across the ground scrapes a broader mark. + let moved = press.to - press.from; + let length = moved.dot(along); + let slid = moved.dot(side); + let (start, end) = (length.min(0.0), length.max(0.0)); + let half_length = press.half_length.max(CELL); + let (berm, berm_width) = berm_of(press); + let reach = (press.half_width + berm_width).max(press.half_width * 1.05) + slid.abs(); + // The cells the strip can reach. + let corners = [ + press.from + along * (start - half_length) + side * reach, + press.from + along * (start - half_length) - side * reach, + press.from + along * (end + half_length) + side * reach, + press.from + along * (end + half_length) - side * reach, + ]; + let low = corners.iter().fold(Vec2::MAX, |low, c| low.min(*c)); + let high = corners.iter().fold(Vec2::MIN, |high, c| high.max(*c)); + let (i0, j0) = ((low.x / CELL).floor() as i32, (low.y / CELL).floor() as i32); + let (i1, j1) = ( + (high.x / CELL).floor() as i32, + (high.y / CELL).floor() as i32, + ); + // A strip is a tyre's width and a step's length: anything far larger is a mistake, + // a car put somewhere else between two steps. + if (i1 - i0) > 400 || (j1 - j0) > 400 { + return; + } + let wet = byte(press.wet); + let stays = byte(press.stays.min(press.wet)); + let churn = press.churn.clamp(0.0, 1.0); + let print = press.print.clamp(0.0, 1.0); + let side_cells = TILE as i32; + let clock = self.clock; + for tile_j in j0.div_euclid(side_cells)..=j1.div_euclid(side_cells) { + for tile_i in i0.div_euclid(side_cells)..=i1.div_euclid(side_cells) { + let key = (tile_i, tile_j); + // The square is taken out of the map while it is pressed, and made only if + // the strip turns out to reach it. + let mut held: Option = None; + let rows = + j0.max(tile_j * side_cells)..=j1.min(tile_j * side_cells + side_cells - 1); + for j in rows { + let columns = + i0.max(tile_i * side_cells)..=i1.min(tile_i * side_cells + side_cells - 1); + for i in columns { + let p = Vec2::new((i as f32 + 0.5) * CELL, (j as f32 + 0.5) * CELL) + - press.from; + let s = p.dot(along); + // Where along the strip the cell is, from 0 to 1, and how far + // across the tyre as it was when it passed. + let passed = if length.abs() > 1.0e-5 { + (s / length).clamp(0.0, 1.0) + } else { + 1.0 + }; + let t = p.dot(side) - slid * passed; + if t.abs() >= reach { + continue; + } + // The contact is round at its ends: it presses less towards them. + let beyond = (start - s).max(s - end).max(0.0) / half_length; + if beyond >= 1.0 { + continue; + } + let weight = 1.0 - beyond * beyond; + let target = profile(t, press.half_width, depth, berm, berm_width) * weight; + let under = t.abs() < press.half_width; + if target.abs() < HEIGHT_UNIT && !under { + continue; + } + let cell = Self::cell_at(i, j).1; + let tile = held.get_or_insert_with(|| { + self.tiles.remove(&key).unwrap_or_else(|| Tile::new(clock)) + }); + let before = tile.height(cell); + let mut after = before; + if target < 0.0 { + after = before.min(target); + } else if target > 0.0 { + after = before.max((before + target).min(target)); + } + if after != before { + tile.set_height(cell, after); + } + // What the tyre reaches takes its print and its wet: the floor + // where the tread stands on it, and the berm it heaped. + let touched = if under { + target <= before + 0.003 + } else { + after != before + }; + if !touched { + continue; + } + let layers = &mut tile.layers; + layers[1][cell * 4 + 3] = 255; + if wet > layers[0][cell * 4 + 3] { + layers[0][cell * 4 + 3] = wet; + tile.damp = true; + } + tile.stays[cell] = tile.stays[cell].max(stays); + // Soil shows where the ground was broken: by how deep, a tyre's + // print in dust being soil too. + let broken = churn * (0.35 + 0.65 * smoothstep(0.0, 0.03, depth * weight)); + layers[1][cell * 4 + 2] = layers[1][cell * 4 + 2].max(byte(broken)); + // The stretch this step newly rolled over takes the tread's print. + if under && beyond <= 0.0 { + let phase = press.phase.0 + (press.phase.1 - press.phase.0) * passed; + // Crisp under the tread, gone at its shoulders. + let crisp = + print * (1.0 - smoothstep(0.8, 1.0, t.abs() / press.half_width)); + layers[1][cell * 4] = byte(0.5 + 0.5 * crisp * phase.cos()); + layers[1][cell * 4 + 1] = byte(0.5 + 0.5 * crisp * phase.sin()); + layers[0][cell * 4 + 2] = byte(0.5 + 0.5 * t / ACROSS_REACH); + } + } + } + if let Some(mut tile) = held { + tile.version = tile.version.wrapping_add(1).max(1); + if !tile.listed { + tile.listed = true; + self.changed.push(key); + } + self.tiles.insert(key, tile); + } + } + } + } + + /// Lays a lump of thrown mud where it landed: a blot `radius` metres across, as wet as + /// `wet`, standing a little proud of the ground. + pub fn splat(&mut self, at: Vec2, radius: f32, wet: f32) { + // (A radius that is no number is no radius.) + if !at.is_finite() || radius.is_nan() || radius <= 0.0 || radius > 1.0 { + return; + } + let (i0, j0) = ( + ((at.x - radius) / CELL).floor() as i32, + ((at.y - radius) / CELL).floor() as i32, + ); + let (i1, j1) = ( + ((at.x + radius) / CELL).floor() as i32, + ((at.y + radius) / CELL).floor() as i32, + ); + for j in j0..=j1 { + for i in i0..=i1 { + let p = Vec2::new((i as f32 + 0.5) * CELL, (j as f32 + 0.5) * CELL); + let near = 1.0 - (p.distance(at) / radius).min(1.0); + if near <= 0.0 { + continue; + } + let (key, cell) = Self::cell_at(i, j); + let tile = self.touch(key); + let heaped = tile.height(cell) + 0.012 * near.sqrt() * radius / 0.08; + // A lump lies on the ground: it does not fill a rut to its brim, nor pile + // on other lumps without end. + if tile.height(cell) < 0.02 { + tile.set_height(cell, heaped.min(0.03)); + } + let layers = &mut tile.layers; + layers[1][cell * 4 + 3] = 255; + layers[1][cell * 4 + 2] = layers[1][cell * 4 + 2].max(byte(near * 3.0)); + let wetter = byte(wet * (near * 3.0).min(1.0)); + if wetter > layers[0][cell * 4 + 3] { + layers[0][cell * 4 + 3] = wetter; + tile.damp = true; + } + // What lands on a print covers it. + let cover = 1.0 - (near * 3.0).min(1.0); + for k in 0..2 { + let was = f32::from(layers[1][cell * 4 + k]) - 128.0; + layers[1][cell * 4 + k] = (128.0 + was * cover).round() as u8; + } + } + } + } + + /// Lets `seconds` pass: what was churned dries towards how wet it stays, a few squares + /// at a time. + pub fn advance(&mut self, seconds: f32) { + if seconds.is_nan() || seconds <= 0.0 { + return; + } + self.clock += seconds; + if self.clock - self.dried_at < DRY_EVERY / DRY_AT_ONCE as f32 || self.tiles.is_empty() { + return; + } + self.dried_at = self.clock; + let clock = self.clock; + // The squares due a drying, the longest left first. + let mut due: Vec<((i32, i32), f32)> = self + .tiles + .iter() + .filter(|(_, tile)| tile.damp && clock - tile.dried_at >= DRY_EVERY) + .map(|(key, tile)| (*key, tile.dried_at)) + .collect(); + due.sort_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0))); + self.drying_from = due.len(); + for (key, _) in due.into_iter().take(DRY_AT_ONCE) { + let tile = self.touch(key); + let kept = (-(clock - tile.dried_at) / DRY_SECONDS).exp(); + tile.dried_at = clock; + let mut damp = false; + for cell in 0..CELLS { + let stays = f32::from(tile.stays[cell]); + let wet = f32::from(tile.layers[0][cell * 4 + 3]); + if wet > stays { + // Down to the nearest step, so that it gets there. + let dried = (stays + (wet - stays) * kept).floor().max(stays); + tile.layers[0][cell * 4 + 3] = dried as u8; + damp |= dried > stays; + } + } + tile.damp = damp; + } + } + + /// How many squares were waiting to be dried when squares were last dried. + pub fn drying(&self) -> usize { + self.drying_from + } + + /// The squares that have changed since this was last called, each once. + pub fn take_changed(&mut self) -> Vec<(i32, i32)> { + for key in &self.changed { + if let Some(tile) = self.tiles.get_mut(key) { + tile.listed = false; + } + } + std::mem::take(&mut self.changed) + } + + /// The square of ground a place is in. + pub fn tile_at(x: f32, z: f32) -> (i32, i32) { + ( + (x / TILE_METRES).floor() as i32, + (z / TILE_METRES).floor() as i32, + ) + } + + /// A count that changes whenever a square does: 0 for a square nothing has pressed. + pub fn version(&self, tile: (i32, i32)) -> u32 { + self.tiles.get(&tile).map_or(0, |tile| tile.version) + } + + /// One layer of a square as the renderer samples it: [`TILE`] rows of [`TILE`] cells, + /// four bytes each. `None` for a square nothing has pressed. + pub fn layer(&self, tile: (i32, i32), layer: usize) -> Option<&[u8]> { + self.tiles.get(&tile).map(|tile| &*tile.layers[layer]) + } + + /// One layer of a square at each smaller size, for the renderer to sample from far off: + /// level 1 first, each half the last a side. Heights, wetness and prints are averaged, + /// so a rut thins out with distance; whether anything is there is kept if it is true of + /// any cell, so that a square with one rut in it is never taken for untouched ground. + pub fn smaller(&self, tile: (i32, i32), layer: usize) -> Option>> { + let mut last: Vec = self.layer(tile, layer)?.to_vec(); + let mut side = TILE; + let mut levels = Vec::with_capacity(LEVELS - 1); + for _ in 1..LEVELS { + let half = side / 2; + let mut next = vec![0_u8; half * half * 4]; + for row in 0..half { + for column in 0..half { + let from = |dx: usize, dy: usize, byte: usize| { + u32::from(last[((row * 2 + dy) * side + column * 2 + dx) * 4 + byte]) + }; + let four = |byte: usize| { + from(0, 0, byte) + from(1, 0, byte) + from(0, 1, byte) + from(1, 1, byte) + }; + let out = &mut next[(row * half + column) * 4..][..4]; + if layer == 0 { + // The height's two bytes are one number. + let height = (four(0) * 256 + four(1) + 2) / 4; + out[0] = (height >> 8) as u8; + out[1] = (height & 0xff) as u8; + out[2] = ((four(2) + 2) / 4) as u8; + out[3] = ((four(3) + 2) / 4) as u8; + } else { + for (byte, out) in out.iter_mut().take(3).enumerate() { + *out = ((four(byte) + 2) / 4) as u8; + } + out[3] = (0..4).map(|k| from(k & 1, k >> 1, 3)).max().unwrap_or(0) as u8; + } + } + } + levels.push(next.clone()); + last = next; + side = half; + } + Some(levels) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A tyre a quarter of a metre wide rolled along +x at z = 1, sunk `depth`. + fn rolled(depth: f32, from: f32, to: f32) -> Press { + Press { + from: Vec2::new(from, 1.0), + to: Vec2::new(to, 1.0), + along: Vec2::X, + half_width: 0.14, + half_length: 0.12, + depth, + berm: 0.5, + phase: (0.0, (to - from) / 0.08 * std::f32::consts::TAU), + print: 1.0, + wet: 0.9, + stays: 0.5, + churn: 1.0, + } + } + + #[test] + fn ground_nobody_has_driven_on_is_as_it_was_made() { + let ruts = Ruts::new(); + assert!(ruts.is_empty()); + assert_eq!(ruts.height(3.0, -7.0), 0.0); + assert_eq!(ruts.slope(3.0, -7.0, 0.1), Vec2::ZERO); + assert_eq!(ruts.version((0, 0)), 0); + assert!(ruts.layer((0, 0), 0).is_none()); + } + + #[test] + fn a_tyre_presses_a_rut_as_deep_as_it_sank() { + let mut ruts = Ruts::new(); + ruts.press(&rolled(0.15, 0.0, 2.0)); + // Under the tread, along the strip: the depth it was pressed to. + for x in [0.1, 0.7, 1.3, 1.9] { + assert!((ruts.depth(x, 1.0) - 0.15).abs() < 0.002, "at {x}"); + assert!((ruts.depth(x, 1.06) - 0.15).abs() < 0.004, "off its middle"); + } + // Well to the side, and well before and beyond it: untouched. + assert_eq!(ruts.height(1.0, 2.0), 0.0); + assert_eq!(ruts.height(-1.0, 1.0), 0.0); + assert_eq!(ruts.height(3.0, 1.0), 0.0); + assert!(!ruts.is_empty()); + } + + #[test] + fn what_is_pressed_out_is_heaped_beside_the_rut() { + let mut ruts = Ruts::new(); + ruts.press(&rolled(0.15, 0.0, 2.0)); + // Just outside each shoulder the ground stands above where it was. + let highest = |side: f32| { + (0..20) + .map(|k| ruts.height(1.0, 1.0 + side * (0.12 + k as f32 * 0.01))) + .fold(f32::MIN, f32::max) + }; + for side in [-1.0, 1.0] { + let berm = highest(side); + assert!(berm > 0.03 && berm <= 0.12, "{berm}"); + } + // A berm is less than the rut: what was pressed is mostly packed down. Across the + // strip, more went down than came up. + let across: f32 = (0..60) + .map(|k| ruts.height(1.0, 0.4 + k as f32 * 0.02)) + .sum(); + assert!(across < 0.0, "{across}"); + // Firm ground that takes a shallow print heaps next to nothing. + let mut firm = Ruts::new(); + firm.press(&Press { + berm: 0.2, + ..rolled(0.01, 0.0, 2.0) + }); + let berm = (0..20) + .map(|k| firm.height(1.0, 1.12 + k as f32 * 0.01)) + .fold(f32::MIN, f32::max); + assert!(berm < 0.006, "{berm}"); + } + + #[test] + fn a_rut_stays_and_only_a_deeper_wheel_deepens_it() { + let mut ruts = Ruts::new(); + ruts.press(&rolled(0.15, 0.0, 2.0)); + let once: Vec = (0..50) + .map(|k| ruts.height(1.0, 0.5 + k as f32 * 0.02)) + .collect(); + // A long time passes: the ground does not come back. + for _ in 0..600 { + ruts.advance(1.0); + } + let later: Vec = (0..50) + .map(|k| ruts.height(1.0, 0.5 + k as f32 * 0.02)) + .collect(); + assert_eq!(once, later); + // The same wheel again, and a lighter one: nothing changes. + ruts.press(&rolled(0.15, 0.0, 2.0)); + ruts.press(&rolled(0.06, 0.0, 2.0)); + let again: Vec = (0..50) + .map(|k| ruts.height(1.0, 0.5 + k as f32 * 0.02)) + .collect(); + assert_eq!(once, again); + // A heavier one: deeper. + ruts.press(&rolled(0.22, 0.0, 2.0)); + assert!((ruts.depth(1.0, 1.0) - 0.22).abs() < 0.002); + } + + #[test] + fn a_strip_pressed_in_steps_is_the_strip_pressed_at_once() { + let mut whole = Ruts::new(); + whole.press(&rolled(0.12, 0.0, 2.0)); + let mut stepped = Ruts::new(); + for k in 0..20 { + stepped.press(&rolled(0.12, k as f32 * 0.1, (k + 1) as f32 * 0.1)); + } + for k in 0..40 { + let x = 0.05 + k as f32 * 0.05; + for z in [0.8, 0.9, 1.0, 1.1, 1.2] { + let (a, b) = (whole.height(x, z), stepped.height(x, z)); + assert!((a - b).abs() < 0.002, "at {x} {z}: {a} and {b}"); + } + } + } + + #[test] + fn a_wheel_crossing_a_rut_flattens_its_berm_and_half_fills_it() { + let mut ruts = Ruts::new(); + ruts.press(&rolled(0.15, 0.0, 4.0)); + // Another, across it at x = 2. + let crossing = Press { + from: Vec2::new(2.0, -1.0), + to: Vec2::new(2.0, 3.0), + along: Vec2::Y, + ..rolled(0.1, 0.0, 0.0) + }; + ruts.press(&crossing); + // Where the first's berm was, under the second's tread: pressed down. + assert!(ruts.height(2.0, 1.2) < -0.09); + // The first rut, beside the second's tread: some of the second's berm is in it, + // and it is still a rut. + let filled = ruts.height(2.2, 1.0); + assert!(filled > -0.15 && filled < 0.0, "{filled}"); + } + + #[test] + fn a_rolling_tyre_prints_its_tread_and_a_spinning_one_smears_it() { + let mut ruts = Ruts::new(); + ruts.press(&rolled(0.05, 0.0, 2.0)); + // A lug every 8 cm: a quarter of a lug on, a quarter of a turn of the pattern. + let (crisp, at) = ruts.print(0.82, 1.0); + assert!(crisp > 0.9, "{crisp}"); + let turned = (at - 0.25 * std::f32::consts::TAU).rem_euclid(std::f32::consts::TAU); + assert!(turned.min(std::f32::consts::TAU - turned) < 0.25, "{at}"); + // Beside the rut, nothing printed. + assert_eq!(ruts.print(1.0, 2.0).0, 0.0); + // The wheel behind it, spinning: the print is wiped. + ruts.press(&Press { + print: 0.0, + ..rolled(0.05, 0.0, 2.0) + }); + assert!(ruts.print(0.82, 1.0).0 < 0.05); + } + + #[test] + fn churned_ground_dries_to_how_wet_it_stays() { + let mut ruts = Ruts::new(); + ruts.press(&rolled(0.1, 0.0, 2.0)); + assert!((ruts.wet(1.0, 1.0) - 0.9).abs() < 0.01); + ruts.take_changed(); + let mut drying = Vec::new(); + for second in 0..900 { + ruts.advance(1.0); + if second % 60 == 59 { + drying.push(ruts.wet(1.0, 1.0)); + } + } + assert!( + drying.windows(2).all(|pair| pair[1] <= pair[0]), + "{drying:?}" + ); + assert!( + drying[1] < 0.75 && drying[1] > 0.55, + "after two minutes: {drying:?}" + ); + assert!((drying[14] - 0.5).abs() < 0.02, "in the end: {drying:?}"); + // Whoever keeps a copy was told, and is told no more once it is dry. + assert!(!ruts.take_changed().is_empty()); + ruts.advance(60.0); + ruts.advance(60.0); + assert!(ruts.take_changed().is_empty()); + // Ground wet from a tyre and nothing else dries right out. + let mut tracked = Ruts::new(); + tracked.press(&Press { + depth: 0.0, + churn: 0.0, + stays: 0.0, + ..rolled(0.0, 0.0, 2.0) + }); + assert!(tracked.wet(1.0, 1.0) > 0.8 && tracked.height(1.0, 1.0) == 0.0); + for _ in 0..1200 { + tracked.advance(1.0); + } + assert_eq!(tracked.wet(1.0, 1.0), 0.0); + } + + #[test] + fn changed_squares_are_listed_once_and_counted() { + let mut ruts = Ruts::new(); + ruts.press(&rolled(0.1, 0.0, 2.0)); + ruts.press(&rolled(0.12, 0.0, 2.0)); + let changed = ruts.take_changed(); + let tile = Ruts::tile_at(1.0, 1.0); + assert_eq!(changed.iter().filter(|&&key| key == tile).count(), 1); + let version = ruts.version(tile); + assert!(version > 0); + assert!(ruts.take_changed().is_empty()); + ruts.press(&rolled(0.2, 0.0, 2.0)); + assert!(ruts.version(tile) != version); + assert_eq!(ruts.take_changed().len(), changed.len()); + // Cleared, each square is listed as gone. + ruts.clear(); + assert!(ruts.is_empty() && ruts.take_changed().contains(&tile)); + assert_eq!(ruts.version(tile), 0); + } + + #[test] + fn a_strip_across_squares_is_whole() { + // From one square into the next, along both axes, and where x and z are below zero. + let mut ruts = Ruts::new(); + let press = Press { + from: Vec2::new(-1.0, -1.0), + to: Vec2::new(1.0, 1.0), + along: Vec2::ONE.normalize(), + ..rolled(0.1, 0.0, 0.0) + }; + ruts.press(&press); + for k in 0..=20 { + let at = -0.9 + k as f32 * 0.09; + assert!((ruts.depth(at, at) - 0.1).abs() < 0.003, "at {at}"); + } + assert!(ruts.tiles() >= 3); + } + + #[test] + fn the_renderer_is_given_the_height_the_wheels_read() { + let mut ruts = Ruts::new(); + ruts.press(&rolled(0.15, 0.0, 2.0)); + let tile = Ruts::tile_at(1.0, 1.0); + let layer = ruts.layer(tile, 0).unwrap(); + assert_eq!(layer.len(), TILE * TILE * 4); + let (i, j) = ((1.0 / CELL) as usize, (1.0 / CELL) as usize); + let cell = (j % TILE * TILE + i % TILE) * 4; + // As the shader puts the two bytes together. + let height = (f32::from(layer[cell]) * 256.0 + f32::from(layer[cell + 1]) + - f32::from(HEIGHT_ZERO)) + * HEIGHT_UNIT; + let read = ruts.height((i as f32 + 0.5) * CELL, (j as f32 + 0.5) * CELL); + assert!((height - read).abs() < 1.0e-6 && (height + 0.15).abs() < 0.002); + // Smaller, a square keeps its ruts, thinner, and never loses that it has any. + let smaller = ruts.smaller(tile, 0).unwrap(); + let marks = ruts.smaller(tile, 1).unwrap(); + assert_eq!(smaller.len(), LEVELS - 1); + for (level, texels) in smaller.iter().enumerate() { + let side = TILE >> (level + 1); + assert_eq!(texels.len(), side * side * 4); + } + let last = &marks[LEVELS - 2]; + assert!(last.chunks_exact(4).any(|cell| cell[3] == 255)); + let deepest = smaller[2] + .chunks_exact(4) + .map(|cell| u16::from_be_bytes([cell[0], cell[1]])) + .min() + .unwrap(); + assert!(deepest < HEIGHT_ZERO - 1000, "{deepest}"); + } + + #[test] + fn a_lump_of_mud_lies_where_it_lands() { + let mut ruts = Ruts::new(); + ruts.splat(Vec2::new(0.5, 0.5), 0.1, 1.0); + assert!(ruts.height(0.5, 0.5) > 0.004 && ruts.height(0.5, 0.5) <= 0.03); + assert!(ruts.wet(0.5, 0.5) > 0.9); + assert_eq!(ruts.height(0.9, 0.5), 0.0); + // More of them do not pile up without end. + for _ in 0..50 { + ruts.splat(Vec2::new(0.5, 0.5), 0.1, 1.0); + } + assert!(ruts.height(0.5, 0.5) <= 0.031); + // Nonsense is left out. + ruts.splat(Vec2::new(f32::NAN, 0.0), 0.1, 1.0); + ruts.press(&Press { + depth: f32::NAN, + ..rolled(0.1, 0.0, 1.0) + }); + ruts.press(&rolled(0.1, 0.0, 5000.0)); + assert!(ruts.tiles() <= 2); + } +} diff --git a/crates/solstice-vehicle/src/spec.rs b/crates/solstice-vehicle/src/spec.rs index 5469deb..f7b579f 100644 --- a/crates/solstice-vehicle/src/spec.rs +++ b/crates/solstice-vehicle/src/spec.rs @@ -143,6 +143,11 @@ pub struct Gearbox { pub efficiency: f32, /// The most torque the clutch can carry. pub clutch: f32, + /// How early an automatic changes up with the throttle barely open, as a share of the + /// engine speed it changes up at flat out. A racing car's is 1: it holds every gear to the + /// limiter. A road car's is under a half, and its gearbox kicks down when the foot goes + /// down. + pub cruise: f32, } /// A clutch-pack limited-slip differential: it resists its two wheels turning at different @@ -156,6 +161,25 @@ pub struct Differential { pub coast: f32, } +/// A four-wheel drive's transfer case: what joins the gearbox to both axles. +/// +/// A part-time system, as utes and most off-roaders have: in two-wheel drive only the rear axle +/// is driven; in four-wheel drive the front and rear propshafts are locked together, so that +/// neither axle can spin away from the other; and low range puts a second reduction after the +/// gearbox, for crawling. Each axle's differential can also be locked, which makes its two +/// wheels turn as one. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Transfer { + /// Low range's reduction: every gear's ratio is this many times shorter. + pub low: f32, + /// The front axle's share of the drive in four-wheel drive, as the load on it is shared. + pub front_share: f32, + /// The most torque the lock between the two propshafts carries, in newton metres. + pub lock: f32, + /// The most torque a locked differential carries across its axle. + pub locker: f32, +} + /// The air. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Aero { @@ -181,18 +205,35 @@ pub struct VehicleSpec { /// The box it hits walls and other cars with: its full size, and where its middle is. pub body_size: Vec3, pub body_at: Vec3, + /// A truck's tray, if it has one: an open box things are carried in. Its size inside, + /// across, deep and long, and where the middle of its floor is. The body is then that + /// box cut out of the back of it, so that what is put in the tray lies in it. + pub tray: Option<(Vec3, Vec3)>, + /// The places inside it that things can be put: a seat, a boot. Each a box shut in on + /// every side, its size across, high and long, and where the middle of its floor is. + /// The body is hollow there, so that what is put in one lies in it and stays in it. + pub holds: Vec<(Vec3, Vec3)>, + /// Whether its driver sits on the right, and gets out on that side: `driver right`. + pub driver_right: bool, pub front: Axle, pub rear: Axle, pub tyre: Tyre, pub engine: Engine, pub gearbox: Gearbox, pub differential: Differential, + /// The front axle's differential, on a car that drives both: open, on most. + pub front_differential: Differential, + /// What joins the two axles, on a car that drives both. + pub transfer: Option, pub aero: Aero, /// The most the front wheels turn, in radians, with the inner wheel at this. pub steering_lock: f32, /// How much more the inner wheel turns than the outer: 1 is true Ackermann, where every /// wheel rolls about one point, and 0 is parallel. pub ackermann: f32, + /// How quickly its wheel is turned from lock to lock, as a share of a racing car's: a + /// truck's steering is slow and heavy, and a driver's hands with it. + pub steering_quick: f32, /// The share of weight transfer under braking and under power that the suspension's links /// carry rather than its springs, which is what stops a car diving and squatting. pub anti_dive: f32, @@ -203,6 +244,22 @@ pub struct VehicleSpec { /// Whether a tail that steps out is caught: the engine eased, the rear brakes let go, /// and the outside front wheel braked, as a road car's stability control does. pub stability: bool, + /// Whether, in low range with the driver's feet off the pedals, it holds itself to a + /// walking pace down a hill with its brakes: hill descent control. + pub hill_descent: bool, +} + +impl Transfer { + /// A part-time transfer case, as a ute's: a 2.64 low range, the drive shared evenly, and + /// locks strong enough to hold whatever the engine sends. + pub fn part_time() -> Self { + Self { + low: 2.64, + front_share: 0.5, + lock: 30_000.0, + locker: 30_000.0, + } + } } impl VehicleSpec { @@ -220,6 +277,9 @@ impl VehicleSpec { centre: Vec3::new(0.0, 0.4, 0.04), body_size: Vec3::new(1.9, 0.9, 4.5), body_at: Vec3::new(0.0, 0.65, 0.0), + tray: None, + holds: Vec::new(), + driver_right: false, front: Axle { at: 1.32, track: 1.66, @@ -280,12 +340,19 @@ impl VehicleSpec { shift_seconds: 0.06, efficiency: 0.93, clutch: 900.0, + cruise: 1.0, }, differential: Differential { preload: 60.0, power: 0.45, coast: 0.3, }, + front_differential: Differential { + preload: 0.0, + power: 0.0, + coast: 0.0, + }, + transfer: None, aero: Aero { drag: 0.92, downforce: 1.9, @@ -293,11 +360,13 @@ impl VehicleSpec { }, steering_lock: 26.0_f32.to_radians(), ackermann: 0.6, + steering_quick: 1.0, anti_dive: 0.25, anti_squat: 0.3, abs: true, traction_control: true, stability: true, + hill_descent: false, } } @@ -372,10 +441,10 @@ impl VehicleSpec { values.iter().map(|w| number(w).map_err(&error)).collect() }; let settings: Vec = match keyword { - // A line for each point of the curve. - "torque" => Vec::new(), - "front" | "rear" | "tyre" | "engine" | "gearbox" | "diff" | "aero" | "steering" - | "geometry" | "assists" => values + // A line for each point of the curve, and for each place things can be put. + "torque" | "hold" => Vec::new(), + "front" | "rear" | "tyre" | "engine" | "gearbox" | "diff" | "front_diff" + | "transfer" | "aero" | "steering" | "geometry" | "assists" => values .iter() .filter_map(|word| word.split_once('=')) .map(|(key, _)| format!("{keyword} {key}")) @@ -403,6 +472,42 @@ impl VehicleSpec { spec.body_size = Vec3::new(read(sx)?, read(sy)?, read(sz)?); spec.body_at = Vec3::new(read(x)?, read(y)?, read(z)?); } + "tray" => { + let form = "expected `tray WIDTH DEPTH LENGTH at X Y Z`"; + let [sx, sy, sz, "at", x, y, z] = values else { + return Err(error(form.to_owned())); + }; + let read = |w: &str| number(w).map_err(&error); + let size = Vec3::new(read(sx)?, read(sy)?, read(sz)?); + if !(size.min_element() > 0.05 && size.max_element() < 10.0) { + return Err(error("a tray is from 5 cm to 10 m each way".to_owned())); + } + spec.tray = Some((size, Vec3::new(read(x)?, read(y)?, read(z)?))); + } + "driver" => { + spec.driver_right = match values { + ["left"] => false, + ["right"] => true, + _ => { + return Err(error( + "expected `driver left` or `driver right`".to_owned(), + )) + } + }; + } + "hold" => { + let form = "expected `hold WIDTH HEIGHT LENGTH at X Y Z`"; + let [sx, sy, sz, "at", x, y, z] = values else { + return Err(error(form.to_owned())); + }; + let read = |w: &str| number(w).map_err(&error); + let size = Vec3::new(read(sx)?, read(sy)?, read(sz)?); + if !(size.min_element() > 0.05 && size.max_element() < 10.0) { + return Err(error("a hold is from 5 cm to 10 m each way".to_owned())); + } + spec.holds + .push((size, Vec3::new(read(x)?, read(y)?, read(z)?))); + } "front" | "rear" => { let axle = if keyword == "front" { &mut spec.front @@ -452,6 +557,7 @@ impl VehicleSpec { "shift" => spec.gearbox.shift_seconds = read, "efficiency" => spec.gearbox.efficiency = read, "clutch" => spec.gearbox.clutch = read, + "cruise" => spec.gearbox.cruise = read, other => return Err(error(unknown("gearbox", other))), } } @@ -467,6 +573,30 @@ impl VehicleSpec { } } } + "front_diff" => { + for (key, value) in pairs(values).map_err(&error)? { + let read = number(value).map_err(&error)?; + match key { + "preload" => spec.front_differential.preload = read, + "power" => spec.front_differential.power = read, + "coast" => spec.front_differential.coast = read, + other => return Err(error(unknown("front_diff", other))), + } + } + } + "transfer" => { + let transfer = spec.transfer.get_or_insert(Transfer::part_time()); + for (key, value) in pairs(values).map_err(&error)? { + let read = number(value).map_err(&error)?; + match key { + "low" => transfer.low = read, + "front" => transfer.front_share = read, + "lock" => transfer.lock = read, + "locker" => transfer.locker = read, + other => return Err(error(unknown("transfer", other))), + } + } + } "aero" => { for (key, value) in pairs(values).map_err(&error)? { let read = number(value).map_err(&error)?; @@ -484,6 +614,7 @@ impl VehicleSpec { match key { "lock" => spec.steering_lock = read.to_radians(), "ackermann" => spec.ackermann = read, + "quick" => spec.steering_quick = read, other => return Err(error(unknown("steering", other))), } } @@ -505,6 +636,7 @@ impl VehicleSpec { "abs" => spec.abs = on, "traction" => spec.traction_control = on, "stability" => spec.stability = on, + "descent" => spec.hill_descent = on, other => return Err(error(unknown("assists", other))), } } @@ -513,7 +645,7 @@ impl VehicleSpec { return Err(error(format!( "unknown line `{other}`: a vehicle file has mass, inertia, centre, body, \ front, rear, tyre, engine, torque, gears, final, reverse, gearbox, diff, \ - aero, steering, geometry and assists lines" + front_diff, transfer, aero, steering, geometry and assists lines" ))) } } @@ -603,8 +735,25 @@ impl VehicleSpec { if !self.front.driven && !self.rear.driven { return Err("one axle must be driven".into()); } - if self.front.driven && self.rear.driven { - return Err("four-wheel drive isn't built yet: drive one axle".into()); + match (&self.transfer, self.front.driven && self.rear.driven) { + (None, true) => { + return Err( + "four-wheel drive needs a `transfer` line: what joins the two axles".into(), + ) + } + (Some(_), false) => { + return Err("a `transfer` joins two driven axles: drive both".into()); + } + (Some(transfer), true) => { + within("the transfer's low range", transfer.low, 1.0, 10.0)?; + share("the transfer's front share", transfer.front_share)?; + if !(0.0..=1.0e6).contains(&transfer.lock) + || !(0.0..=1.0e6).contains(&transfer.locker) + { + return Err("the transfer's locks carry from 0 to 1,000,000 N m".into()); + } + } + (None, false) => {} } let tyre = &self.tyre; for (name, value, low, high) in [ @@ -639,6 +788,9 @@ impl VehicleSpec { if !(0.0..1.0).contains(&tyre.load_sensitivity) { return Err("the tyre's load sensitivity is between 0 and 1".into()); } + if !(0.3..=2.0).contains(&tyre.tread.0) || !(0.3..=2.0).contains(&tyre.tread.1) { + return Err("the tyre's tread is between 0.3 and 2 on firm ground and on soft".into()); + } let engine = &self.engine; if engine.torque.len() < 2 { return Err("the engine needs at least two `torque` points".into()); @@ -687,13 +839,18 @@ impl VehicleSpec { if !(0.5..=1.0).contains(&gearbox.efficiency) { return Err("the gearbox's efficiency is between 0.5 and 1".into()); } - let diff = &self.differential; - if !(0.0..=10_000.0).contains(&diff.preload) || !(0.0..=1.0).contains(&diff.power) { - return Err( - "the diff's preload is from 0 to 10,000 N m, and its power lock from 0 to 1".into(), - ); + if !(0.2..=1.0).contains(&gearbox.cruise) { + return Err("the gearbox's cruise is a share of its change-up speed, 0.2 to 1".into()); + } + for diff in [&self.differential, &self.front_differential] { + if !(0.0..=10_000.0).contains(&diff.preload) || !(0.0..=1.0).contains(&diff.power) { + return Err( + "the diff's preload is from 0 to 10,000 N m, and its power lock from 0 to 1" + .into(), + ); + } + share("the diff's coast lock", diff.coast)?; } - share("the diff's coast lock", diff.coast)?; let aero = 0.0..=50.0; if !aero.contains(&self.aero.drag) || !aero.contains(&self.aero.downforce) { return Err("drag and downforce are from 0 to 50".into()); @@ -703,6 +860,9 @@ impl VehicleSpec { return Err("the steering lock is above 0 and below 68 degrees".into()); } share("ackermann", self.ackermann)?; + if !(0.1..=2.0).contains(&self.steering_quick) { + return Err("how quick the steering is, is from 0.1 to 2".into()); + } share("anti_dive", self.anti_dive)?; share("anti_squat", self.anti_squat)?; Ok(()) @@ -723,6 +883,23 @@ impl VehicleSpec { "body {} {} {} at {} {} {}", s.x, s.y, s.z, a.x, a.y, a.z ); + if let Some((s, a)) = self.tray { + let _ = writeln!( + text, + "tray {} {} {} at {} {} {}", + s.x, s.y, s.z, a.x, a.y, a.z + ); + } + if self.driver_right { + let _ = writeln!(text, "driver right"); + } + for (s, a) in &self.holds { + let _ = writeln!( + text, + "hold {} {} {} at {} {} {}", + s.x, s.y, s.z, a.x, a.y, a.z + ); + } for (name, axle) in [("front", &self.front), ("rear", &self.rear)] { let _ = writeln!( text, @@ -761,8 +938,8 @@ impl VehicleSpec { ); let _ = writeln!( text, - "tyre load={} sensitivity={} relaxation={}", - t.nominal_load, t.load_sensitivity, t.relaxation + "tyre load={} sensitivity={} relaxation={} tread={},{}", + t.nominal_load, t.load_sensitivity, t.relaxation, t.tread.0, t.tread.1 ); let e = &self.engine; let _ = writeln!( @@ -780,8 +957,8 @@ impl VehicleSpec { let _ = writeln!(text, "reverse {}", g.reverse); let _ = writeln!( text, - "gearbox shift={} efficiency={} clutch={}", - g.shift_seconds, g.efficiency, g.clutch + "gearbox shift={} efficiency={} clutch={} cruise={}", + g.shift_seconds, g.efficiency, g.clutch, g.cruise ); let d = &self.differential; let _ = writeln!( @@ -789,6 +966,19 @@ impl VehicleSpec { "diff preload={} power={} coast={}", d.preload, d.power, d.coast ); + if let Some(transfer) = &self.transfer { + let d = &self.front_differential; + let _ = writeln!( + text, + "front_diff preload={} power={} coast={}", + d.preload, d.power, d.coast + ); + let _ = writeln!( + text, + "transfer low={} front={} lock={} locker={}", + transfer.low, transfer.front_share, transfer.lock, transfer.locker + ); + } let _ = writeln!( text, "aero drag={} downforce={} balance={}", @@ -796,9 +986,15 @@ impl VehicleSpec { ); let _ = writeln!( text, - "steering lock={} ackermann={}", + "steering lock={} ackermann={}{}", self.steering_lock.to_degrees(), - self.ackermann + self.ackermann, + // Only a car whose steering is not a racing car's says so. + if self.steering_quick == 1.0 { + String::new() + } else { + format!(" quick={}", self.steering_quick) + } ); let _ = writeln!( text, @@ -807,10 +1003,16 @@ impl VehicleSpec { ); let _ = writeln!( text, - "assists abs={} traction={} stability={}", + "assists abs={} traction={} stability={}{}", yes(self.abs), yes(self.traction_control), - yes(self.stability) + yes(self.stability), + // Only a car that has it says so: every other file reads as it always did. + if self.hill_descent { + " descent=yes" + } else { + "" + } ); text } @@ -891,6 +1093,7 @@ fn set_tyre(tyre: &mut Tyre, key: &str, value: &str) -> Result<(), String> { "load" => tyre.nominal_load = number(value)?, "sensitivity" => tyre.load_sensitivity = number(value)?, "relaxation" => tyre.relaxation = number(value)?, + "tread" => tyre.tread = pair(value)?, other => return Err(unknown("tyre", other)), } Ok(()) @@ -983,6 +1186,28 @@ mod tests { assert_eq!(back.to_text(), text); } + #[test] + fn a_four_wheel_drive_reads_back_what_it_wrote() { + let mut spec = VehicleSpec::gt(); + spec.front.driven = true; + spec.transfer = Some(Transfer { + low: 2.72, + front_share: 0.45, + lock: 12_000.0, + locker: 9000.0, + }); + spec.front_differential.preload = 25.0; + spec.check().unwrap(); + let text = spec.to_text(); + let back = VehicleSpec::parse(&text).unwrap(); + assert_eq!(back.transfer, spec.transfer); + assert_eq!(back.front_differential, spec.front_differential); + assert_eq!(back.to_text(), text); + // Without the line that joins the axles, it is a mistake. + spec.transfer = None; + assert!(spec.check().is_err()); + } + #[test] fn an_empty_file_is_the_gt() { assert_eq!( @@ -1005,6 +1230,8 @@ mod tests { ("torque 2000 300\ntorque 1000 300", 1, "rise in rpm"), ("centre 0 0.4 3", 1, "between the axles"), ("front driven=yes", 1, "four-wheel drive"), + ("transfer low=2.6", 1, "drive both"), + ("front driven=yes\ntransfer low=0.5", 1, "low range"), ("assists abs=maybe", 1, "yes or no"), ("body 1 1 1", 1, "body SX SY SZ at"), ("tyre along=2.5,0", 1, "C between 1 and 2"), diff --git a/crates/solstice-vehicle/src/surface.rs b/crates/solstice-vehicle/src/surface.rs index 0423742..698da0e 100644 --- a/crates/solstice-vehicle/src/surface.rs +++ b/crates/solstice-vehicle/src/surface.rs @@ -1,4 +1,11 @@ //! What a tyre runs on. +//! +//! A circuit's surfaces are hard: asphalt, kerbs, concrete, with grass and gravel beside them. +//! Off the road the ground gives way. A tyre on clay, mud or sand sinks until the ground under +//! it carries its load, ploughs a rut as it rolls, and grips best while slipping far more than +//! it would on a road, as its tread shears the soil rather than rubber the stone. Rain changes +//! all of it: hard clay turns to grease, and mud softens. Each surface gives the numbers for +//! that ([`SurfaceGrip`]); the car does the rest (`vehicle.rs`). /// A kind of ground, as a tyre feels it. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] @@ -14,6 +21,20 @@ pub enum Surface { Gravel, /// Bare concrete: paddock and run-off. Concrete, + /// A bush track's hard-packed clay and dirt: firm in the dry, greasy in the wet. + Dirt, + /// Mud a wheel sinks a hand's depth into: a track's wet hollows and wheel ruts. + Mud, + /// A bog hole: deep, soft mud that stops a car driven by one axle. + Bog, + /// The floor of the bush off the track: leaf litter, bark and sticks over soft soil. + Litter, + /// Bare rock: slabs, ledges and steps. It grips well and gives nothing. + Rock, + /// A creek's bed where a track fords it: stones and gravel under moving water. + Ford, + /// Loose dry sand, as in a creek's bank or a washout. + Sand, } /// How a surface changes what a tyre can do. @@ -21,6 +42,8 @@ pub enum Surface { pub struct SurfaceGrip { /// Times the tyre's own friction on dry asphalt. pub grip: f32, + /// Times that again when it is soaked: wet clay keeps half its grip, wet rock most of it. + pub wet: f32, /// Rolling resistance, as a share of the load on the tyre: at a crawl, and at speed. Loose /// ground drags harder the faster a tyre ploughs through it; a car can crawl out of a /// gravel trap that stopped it from a hundred. @@ -30,15 +53,35 @@ pub struct SurfaceGrip { pub bump_height: f32, /// How far apart those bumps are, in metres. pub bump_length: f32, + /// How many times further a tyre must slip here to grip its best than on a road. Soil is + /// sheared, not gripped: the force builds over centimetres of slip, not millimetres. + pub slip: f32, + /// How much of the fall in grip past its best a tyre is spared here, from 0 to 1. On a + /// road a spinning tyre slides on rubber and grips a quarter less. Soil is sheared by the + /// tread, and goes on pushing back however fast the wheel turns (Janosi and Hanamoto), so + /// a tyre spinning in mud pulls nearly as hard as one that is not: what it loses, it + /// loses by digging itself in. + pub hold: f32, + /// How far a tyre carrying its share of a standing car sinks in, in metres. + pub sink: f32, + /// How much further a wheel spinning at twice the speed it rolls at digs itself in. + pub dig: f32, } impl Surface { - pub const ALL: [Self; 5] = [ + pub const ALL: [Self; 12] = [ Self::Asphalt, Self::Kerb, Self::Grass, Self::Gravel, Self::Concrete, + Self::Dirt, + Self::Mud, + Self::Bog, + Self::Litter, + Self::Rock, + Self::Ford, + Self::Sand, ]; pub fn name(self) -> &'static str { @@ -48,6 +91,13 @@ impl Surface { Self::Grass => "grass", Self::Gravel => "gravel", Self::Concrete => "concrete", + Self::Dirt => "dirt", + Self::Mud => "mud", + Self::Bog => "bog", + Self::Litter => "litter", + Self::Rock => "rock", + Self::Ford => "ford", + Self::Sand => "sand", } } @@ -55,50 +105,201 @@ impl Surface { Self::ALL.into_iter().find(|s| s.name() == name) } - /// Figures for a slick tyre in the dry. Grass and gravel are from the usual ranges quoted - /// for race tyres off the track: a third to a half of the grip, and a gravel trap, which a - /// car sinks into, slowing it at about half a g by drag alone. + /// A number for this surface that fits a byte, for maps of the ground: its place in + /// [`Surface::ALL`]. + pub fn index(self) -> u8 { + Self::ALL + .iter() + .position(|&surface| surface == self) + .unwrap_or(0) as u8 + } + + pub fn from_index(index: u8) -> Option { + Self::ALL.get(index as usize).copied() + } + + /// Whether a tyre sinks into it: soft ground, which sprays and holds a car back. + pub fn is_soft(self) -> bool { + self.grip().sink > 0.02 + } + + /// The road surfaces are figures for a slick tyre in the dry. Grass and gravel are from + /// the usual ranges quoted for race tyres off the track: a third to a half of the grip, and + /// a gravel trap, which a car sinks into, slowing it at about half a g by drag alone. + /// + /// The off-road ones follow the terramechanics of Bekker and Wong (*Theory of Ground + /// Vehicles*): friction of a tyre on firm soil of 0.6 to 0.8, half that on wet clay and + /// less in mud; motion resistance of a few hundredths of the load on a firm track, a tenth + /// to a quarter in soft mud; and the slip for the best pull several times a road's. pub fn grip(self) -> SurfaceGrip { + let hard = |grip: f32, wet: f32, rolling: f32| SurfaceGrip { + grip, + wet, + rolling_slow: rolling, + rolling, + bump_height: 0.0, + bump_length: 1.0, + slip: 1.0, + hold: 0.0, + sink: 0.0, + dig: 0.0, + }; match self { - Self::Asphalt => SurfaceGrip { - grip: 1.0, - rolling_slow: 0.012, - rolling: 0.012, - bump_height: 0.0, - bump_length: 1.0, - }, - Self::Kerb => SurfaceGrip { - grip: 0.9, - rolling_slow: 0.015, - rolling: 0.015, - bump_height: 0.0, - bump_length: 1.0, - }, + Self::Asphalt => hard(1.0, 0.78, 0.012), + Self::Kerb => hard(0.9, 0.6, 0.015), + Self::Concrete => hard(0.93, 0.8, 0.013), Self::Grass => SurfaceGrip { grip: 0.45, + wet: 0.7, rolling_slow: 0.05, rolling: 0.07, bump_height: 0.018, bump_length: 1.3, + ..hard(0.0, 0.0, 0.0) }, Self::Gravel => SurfaceGrip { grip: 0.42, + wet: 0.92, rolling_slow: 0.14, rolling: 0.55, bump_height: 0.025, bump_length: 0.9, + ..hard(0.0, 0.0, 0.0) + }, + Self::Dirt => SurfaceGrip { + grip: 0.74, + wet: 0.6, + rolling_slow: 0.028, + rolling: 0.05, + bump_height: 0.022, + bump_length: 1.1, + slip: 1.7, + hold: 0.7, + sink: 0.004, + dig: 0.012, }, - Self::Concrete => SurfaceGrip { - grip: 0.93, - rolling_slow: 0.013, - rolling: 0.013, - bump_height: 0.0, - bump_length: 1.0, + Self::Mud => SurfaceGrip { + grip: 0.46, + wet: 0.85, + rolling_slow: 0.06, + rolling: 0.2, + bump_height: 0.035, + bump_length: 0.8, + slip: 2.6, + hold: 0.9, + sink: 0.07, + dig: 0.05, + }, + Self::Bog => SurfaceGrip { + grip: 0.38, + wet: 0.88, + rolling_slow: 0.09, + rolling: 0.32, + bump_height: 0.03, + bump_length: 0.9, + slip: 3.0, + hold: 0.9, + sink: 0.14, + dig: 0.05, + }, + Self::Litter => SurfaceGrip { + grip: 0.58, + wet: 0.75, + rolling_slow: 0.055, + rolling: 0.1, + bump_height: 0.04, + bump_length: 0.75, + slip: 1.9, + hold: 0.75, + sink: 0.015, + dig: 0.03, + }, + Self::Rock => SurfaceGrip { + grip: 0.86, + wet: 0.78, + rolling_slow: 0.02, + rolling: 0.025, + bump_height: 0.05, + bump_length: 0.55, + slip: 1.15, + hold: 0.25, + sink: 0.0, + dig: 0.0, + }, + Self::Ford => SurfaceGrip { + grip: 0.52, + wet: 1.0, + rolling_slow: 0.1, + rolling: 0.6, + bump_height: 0.045, + bump_length: 0.5, + slip: 1.6, + hold: 0.7, + sink: 0.03, + dig: 0.03, + }, + Self::Sand => SurfaceGrip { + grip: 0.5, + wet: 1.15, + rolling_slow: 0.11, + rolling: 0.3, + bump_height: 0.02, + bump_length: 1.4, + slip: 2.4, + hold: 0.9, + sink: 0.055, + dig: 0.09, }, } } } +/// How a surface takes a tyre's mark: what is left in the ground where one has been +/// ([`crate::rut`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Soil { + /// How wet what a tyre churns up is, from 0 to 1, and how wet it stays once the churned + /// ground has dried: a bog stays sodden, a clay track dries pale. + pub wet: f32, + pub stays: f32, + /// How much bare soil a tyre leaves showing where it broke the ground: all of it in + /// mud, most of it through leaf litter, none of it in sand, which is sand all the way + /// down. + pub churn: f32, + /// The share of what a tyre presses out of its rut that is heaped up beside it. Mud + /// flows aside; litter and dry soil pack down. + pub berm: f32, + /// How well it holds a tread's print: damp clay holds every lug, slop closes over it. + pub print: f32, +} + +impl Surface { + /// How this ground takes a tyre's mark when it is this wet: 0 dry, 1 soaked. + pub fn soil(self, wetness: f32) -> Soil { + let w = wetness.clamp(0.0, 1.0); + let soil = |wet: f32, stays: f32, churn: f32, berm: f32, print: f32| Soil { + wet, + stays, + churn, + berm, + print, + }; + match self { + Self::Asphalt | Self::Kerb | Self::Concrete | Self::Rock => { + soil(0.0, 0.0, 0.0, 0.0, 0.0) + } + Self::Grass => soil(0.2 + 0.5 * w, 0.1 + 0.3 * w, 0.5, 0.2, 0.5), + Self::Gravel => soil(0.3 * w, 0.0, 0.0, 0.45, 0.2), + Self::Dirt => soil(0.15 + 0.75 * w, 0.05 + 0.45 * w, 0.45 + 0.3 * w, 0.25, 0.85), + Self::Mud => soil(0.9, 0.55 + 0.25 * w, 1.0, 0.5, 0.85), + Self::Bog => soil(1.0, 0.8 + 0.2 * w, 1.0, 0.55, 0.45), + Self::Litter => soil(0.3 + 0.5 * w, 0.12 + 0.4 * w, 0.8, 0.2, 0.6), + Self::Ford => soil(1.0, 1.0, 0.25, 0.2, 0.2), + Self::Sand => soil(0.05 + 0.6 * w, 0.3 * w, 0.15, 0.45, 0.7), + } + } +} + impl SurfaceGrip { /// Rolling resistance at a speed, in metres a second, as a share of the load. pub fn rolling_at(&self, speed: f32) -> f32 { @@ -106,6 +307,23 @@ impl SurfaceGrip { const FULL: f32 = 14.0; self.rolling_slow + (self.rolling - self.rolling_slow) * (speed.abs() / FULL).min(1.0) } + + /// Its grip when it is this wet: 0 dry, 1 soaked. + pub fn grip_at(&self, wetness: f32) -> f32 { + self.grip * (1.0 + (self.wet - 1.0) * wetness.clamp(0.0, 1.0)) + } + + /// How far a tyre sinks in when the ground is this wet: rain softens what was already + /// soft, by a third as much again, and firm ground a little. + pub fn sink_at(&self, wetness: f32) -> f32 { + let wetness = wetness.clamp(0.0, 1.0); + self.sink * (1.0 + 0.3 * wetness) + + if self.slip > 1.5 { + 0.012 * wetness + } else { + 0.0 + } + } } /// The height of a rough surface's bumps at a spot: smooth, repeatable noise between -1 and 1, @@ -140,8 +358,10 @@ mod tests { fn names_read_back() { for surface in Surface::ALL { assert_eq!(Surface::from_name(surface.name()), Some(surface)); + assert_eq!(Surface::from_index(surface.index()), Some(surface)); } assert_eq!(Surface::from_name("ice"), None); + assert_eq!(Surface::from_index(200), None); } #[test] @@ -157,6 +377,55 @@ mod tests { assert_eq!(road.rolling_at(0.0), road.rolling_at(80.0)); } + #[test] + fn every_surface_is_one_a_tyre_can_be_on() { + for surface in Surface::ALL { + let grip = surface.grip(); + assert!((0.2..=1.0).contains(&grip.grip), "{surface:?}"); + assert!((0.4..=1.2).contains(&grip.wet), "{surface:?}"); + assert!(grip.rolling >= grip.rolling_slow && grip.rolling_slow > 0.0); + assert!(grip.slip >= 1.0 && grip.sink >= 0.0 && grip.dig >= 0.0); + assert!((0.0..=1.0).contains(&grip.hold)); + assert!(grip.bump_length > 0.0); + } + } + + #[test] + fn rain_makes_clay_greasy_and_mud_deeper() { + let dirt = Surface::Dirt.grip(); + assert_eq!(dirt.grip_at(0.0), dirt.grip); + assert!(dirt.grip_at(1.0) < dirt.grip * 0.65); + assert!(dirt.grip_at(0.5) < dirt.grip && dirt.grip_at(0.5) > dirt.grip_at(1.0)); + let bog = Surface::Bog.grip(); + assert!(bog.sink_at(1.0) > bog.sink * 1.3); + // A road is as hard wet as dry. + assert_eq!(Surface::Asphalt.grip().sink_at(1.0), 0.0); + // The soft ones are the ones that hold a car back. + assert!(Surface::Mud.is_soft() && Surface::Bog.is_soft() && Surface::Sand.is_soft()); + assert!(!Surface::Dirt.is_soft() && !Surface::Rock.is_soft()); + } + + #[test] + fn soft_ground_keeps_a_mark_and_hard_ground_none() { + for surface in Surface::ALL { + for wetness in [0.0, 0.5, 1.0] { + let soil = surface.soil(wetness); + for share in [soil.wet, soil.stays, soil.churn, soil.berm, soil.print] { + assert!((0.0..=1.0).contains(&share), "{surface:?}"); + } + assert!( + soil.stays <= soil.wet, + "{surface:?} dries wetter than it was" + ); + } + } + assert_eq!(Surface::Rock.soil(1.0).churn, 0.0); + assert!(Surface::Bog.soil(0.0).stays > Surface::Mud.soil(0.0).stays); + // Rain makes a clay track's ruts wet; a bog's are wet whatever the weather. + assert!(Surface::Dirt.soil(1.0).wet > Surface::Dirt.soil(0.0).wet + 0.5); + assert_eq!(Surface::Bog.soil(0.0).wet, 1.0); + } + #[test] fn bumps_are_smooth_bounded_and_repeat() { let mut last = bump(0.0, 0.3, 1.3); diff --git a/crates/solstice-vehicle/src/tyre.rs b/crates/solstice-vehicle/src/tyre.rs index 81bb7e0..a5e8e2f 100644 --- a/crates/solstice-vehicle/src/tyre.rs +++ b/crates/solstice-vehicle/src/tyre.rs @@ -84,6 +84,10 @@ pub struct Tyre { pub load_sensitivity: f32, /// How far the tyre rolls, in metres, before its side force catches up with its slip angle. pub relaxation: f32, + /// What its tread makes of the ground: times its grip on firm ground (a road, rock, hard + /// clay), and on soft ground that a tyre sinks into (mud, sand, a bog). A road tyre is + /// more than 1 and less; a mud tyre, less than 1 and more. + pub tread: (f32, f32), } impl Tyre { @@ -103,9 +107,16 @@ impl Tyre { nominal_load: 4000.0, load_sensitivity: 0.14, relaxation: 0.28, + tread: (1.0, 1.0), } } + /// What its tread makes of ground a tyre sinks this far into, in metres: times its grip. + pub fn tread_on(&self, sink: f32) -> f32 { + let soft = ((sink - 0.008) / 0.04).clamp(0.0, 1.0); + self.tread.0 + (self.tread.1 - self.tread.0) * soft + } + /// The friction a tyre has under this load, as a multiple of the figure at its nominal one. pub fn load_factor(&self, load: f32) -> f32 { (1.0 - self.load_sensitivity * (load / self.nominal_load - 1.0)).clamp(0.55, 1.2) diff --git a/crates/solstice-vehicle/src/vehicle.rs b/crates/solstice-vehicle/src/vehicle.rs index e9ca71d..157f39b 100644 --- a/crates/solstice-vehicle/src/vehicle.rs +++ b/crates/solstice-vehicle/src/vehicle.rs @@ -7,7 +7,12 @@ //! how far the wheel has risen, the spring, damper, anti-roll bar and bump stop give the load //! on its tyre. //! 2. **Solves the drivetrain**: the engine, clutch, gearbox, differential, brakes and the two -//! driven wheels, with the tyres' grip on the road, all at once (see [`drivetrain`]). +//! driven wheels, with the tyres' grip on the road, all at once (see [`drivetrain`]). A +//! four-wheel drive solves all four wheels, with its transfer case and both differentials. +//! +//! Off the road the ground is soft. A tyre sinks into it by what the surface says +//! ([`crate::surface::SurfaceGrip`]), further the harder it is pressed and the more it spins, +//! and the rut it ploughs holds the car back by how deep it is. //! 3. **Sums the forces** on the body: each tyre's, gravity, drag and downforce. //! 4. **Moves the body**: its velocity and spin, then its place and turn. //! @@ -15,7 +20,8 @@ //! same body and deals with what it hits: it is handed where this step ended (see //! [`Body`]), and adds what the collision did. -use crate::drivetrain::{self, Coupling, DrivenAxle}; +use crate::drivetrain::{self, Coupling, Driveline, DrivenAxle}; +use crate::rut::Press; use crate::spec::{VehicleSpec, AIR_DENSITY, RPM_TO_RADIANS}; use crate::surface::{bump, Surface}; use crate::tyre::TyreCurves; @@ -56,6 +62,46 @@ const STABILITY_BRAKE: f32 = 0.6; const STABILITY_RELEASE: f32 = 0.55; /// Below this speed, in metres a second, there is nothing for it to do. const STABILITY_SPEED: f32 = 7.0; +/// How long, in seconds, a tyre takes to sink into soft ground, and to climb back out of it. +const SINK_SECONDS: f32 = 0.22; +const RISE_SECONDS: f32 = 0.5; +/// The drag of ploughing a rut, as a share of the tyre's load, for a rut as deep as the tyre's +/// radius (Bekker's compaction resistance, near enough a straight line over the depths here). +const RUT_DRAG: f32 = 0.35; +/// A wheel that spins goes on digging where it stands: how far below the floor of its own +/// rut it reaches for, as a multiple of what the ground says a spinning wheel digs. +const DIG_ON: f32 = 0.25; +/// The deepest a wheel can dig itself into ground, as multiples of how far it sinks there +/// and of how far spinning digs it, and as a share of its own radius: by then it is on its +/// axle. +const DIG_SOFT: f32 = 1.5; +const DIG_SPUN: f32 = 2.5; +const DIG_RADIUS: f32 = 0.7; +/// How many lugs a tyre's tread has round it: what it prints in soft ground. +pub const TREAD_LUGS: f32 = 32.0; +/// A tyre's width, as a multiple of its radius. +const TYRE_WIDTH: f32 = 0.7; +/// How far a tyre rolls, in metres, before the water it came out of a creek with is mostly +/// off it, and the mud it came out of a bog with; and how far through water before that +/// mud is washed off. +const CARRIES_WATER: f32 = 18.0; +const CARRIES_MUD: f32 = 30.0; +const WASHES_MUD: f32 = 4.0; +/// The most of a wheel's brake a four-wheel drive's traction control puts on to stop it +/// spinning: enough to send a good share of the drive across an open differential, and less +/// than locking it does. +const BRAKE_TRACTION: f32 = 0.3; +/// Hill descent control: the speed it holds a car to, in metres a second, and the most of the +/// brakes it uses to do it. +const DESCENT_SPEED: f32 = 1.7; +const DESCENT_BRAKE: f32 = 0.75; +/// Tyres let down for soft ground, to about half their road pressure: the tread lies longer +/// and wider on the ground. On soil it grips this much better and sinks this much less; on a +/// hard road it squirms, gripping a little worse and rolling this much harder. +const AIRED_GRIP: f32 = 1.17; +const AIRED_SINK: f32 = 0.62; +const AIRED_ROAD_GRIP: f32 = 0.93; +const AIRED_ROLLING: f32 = 1.6; /// How far above idle, in rpm, the clutch starts to bite when pulling away flat out. const LAUNCH_REVS: f32 = 2600.0; /// Within this many rpm of the gearbox's speed, the engine counts as turning with it. @@ -75,6 +121,17 @@ pub struct Contact { pub trait Ground { /// What a ray from `from` along the unit vector `direction` meets first within `reach`. fn cast(&self, from: Vec3, direction: Vec3, reach: f32) -> Option; + + /// How far the ground at a place has been pressed down since it was made, in metres: + /// the depth of the rut there, below zero on the berm beside one ([`crate::rut`]). + /// Ground that keeps no ruts has none. + fn rut(&self, _at: Vec3) -> f32 { + 0.0 + } + + /// Takes a tyre's mark: where its contact has been over a step, and how deep. Ground + /// that keeps no ruts does nothing with it. + fn press(&self, _press: &Press) {} } /// Flat ground at a height, of one surface: for tests, and for tuning a car. @@ -135,6 +192,43 @@ impl Body { } } +/// What a four-wheel drive's transfer case is set to. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum DriveMode { + /// Two-wheel drive, high range: the rear axle alone, for the road. + #[default] + TwoHigh, + /// Four-wheel drive, high range: both axles, locked together. + FourHigh, + /// Four-wheel drive, low range: the same, geared down for crawling. + FourLow, +} + +impl DriveMode { + /// The setting after this one, as its lever goes: 2H, 4H, 4L, and round again. + pub fn next(self) -> Self { + match self { + Self::TwoHigh => Self::FourHigh, + Self::FourHigh => Self::FourLow, + Self::FourLow => Self::TwoHigh, + } + } + + /// As it is written on the lever. + pub fn name(self) -> &'static str { + match self { + Self::TwoHigh => "2H", + Self::FourHigh => "4H", + Self::FourLow => "4L", + } + } + + /// Whether both axles are driven. + pub fn four(self) -> bool { + self != Self::TwoHigh + } +} + /// What the driver is doing with the car, after any help (see [`crate::driver`]). #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct Controls { @@ -159,6 +253,8 @@ pub struct Wheel { pub angle: f32, /// How far it has risen from where it rests, in metres: below zero, hanging. pub travel: f32, + /// How far its tyre has sunk into soft ground, in metres. + pub sink: f32, /// How far it is steered, in radians: above zero to the right. pub steer: f32, /// How hard its tyre is pressed to the ground, in newtons. @@ -192,6 +288,15 @@ pub struct Telemetry { pub stability_active: bool, /// Whether the engine is at its limiter. pub limiter: bool, + /// What a four-wheel drive's transfer case is set to, and whether the front and the rear + /// differentials are locked. + pub drive: DriveMode, + pub front_locked: bool, + pub rear_locked: bool, + /// Whether its tyres are let down for soft ground, and whether hill descent control is + /// holding it back. + pub aired_down: bool, + pub descent_active: bool, } /// A gear change under way. @@ -206,6 +311,8 @@ struct Shift { #[derive(Clone, Debug)] pub struct Vehicle { spec: VehicleSpec, + /// What it weighs with nothing in it, in kilograms. + unladen: f32, curves: TyreCurves, gravity: f32, /// The load on a front wheel and on a rear one, standing still. @@ -224,6 +331,22 @@ pub struct Vehicle { /// radians, above zero when it slides to the right. rear_slide: f32, limiting: bool, + /// A four-wheel drive's transfer case, and whether each differential is locked: front, + /// then rear. + drive: DriveMode, + lockers: (bool, bool), + /// How wet the ground is, from 0, dry, to 1, soaked: rain makes clay greasy and mud deep. + wetness: f32, + /// Whether its tyres are let down for soft ground. + aired_down: bool, + /// Where each tyre met the ground in the last short step, if it did. + touching: [Option; 4], + /// Where each tyre's last mark on the ground ended, and where in its pattern each + /// tyre's tread is, in radians. + trail: [Option; 4], + tread: [f32; 4], + /// What each tyre carries from where it has been, from 0 to 1: water, and mud. + carried: [(f32, f32); 4], telemetry: Telemetry, } @@ -241,11 +364,11 @@ impl Vehicle { ..Wheel::default() }; Self { + unladen: spec.mass, curves: spec.tyre.curves(), static_loads: spec.static_loads(gravity), engine_speed: spec.engine.idle * RPM_TO_RADIANS, gravity, - spec, wheels: [wheel; 4], gear: 0, shift: None, @@ -253,14 +376,86 @@ impl Vehicle { traction_share: 1.0, rear_slide: 0.0, limiting: false, + // A four-wheel drive starts with both axles driven: it is what it is for. + drive: if spec.transfer.is_some() { + DriveMode::FourHigh + } else { + DriveMode::TwoHigh + }, + lockers: (false, false), + wetness: 0.0, + aired_down: false, + touching: [None; 4], + trail: [None; 4], + tread: [0.0; 4], + carried: [(0.0, 0.0); 4], + spec, telemetry: Telemetry::default(), } } + /// What the transfer case is set to. A car without one is always in two-wheel drive. + pub fn drive_mode(&self) -> DriveMode { + self.drive + } + + /// Sets the transfer case, on a car that has one. + pub fn set_drive_mode(&mut self, mode: DriveMode) { + if self.spec.transfer.is_some() { + self.drive = mode; + } + } + + /// Whether the front and the rear differentials are locked. + pub fn lockers(&self) -> (bool, bool) { + self.lockers + } + + /// Locks or frees each differential, on a car with a transfer case. The front one only + /// locks in four-wheel drive, as its axle is only driven then. + pub fn set_lockers(&mut self, front: bool, rear: bool) { + if self.spec.transfer.is_some() { + self.lockers = (front, rear); + } + } + + /// Says how wet the ground is, from 0, dry, to 1, soaked. + pub fn set_wetness(&mut self, wetness: f32) { + self.wetness = if wetness.is_finite() { + wetness.clamp(0.0, 1.0) + } else { + 0.0 + }; + } + + pub fn wetness(&self) -> f32 { + self.wetness + } + + /// Lets the tyres down for soft ground, or pumps them back up for the road. + pub fn set_aired_down(&mut self, aired_down: bool) { + self.aired_down = aired_down; + } + + pub fn aired_down(&self) -> bool { + self.aired_down + } + pub fn spec(&self) -> &VehicleSpec { &self.spec } + /// Loads it: what is carried in it, in kilograms, is that much more for its engine to + /// move, its brakes to stop and its springs to hold up. + pub fn set_payload(&mut self, kilograms: f32) { + self.spec.mass = self.unladen + kilograms.max(0.0); + } + + /// What it is carrying, in kilograms. + pub fn payload(&self) -> f32 { + self.spec.mass - self.unladen + } + pub fn telemetry(&self) -> &Telemetry { &self.telemetry } @@ -300,6 +495,88 @@ impl Vehicle { self.clutch_torque = 0.0; self.traction_share = 1.0; self.rear_slide = 0.0; + self.touching = [None; 4]; + self.trail = [None; 4]; + } + + /// What each tyre carries from where it has been, from 0 to 1: water, then mud. A + /// tyre out of a creek leaves wet tracks; one out of a bog, muddy ones. + pub fn carried(&self) -> [(f32, f32); 4] { + self.carried + } + + /// The deepest a wheel of this radius can dig itself into a surface, in metres: as far + /// as it sinks there and a spinning wheel digs, and no further than its axle. + fn deepest(&self, surface: Surface, radius: f32) -> f32 { + let grip = surface.grip(); + let soft = grip.sink_at(self.wetness) * if self.aired_down { AIRED_SINK } else { 1.0 }; + (soft * DIG_SOFT + grip.dig * DIG_SPUN).min(DIG_RADIUS * radius) + } + + /// Leaves each tyre's mark on the ground it rolled over in the step just taken: a rut + /// as deep as the tyre has sunk, printed with its tread, and as wet and as churned as + /// the ground there is and as the tyre came to it. + fn mark(&mut self, body: &Body, ground: &dyn Ground, seconds: f32) { + use std::f32::consts::TAU; + for index in 0..4 { + let wheel = self.wheels[index]; + let radius = self.spec.axle(index).radius; + let turned = wheel.speed * seconds * TREAD_LUGS; + let phase = self.tread[index]; + self.tread[index] = (phase + turned).rem_euclid(TAU); + let rolled = (wheel.speed * radius * seconds).abs(); + let (mut water, mut mud) = self.carried[index]; + water *= (-rolled / CARRIES_WATER).exp(); + mud *= (-rolled / CARRIES_MUD).exp(); + let Some(at) = self.touching[index].filter(|_| wheel.load > 0.0) else { + self.carried[index] = (water, mud); + self.trail[index] = None; + continue; + }; + let soil = wheel.surface.soil(self.wetness); + // No deeper than this ground can be pressed: a tyre still climbing out of a + // bog as it comes onto rock leaves the rock as it was. + let depth = wheel.sink.clamp(0.0, self.deepest(wheel.surface, radius)); + // What the tyre picks up: water from a creek, which washes the mud off it, and + // mud from ground it has sunk into. + let sunk = (depth / 0.03).min(1.0); + if wheel.surface == Surface::Ford { + water = 1.0; + mud *= (-rolled / WASHES_MUD).exp(); + } else { + water = water.max(soil.wet * sunk); + mud = mud.max(soil.churn * soil.wet * sunk); + } + self.carried[index] = (water, mud); + let to = glam::Vec2::new(at.x, at.z); + // A car put somewhere else between two steps leaves no strip from where it was. + let from = self.trail[index] + .filter(|from| from.distance(to) < 1.5) + .unwrap_or(to); + self.trail[index] = Some(to); + let heading = body.rotation * (Quat::from_rotation_y(-wheel.steer) * Vec3::NEG_Z); + let along = glam::Vec2::new(heading.x, heading.z).normalize_or_zero(); + if along == glam::Vec2::ZERO { + continue; + } + // A tyre rolling prints its tread; one spinning or locked smears it. + let print = soil.print.max(0.5 * mud) * (1.0 - (wheel.slip_ratio.abs() - 0.06) / 0.3); + ground.press(&Press { + from, + to, + along, + half_width: 0.5 * TYRE_WIDTH * radius, + // The chord of the tyre below the ground's surface, and its own flat. + half_length: (2.0 * radius * (depth + 0.02)).sqrt().min(0.75 * radius), + depth, + berm: soil.berm, + phase: (phase, phase + turned), + print: print.clamp(0.0, 1.0), + wet: soil.wet.max(0.85 * water), + stays: soil.stays, + churn: soil.churn.max(0.7 * mud), + }); + } } /// Sets every wheel rolling at the speed the car is going: for starting a car that is @@ -310,8 +587,7 @@ impl Vehicle { wheel.speed = speed / self.spec.axle(index).radius; } if let Some(ratio) = self.ratio() { - let driven = self.driven_wheels(); - let wheels = 0.5 * (self.wheels[driven[0]].speed + self.wheels[driven[1]].speed); + let wheels = self.shaft_speed(); self.engine_speed = (wheels * ratio).max(self.spec.engine.idle * RPM_TO_RADIANS); } } @@ -320,15 +596,46 @@ impl Vehicle { /// reverse, and none in neutral. pub fn ratio(&self) -> Option { let gearbox = &self.spec.gearbox; + let range = self.range(); match self.gear { 0 => None, - gear if gear < 0 => Some(-gearbox.reverse * gearbox.final_drive), - gear => Some(gearbox.gears[gear as usize - 1] * gearbox.final_drive), + gear if gear < 0 => Some(-gearbox.reverse * gearbox.final_drive * range), + gear => Some(gearbox.gears[gear as usize - 1] * gearbox.final_drive * range), + } + } + + /// The transfer case's reduction: 1 in high range. + pub fn range(&self) -> f32 { + match (&self.spec.transfer, self.drive) { + (Some(transfer), DriveMode::FourLow) => transfer.low, + _ => 1.0, } } + /// How much of the drive each wheel is sent, which is also how much of the propshaft's + /// speed each is: a half each on the one driven axle, or shared between both. + fn shares(&self) -> [f32; 4] { + match &self.spec.transfer { + Some(transfer) if self.drive.four() => { + let front = transfer.front_share * 0.5; + [front, front, 0.5 - front, 0.5 - front] + } + Some(_) => [0.0, 0.0, 0.5, 0.5], + None if self.spec.front.driven => [0.5, 0.5, 0.0, 0.0], + None => [0.0, 0.0, 0.5, 0.5], + } + } + + /// How fast the driven wheels turn, as the gearbox's output sees them. + fn shaft_speed(&self) -> f32 { + let shares = self.shares(); + (0..4) + .map(|index| shares[index] * self.wheels[index].speed) + .sum() + } + fn driven_wheels(&self) -> [usize; 2] { - if self.spec.front.driven { + if self.spec.front.driven && self.spec.transfer.is_none() { [0, 1] } else { [2, 3] @@ -382,9 +689,8 @@ impl Vehicle { } if !up && target >= 1 { let gearbox = &self.spec.gearbox; - let ratio = gearbox.gears[target as usize - 1] * gearbox.final_drive; - let driven = self.driven_wheels(); - let wheels = 0.5 * (self.wheels[driven[0]].speed + self.wheels[driven[1]].speed); + let ratio = gearbox.gears[target as usize - 1] * gearbox.final_drive * self.range(); + let wheels = self.shaft_speed(); if wheels * ratio > (self.spec.engine.limit + 300.0) * RPM_TO_RADIANS { return; } @@ -415,6 +721,20 @@ impl Vehicle { self.wheels[0].steer = left; self.wheels[1].steer = right; + // Hill descent control: in low range, with no foot on either pedal, the brakes hold + // the car to a walking pace whichever way it is rolling. + let mut held = *controls; + let descending = self.spec.hill_descent + && self.drive == DriveMode::FourLow + && controls.throttle < 0.05 + && speed.abs() > DESCENT_SPEED; + if descending { + held.brake = held + .brake + .max(((speed.abs() - DESCENT_SPEED) * 0.55).min(DESCENT_BRAKE)); + } + let controls = &held; + let before = body.velocity; let dt = seconds / SUBSTEPS as f32; let mut aids = (false, false, false); @@ -422,6 +742,7 @@ impl Vehicle { let (abs, traction, stability) = self.substep(body, controls, ground, dt); aids = (aids.0 | abs, aids.1 | traction, aids.2 | stability); } + self.mark(body, ground, seconds); let acceleration = (body.velocity - before) / seconds; // What the driver feels: the acceleration, less gravity's. @@ -440,6 +761,11 @@ impl Vehicle { traction_active: aids.1, stability_active: aids.2, limiter: self.limiting, + drive: self.drive, + front_locked: self.lockers.0 && self.drive.four(), + rear_locked: self.lockers.1, + aired_down: self.aired_down, + descent_active: descending, }; } @@ -452,6 +778,12 @@ impl Vehicle { ground: &dyn Ground, dt: f32, ) -> (bool, bool, bool) { + let shares = self.shares(); + let range = self.range(); + let four = self.drive.four() && self.spec.transfer.is_some(); + let lockers = self.lockers; + let wetness = self.wetness; + let aired = self.aired_down; let spec = &self.spec; let hubs = spec.hubs(); let (forward, up) = (body.forward(), body.up()); @@ -466,21 +798,62 @@ impl Vehicle { let top = body.position + body.rotation * hubs[index] + up * top_offset; let reach = top_offset + axle.travel_down + axle.radius; travel[index] = -axle.travel_down; - let Some(contact) = ground.cast(top, -up, reach) else { - continue; + let rest = if index < 2 { + self.static_loads.0 + } else { + self.static_loads.1 }; - // A wall, or the underside of something: not ground to stand on. - if contact.normal.dot(up) < 0.3 || !contact.normal.is_finite() { + let wheel = &mut self.wheels[index]; + self.touching[index] = None; + // A wall, or the underside of something, is not ground to stand on. + let contact = ground + .cast(top, -up, reach + wheel.sink.max(0.0)) + .filter(|contact| contact.normal.dot(up) >= 0.3 && contact.normal.is_finite()); + let Some(contact) = contact else { + // In the air, the tyre is out of whatever it had sunk into. + wheel.sink *= (-dt / RISE_SECONDS).exp(); continue; - } - let grip = contact.surface.grip(); + }; let point = top - up * contact.distance; + // What has been pressed into the ground here already: the floor of a rut, which + // the tyre stands on, or the berm beside one, which it rides over. + let floor = ground.rut(point); + let floor = if floor.is_finite() { floor } else { 0.0 }; + let grip = contact.surface.grip(); + // Soft ground gives until it carries the tyre: deeper the harder the tyre is + // pressed, and deeper again under a wheel that spins and digs. It takes a moment + // to sink, and longer to climb out. + let soft = grip.sink_at(wetness) * if aired { AIRED_SINK } else { 1.0 }; + let wanted = if soft > 0.0 || grip.dig > 0.0 { + let pressed = (wheel.load / rest).clamp(0.0, 2.5); + let spinning = (wheel.slip_ratio.abs() - 0.15).clamp(0.0, 1.0); + let sunk = soft * pressed.sqrt() + grip.dig * spinning * pressed.min(1.0); + // A wheel that goes on spinning goes on digging: always a little below the + // floor of the hole it has made, until it is as deep as this ground lets a + // wheel dig itself. + let deepest = (soft * DIG_SOFT + grip.dig * DIG_SPUN).min(DIG_RADIUS * axle.radius); + let dug = floor + grip.dig * spinning * pressed.min(1.0) * DIG_ON; + sunk.max(dug.min(deepest)) + } else { + 0.0 + }; + // The tyre stands on the floor of whatever rut is here, and sinks below it only + // as far as it would have sunk in ground nobody had pressed. + let below = (wheel.sink - floor).max(0.0); + let wanted_below = (wanted - floor).max(0.0); + let seconds = if wanted_below > below { + SINK_SECONDS + } else { + RISE_SECONDS + }; + wheel.sink = floor + below + (wanted_below - below) * (1.0 - (-dt / seconds).exp()); + self.touching[index] = Some(point); let rough = if grip.bump_height > 0.0 { grip.bump_height * bump(point.x, point.z, grip.bump_length) } else { 0.0 }; - let risen = top_offset - (contact.distance - rough - axle.radius); + let risen = top_offset - (contact.distance + wheel.sink - rough - axle.radius); if risen <= -axle.travel_down { continue; } @@ -557,6 +930,16 @@ impl Vehicle { let catch_up = 1.0 - (-dt * (rolling.abs() + 3.0) / spec.tyre.relaxation).exp(); wheel.slide += (slide - wheel.slide) * catch_up; let surface = contact.surface.grip(); + // What holds a tyre back: the ground's own drag, and the rut it is ploughing. + // Let down, a tyre grips soil better, and squirms and drags on anything hard. + let loose = surface.slip > 1.5; + let (footprint, squirm) = match (aired, loose) { + (false, _) => (1.0, 1.0), + (true, true) => (AIRED_GRIP, 1.0), + (true, false) => (AIRED_ROAD_GRIP, AIRED_ROLLING), + }; + let drag = + surface.rolling_at(rolling) * squirm + RUT_DRAG * wheel.sink.max(0.0) / axle.radius; patches[index] = Some(Patch { point: contact.point, normal: contact.normal, @@ -564,8 +947,13 @@ impl Vehicle { across, rolling, against, - grip: surface.grip * axle.grip, - resistance: -surface.rolling_at(rolling) * loads[index] * (rolling / 0.5).tanh(), + grip: surface.grip_at(wetness) + * axle.grip + * footprint + * spec.tyre.tread_on(surface.sink), + slip: surface.slip, + hold: surface.hold, + resistance: -drag * loads[index] * (rolling / 0.5).tanh(), }); } @@ -573,9 +961,23 @@ impl Vehicle { // it changes with that speed. let tyre = spec.tyre; let curves = self.curves; + // On loose ground a tyre must slip further to grip its best: its slips are measured + // against that. let grip_force = |patch: &Patch, load: f32, slide: f32, radius: f32, speed: f32| { - let ratio = (speed * radius - patch.rolling) / patch.against; - tyre.force(&curves, load, ratio, slide, patch.grip) + let mut ratio = (speed * radius - patch.rolling) / patch.against; + // Soil goes on pushing back past the slip it grips best at: so much of the slip + // beyond that counts for nothing. + let best = tyre.peak_ratio * patch.slip; + if ratio.abs() > best { + ratio = ratio.signum() * (best + (ratio.abs() - best) * (1.0 - patch.hold)); + } + tyre.force( + &curves, + load, + ratio / patch.slip, + slide / patch.slip, + patch.grip, + ) }; let mut along_now = [0.0_f32; 4]; let mut stiffness = [0.0_f32; 4]; @@ -607,7 +1009,9 @@ impl Vehicle { && controls.brake > 0.0 && wheel.on_ground && patch.is_some_and(|p| { - p.rolling.abs() > 2.5 && wheel.slip_ratio * p.rolling.signum() < -ABS_SLIP + // On loose ground a tyre grips best slipping further: it is let. + p.rolling.abs() > 2.5 + && wheel.slip_ratio * p.rolling.signum() < -ABS_SLIP * p.slip }); wheel.brake_share = if slipping { abs_active = true; @@ -619,18 +1023,52 @@ impl Vehicle { // Traction control eases the throttle by how far past the tyre's peak the faster // driven wheel is spinning, quickly, and gives it back more slowly. let driven = self.driven_wheels(); - let wheelspin = driven - .iter() - .filter(|&&index| self.wheels[index].on_ground) - .map(|&index| self.wheels[index].slip_ratio * self.gear.signum() as f32) + // How far each driven wheel is spinning past the speed the car is going, measured + // against what the ground under it grips best at. A wheel in the air counts: it is + // the one that spins. + let onward = body.velocity.dot(forward); + let mut spin = [0.0_f32; 4]; + for index in 0..4 { + if shares[index] > 0.0 { + let slip = patches[index].map_or(1.0, |patch| patch.slip); + let passing = self.wheels[index].speed * spec.axle(index).radius - onward; + spin[index] = + passing * self.gear.signum() as f32 / onward.abs().max(LOW_SPEED) / slip; + } + } + // A four-wheel drive's traction control works on each wheel: one that runs away from + // the wheel across its axle is braked, which sends the drive across an open + // differential to the wheel that grips, and the engine is eased only for the wheels + // that are not being braked so. A car with one driven axle eases it for the faster. + let per_wheel = spec.transfer.is_some(); + let runaway = |index: usize| { + per_wheel + && (self.wheels[index].speed - self.wheels[index ^ 1].speed) + * spec.axle(index).radius + * self.gear.signum() as f32 + > 0.5 + }; + let wheelspin = (0..4) + .filter(|&index| shares[index] > 0.0 && self.wheels[index].on_ground) + .filter(|&index| !runaway(index)) + .map(|index| { + if per_wheel { + spin[index] + } else { + self.wheels[index].slip_ratio * self.gear.signum() as f32 + / patches[index].map_or(1.0, |patch| patch.slip) + } + }) .fold(0.0, f32::max); - let spinning = - spec.traction_control && controls.throttle > 0.0 && wheelspin > TRACTION_SLIP; + // It lets a tyre slip as far as that tyre grips best at, and a little more: a slick + // peaks sooner than a tyre with tread. + let allowed = TRACTION_SLIP.max(spec.tyre.peak_ratio * 1.15); + let spinning = spec.traction_control && controls.throttle > 0.0 && wheelspin > allowed; // At once, no more throttle than the slip allows; and for as long as the wheel goes on // spinning, less and less, until it is back at the edge of its grip. Without the // second, it would settle part-way, spinning a little for good. self.traction_share = if spinning { - let excess = (wheelspin - TRACTION_SLIP) / TRACTION_BAND; + let excess = (wheelspin - allowed) / TRACTION_BAND; (self.traction_share - dt * 14.0 * excess) .min(1.0 - excess) .max(0.0) @@ -673,8 +1111,15 @@ impl Vehicle { } else { rpm > engine.limit }; - let ratio = self.ratio(); - let wheels_speed = 0.5 * (self.wheels[driven[0]].speed + self.wheels[driven[1]].speed); + let gearbox = &spec.gearbox; + let ratio = match self.gear { + 0 => None, + gear if gear < 0 => Some(-gearbox.reverse * gearbox.final_drive * range), + gear => Some(gearbox.gears[gear as usize - 1] * gearbox.final_drive * range), + }; + let wheels_speed: f32 = (0..4) + .map(|index| shares[index] * self.wheels[index].speed) + .sum(); // How fast the gearbox's input shaft turns: what the engine would turn at, in gear. let shaft = ratio.map_or(0.0, |ratio| wheels_speed * ratio); let mut throttle = @@ -711,7 +1156,14 @@ impl Vehicle { // start slips it just above idle; a hard one holds the engine up in its torque // while the car catches up. Traction control eases it with the throttle, as the // engine's own momentum would spin the wheels whatever the throttle did. - let bite = engine.idle * 1.05 + controls.throttle.clamp(0.0, 1.0) * LAUNCH_REVS; + // A gearbox that cruises takes up the drive low in the revs, as a road car's + // does, where a racing car's is held up in its power to leave the line. + let launch = if spec.gearbox.cruise < 1.0 { + LAUNCH_REVS * 0.4 + } else { + LAUNCH_REVS + }; + let bite = engine.idle * 1.05 + controls.throttle.clamp(0.0, 1.0) * launch; ((rpm - bite) / 1500.0).clamp(0.0, 1.0) * self.traction_share }; let diff = &spec.differential; @@ -732,6 +1184,17 @@ impl Vehicle { let axle = spec.axle(index); let share = self.wheels[index].brake_share; *torque = brake * axle.brake * share; + // A four-wheel drive's wheel that runs away from the one across its axle is + // braked, by how far it has run away: metres a second at the tread. Wheels that + // a locked differential holds together never do. + if per_wheel && spec.traction_control && controls.throttle > 0.0 && shares[index] > 0.0 + { + let ahead = (self.wheels[index].speed - self.wheels[index ^ 1].speed) + * axle.radius + * self.gear.signum() as f32; + let over = ((ahead - 0.5) / 1.5).clamp(0.0, 1.0); + *torque += over * axle.brake * BRAKE_TRACTION; + } if index >= 2 { *torque *= 1.0 - 0.92 * releasing; *torque += handbrake * 3000.0; @@ -751,29 +1214,74 @@ impl Vehicle { stiffness: stiffness[index], brake: brakes[index], }; - let solved = drivetrain::solve( - &DrivenAxle { - engine_speed: self.engine_speed, - engine_inertia: engine.inertia, - engine_torque, - ratio: ratio.unwrap_or(0.0), - efficiency: spec.gearbox.efficiency, - clutch: Coupling::new(spec.gearbox.clutch * engaged), - differential: Coupling::new(lock), - left: side(driven[0]), - right: side(driven[1]), - }, - dt, - ); debug_assert!(axle.driven); let mut speeds = [0.0_f32; 4]; - speeds[driven[0]] = solved.left; - speeds[driven[1]] = solved.right; - for index in (0..4).filter(|index| !driven.contains(index)) { - speeds[index] = drivetrain::solve_free(&side(index), dt); + if let Some(transfer) = &spec.transfer { + // A four-wheel drive: both axles, and what joins them. In two-wheel drive the + // front is sent nothing and the lock between the propshafts is open. A locked + // differential carries whatever its lock can; the front's own differential shares + // what its axle is sent as the rear's does. + let front_share = if four { transfer.front_share } else { 0.0 }; + let front_diff = &spec.front_differential; + let front_lock = if lockers.0 && four { + transfer.locker + } else { + front_diff.preload + + carried.abs() + * front_share + * if self.clutch_torque >= 0.0 { + front_diff.power + } else { + front_diff.coast + } + }; + let rear_lock = if lockers.1 { + transfer.locker + } else { + diff.preload + (lock - diff.preload) * (1.0 - front_share) + }; + let solved = drivetrain::solve_all( + &Driveline { + engine_speed: self.engine_speed, + engine_inertia: engine.inertia, + engine_torque, + ratio: ratio.unwrap_or(0.0), + efficiency: spec.gearbox.efficiency, + clutch: Coupling::new(spec.gearbox.clutch * engaged), + front_share, + centre: Coupling::new(if four { transfer.lock } else { 0.0 }), + front: Coupling::new(front_lock), + rear: Coupling::new(rear_lock), + wheels: [side(0), side(1), side(2), side(3)], + }, + dt, + ); + speeds = solved.wheels; + self.engine_speed = solved.engine.max(0.0); + self.clutch_torque = solved.clutch_torque; + } else { + let solved = drivetrain::solve( + &DrivenAxle { + engine_speed: self.engine_speed, + engine_inertia: engine.inertia, + engine_torque, + ratio: ratio.unwrap_or(0.0), + efficiency: spec.gearbox.efficiency, + clutch: Coupling::new(spec.gearbox.clutch * engaged), + differential: Coupling::new(lock), + left: side(driven[0]), + right: side(driven[1]), + }, + dt, + ); + speeds[driven[0]] = solved.left; + speeds[driven[1]] = solved.right; + for index in (0..4).filter(|index| !driven.contains(index)) { + speeds[index] = drivetrain::solve_free(&side(index), dt); + } + self.engine_speed = solved.engine.max(0.0); + self.clutch_torque = solved.clutch_torque; } - self.engine_speed = solved.engine.max(0.0); - self.clutch_torque = solved.clutch_torque; // 3. The forces on the body. let mut force = Vec3::new(0.0, -spec.mass * self.gravity, 0.0); @@ -885,6 +1393,10 @@ struct Patch { against: f32, /// The surface's grip, with the axle's. grip: f32, + /// How many times further the tyre must slip here to grip its best. + slip: f32, + /// How much of the fall in grip past its best a spinning tyre is spared here. + hold: f32, /// Rolling resistance, along the way it points. resistance: f32, } diff --git a/crates/solstice-vehicle/tests/ruts.rs b/crates/solstice-vehicle/tests/ruts.rs new file mode 100644 index 0000000..55ed45f --- /dev/null +++ b/crates/solstice-vehicle/tests/ruts.rs @@ -0,0 +1,318 @@ +//! Ground that keeps the ruts a truck presses into it: that a tyre stands in the rut that +//! is kept, that the ruts are left behind it and stay, that spinning digs, that the wheels +//! behind ride in the ruts of those ahead, and that a deep rut holds a truck back. + +use glam::{Vec2, Vec3}; +use solstice_vehicle::{ + Asked, Body, Contact, DriveMode, Driver, Flat, Ground, Press, Ruts, Surface, Vehicle, + VehicleSpec, +}; +use std::cell::RefCell; + +const G: f32 = 9.81; +const DT: f32 = 1.0 / 60.0; + +/// Level ground of one surface that keeps what is pressed into it. +struct Soft { + surface: Surface, + ruts: RefCell, +} + +impl Soft { + fn new(surface: Surface) -> Self { + Self { + surface, + ruts: RefCell::default(), + } + } + + fn depth(&self, x: f32, z: f32) -> f32 { + self.ruts.borrow().depth(x, z) + } +} + +impl Ground for Soft { + fn cast(&self, from: Vec3, direction: Vec3, reach: f32) -> Option { + Flat { + height: 0.0, + surface: self.surface, + } + .cast(from, direction, reach) + } + + fn rut(&self, at: Vec3) -> f32 { + self.ruts.borrow().depth(at.x, at.z) + } + + fn press(&self, press: &Press) { + self.ruts.borrow_mut().press(press); + } +} + +fn truck(mode: DriveMode) -> (Vehicle, Body) { + let spec = VehicleSpec::parse(include_str!("truck.vehicle")).unwrap(); + let mut vehicle = Vehicle::new(spec, G); + vehicle.set_drive_mode(mode); + (vehicle, Body::at_rest(Vec3::ZERO, 0.0)) +} + +/// Where each tyre stands on the ground, in the world: x and z. +fn feet(vehicle: &Vehicle, body: &Body) -> [Vec2; 4] { + let hubs = vehicle.spec().hubs(); + std::array::from_fn(|index| { + let at = body.position + body.rotation * hubs[index]; + Vec2::new(at.x, at.z) + }) +} + +/// Drives for `seconds` at this much throttle, and gives back how far the truck went. +fn drive( + vehicle: &mut Vehicle, + body: &mut Body, + ground: &dyn Ground, + throttle: f32, + seconds: f32, +) -> f32 { + let mut driver = Driver::new(true); + let asked = Asked { + throttle, + ..Asked::default() + }; + let start = body.position; + let mut time = 0.0; + while time < seconds { + let controls = driver.drive(&asked, vehicle, body, G, DT); + vehicle.step(body, &controls, ground, DT); + time += DT; + assert!(body.position.is_finite() && body.velocity.is_finite()); + } + (start - body.position).z +} + +#[test] +fn a_standing_truck_sits_in_the_ruts_it_pressed() { + for (surface, low, high) in [ + (Surface::Dirt, 0.002, 0.01), + (Surface::Mud, 0.05, 0.1), + (Surface::Bog, 0.1, 0.2), + ] { + let ground = Soft::new(surface); + let (mut vehicle, mut body) = truck(DriveMode::FourHigh); + for _ in 0..300 { + vehicle.step(&mut body, &Default::default(), &ground, DT); + } + for (wheel, foot) in vehicle.wheels.iter().zip(feet(&vehicle, &body)) { + // As deep as on ground that keeps nothing, and the map says the same depth + // under the tyre as the tyre has sunk. + assert!( + (low..=high).contains(&wheel.sink), + "{surface:?}: sunk {}", + wheel.sink + ); + let kept = ground.depth(foot.x, foot.y); + assert!( + (kept - wheel.sink).abs() < 0.004, + "{surface:?}: the tyre is {} down in a rut {kept} deep", + wheel.sink + ); + } + // And the body sits lower by it. + assert!((body.position.y + vehicle.wheels[0].sink).abs() < 0.03); + } + // Rock keeps nothing. + let ground = Soft::new(Surface::Rock); + let (mut vehicle, mut body) = truck(DriveMode::FourHigh); + for _ in 0..120 { + vehicle.step(&mut body, &Default::default(), &ground, DT); + } + assert!(ground.ruts.borrow().is_empty()); +} + +#[test] +fn a_truck_leaves_its_ruts_behind_it_with_berms_beside_them() { + let ground = Soft::new(Surface::Mud); + let (mut vehicle, mut body) = truck(DriveMode::FourHigh); + let went = drive(&mut vehicle, &mut body, &ground, 0.5, 5.0); + assert!(went > 12.0, "it went {went} m"); + let half_track = vehicle.spec().front.track * 0.5; + // Behind it, under where each side's wheels ran, a rut all the way back to the start; + // between them and outside them, ground nobody pressed. + for along in [2.0, 5.0, 9.0] { + for side in [-1.0, 1.0] { + let rut = ground.depth(side * half_track, -along); + assert!((0.04..0.2).contains(&rut), "{along} m on: {rut}"); + // Beside the rut, a berm. + let berm = (0..30) + .map(|k| -ground.depth(side * (half_track + 0.1 + k as f32 * 0.01), -along)) + .fold(f32::MIN, f32::max); + assert!(berm > 0.008, "{along} m on: a berm of {berm}"); + } + assert_eq!(ground.depth(0.0, -along), 0.0); + assert_eq!(ground.depth(2.0 * half_track, -along), 0.0); + } + // They are still there when it has gone and time has passed. + let before = ground.depth(half_track, -5.0); + for _ in 0..600 { + ground.ruts.borrow_mut().advance(1.0); + } + assert_eq!(ground.depth(half_track, -5.0), before); +} + +#[test] +fn the_wheels_behind_ride_in_the_ruts_of_the_wheels_ahead() { + let ground = Soft::new(Surface::Mud); + let (mut vehicle, mut body) = truck(DriveMode::FourHigh); + drive(&mut vehicle, &mut body, &ground, 0.35, 6.0); + // Rolling steadily, a rear tyre is no deeper than the rut it is in: it stands on the + // floor the front one made, or has pressed it a little deeper and stands on that. + for (wheel, foot) in vehicle.wheels.iter().zip(feet(&vehicle, &body)).skip(2) { + let kept = ground.depth(foot.x, foot.y); + assert!(wheel.sink > 0.03, "{}", wheel.sink); + assert!( + (wheel.sink - kept).abs() < 0.012, + "a rear tyre {} down in a rut {kept} deep", + wheel.sink + ); + } + // A second truck down the same ruts makes them no deeper than a first does a fresh + // line beside them. + let first = ground.depth(vehicle.spec().front.track * 0.5, -6.0); + let (mut second, mut body) = truck(DriveMode::FourHigh); + drive(&mut second, &mut body, &ground, 0.35, 6.0); + let both = ground.depth(vehicle.spec().front.track * 0.5, -6.0); + assert!(both >= first && both < first + 0.03, "{first} then {both}"); +} + +#[test] +fn a_spinning_wheel_digs_itself_in() { + // Two-wheel drive, flat out in a bog, traction control or not: the rear wheels spin + // and dig, and the fronts, which only roll, do not. + let ground = Soft::new(Surface::Bog); + let (mut vehicle, mut body) = truck(DriveMode::TwoHigh); + drive(&mut vehicle, &mut body, &ground, 1.0, 8.0); + let (front, rear) = (vehicle.wheels[0].sink, vehicle.wheels[2].sink); + assert!(rear > front + 0.03, "front {front}, rear {rear}"); + // No deeper than a wheel can dig: it is on its axle by then. + let radius = vehicle.spec().rear.radius; + assert!(rear < 0.75 * radius, "{rear}"); + // Deeper than the same truck sinks on ground that keeps nothing. + let (mut other, mut body) = truck(DriveMode::TwoHigh); + drive( + &mut other, + &mut body, + &Flat { + height: 0.0, + surface: Surface::Bog, + }, + 1.0, + 8.0, + ); + assert!(rear > other.wheels[2].sink + 0.02); +} + +#[test] +fn four_wheel_drive_still_gets_through_a_bog_that_keeps_its_ruts() { + let across = |mode: DriveMode| { + let ground = Soft::new(Surface::Bog); + let (mut vehicle, mut body) = truck(mode); + drive(&mut vehicle, &mut body, &ground, 0.7, 12.0) + }; + let (two, four, low) = ( + across(DriveMode::TwoHigh), + across(DriveMode::FourHigh), + across(DriveMode::FourLow), + ); + assert!(two < 6.0, "two-wheel drive went {two} m through the bog"); + assert!(four > 15.0, "four-wheel drive went only {four} m"); + assert!(low > 10.0, "low range went only {low} m"); +} + +#[test] +fn a_deep_rut_holds_a_truck_back() { + // Rolling at 8 m/s out of gear along a clay track: once on ground nobody has driven, + // once along ruts a hand deep. + let coast = |rutted: bool| { + let ground = Soft::new(Surface::Dirt); + let (mut vehicle, mut body) = truck(DriveMode::FourHigh); + if rutted { + let half_track = vehicle.spec().front.track * 0.5; + for (side, metre) in [-1.0, 1.0] + .into_iter() + .flat_map(|side| (-5..80).map(move |metre| (side, metre as f32))) + { + ground.ruts.borrow_mut().press(&Press { + from: Vec2::new(side * half_track, -metre), + to: Vec2::new(side * half_track, -metre - 1.0), + along: Vec2::NEG_Y, + half_width: 0.2, + half_length: 0.15, + depth: 0.12, + berm: 0.4, + phase: (0.0, 0.0), + print: 0.0, + wet: 0.5, + stays: 0.3, + churn: 1.0, + }); + } + } + for _ in 0..120 { + vehicle.step(&mut body, &Default::default(), &ground, DT); + } + body.velocity = body.forward() * 8.0; + vehicle.roll_with(&body); + for _ in 0..180 { + vehicle.step(&mut body, &Default::default(), &ground, DT); + } + (body.velocity.length(), vehicle.wheels[0].sink) + }; + let ((open, sink), (rutted, deep)) = (coast(false), coast(true)); + assert!( + sink < 0.02 && (deep - 0.12).abs() < 0.02, + "{sink} and {deep}" + ); + assert!( + rutted < open - 0.5, + "{open} m/s on open ground, {rutted} in ruts" + ); +} + +#[test] +fn a_tyre_out_of_a_creek_leaves_wet_tracks_on_dry_rock() { + // Half the ground is a ford, the rest bare rock, which takes no rut. + struct Bank(RefCell); + impl Ground for Bank { + fn cast(&self, from: Vec3, direction: Vec3, reach: f32) -> Option { + let mut contact = Flat { + height: 0.0, + surface: Surface::Ford, + } + .cast(from, direction, reach)?; + if (from + direction * contact.distance).z < -6.0 { + contact.surface = Surface::Rock; + } + Some(contact) + } + fn rut(&self, at: Vec3) -> f32 { + self.0.borrow().depth(at.x, at.z) + } + fn press(&self, press: &Press) { + self.0.borrow_mut().press(press); + } + } + let ground = Bank(RefCell::default()); + let (mut vehicle, mut body) = truck(DriveMode::FourHigh); + let went = drive(&mut vehicle, &mut body, &ground, 0.5, 6.0); + assert!(went > 20.0, "{went}"); + let half_track = vehicle.spec().front.track * 0.5; + let ruts = ground.0.borrow(); + // Just out of the water the rock is wet where the tyres ran, and not pressed; further + // on, less wet; between the tyres, dry. + let near = ruts.wet(half_track, -8.0); + let far = ruts.wet(half_track, -(went - 1.0).min(40.0)); + assert!(near > 0.5, "{near}"); + assert!(far < near, "{near} then {far}"); + assert_eq!(ruts.height(half_track, -8.0), 0.0); + assert_eq!(ruts.wet(0.0, -8.0), 0.0); + assert!(vehicle.carried()[0].0 < 1.0); +} diff --git a/crates/solstice-vehicle/tests/truck.rs b/crates/solstice-vehicle/tests/truck.rs new file mode 100644 index 0000000..3ee8b8d --- /dev/null +++ b/crates/solstice-vehicle/tests/truck.rs @@ -0,0 +1,361 @@ +//! A four-wheel-drive desert truck, driven off the road: that its figures are those of the truck +//! it says it is, that its long suspension carries it, and that mud, bog and a wet clay hill do +//! to it what they do to a real one, each as its transfer case and lockers are set. + +use glam::Vec3; +use solstice_vehicle::{ + Asked, Body, Contact, DriveMode, Driver, Flat, Ground, Surface, Vehicle, VehicleSpec, +}; + +const G: f32 = 9.81; +const DT: f32 = 1.0 / 60.0; + +fn spec() -> VehicleSpec { + VehicleSpec::parse(include_str!("truck.vehicle")).unwrap() +} + +fn flat(surface: Surface) -> Flat { + Flat { + height: 0.0, + surface, + } +} + +/// A slope of one surface, rising along -Z, the way a car at rest faces: `grade` is its rise +/// over its run. +struct Hill { + grade: f32, + surface: Surface, +} + +impl Ground for Hill { + fn cast(&self, from: Vec3, direction: Vec3, reach: f32) -> Option { + // The plane y = -grade * z. + let normal = Vec3::new(0.0, 1.0, self.grade).normalize(); + let facing = direction.dot(normal); + if facing >= -1.0e-6 { + return None; + } + let distance = -from.dot(normal) / facing; + (0.0..=reach).contains(&distance).then_some(Contact { + distance, + normal, + surface: self.surface, + }) + } +} + +/// Ground whose left and right halves are different surfaces. +struct Split { + left: Surface, + right: Surface, +} + +impl Ground for Split { + fn cast(&self, from: Vec3, direction: Vec3, reach: f32) -> Option { + let mut contact = flat(self.left).cast(from, direction, reach)?; + if (from + direction * contact.distance).x > 0.0 { + contact.surface = self.right; + } + Some(contact) + } +} + +/// Drives flat out for `seconds` and gives back how far the car went, in metres. +fn drive( + vehicle: &mut Vehicle, + body: &mut Body, + ground: &dyn Ground, + throttle: f32, + seconds: f32, +) -> f32 { + let mut driver = Driver::new(true); + let asked = Asked { + throttle, + ..Asked::default() + }; + let start = body.position; + let mut time = 0.0; + while time < seconds { + let controls = driver.drive(&asked, vehicle, body, G, DT); + vehicle.step(body, &controls, ground, DT); + time += DT; + assert!(body.position.is_finite() && body.velocity.is_finite()); + } + (start - body.position).z +} + +fn truck(mode: DriveMode) -> (Vehicle, Body) { + let mut vehicle = Vehicle::new(spec(), G); + vehicle.set_drive_mode(mode); + (vehicle, Body::at_rest(Vec3::ZERO, 0.0)) +} + +/// A truck standing on a hill of this grade, nose up it. +fn truck_on(grade: f32, mode: DriveMode) -> (Vehicle, Body) { + let (vehicle, mut body) = truck(mode); + body.rotation = glam::Quat::from_rotation_x(grade.atan()); + (vehicle, body) +} + +#[test] +fn the_file_is_the_truck_it_says() { + let spec = spec(); + assert!((spec.wheelbase() - 3.686).abs() < 1.0e-3); + let (power, rpm) = spec.engine.peak_power(); + assert!((525.0e3..545.0e3).contains(&power), "{} kW", power / 1000.0); + assert!((6300.0..6900.0).contains(&rpm)); + assert_eq!(spec.gearbox.gears.len(), 10); + let front = spec.front_weight(); + assert!((0.54..0.58).contains(&front), "{front} on the front"); + let transfer = spec.transfer.expect("a transfer case"); + assert!((transfer.low - 2.64).abs() < 1.0e-6); + // A foot of wheel travel at each end. + assert!(spec.front.travel_up + spec.front.travel_down > 0.3); + assert!(spec.rear.travel_up + spec.rear.travel_down > 0.34); + // A soft ride: each end's own bounce near 1.3 Hz. + for (axle, share) in [(&spec.front, front), (&spec.rear, 1.0 - front)] { + let corner = spec.mass * share * 0.5; + let hertz = (axle.spring / corner).sqrt() / std::f32::consts::TAU; + assert!((1.1..1.6).contains(&hertz), "{hertz} Hz"); + } +} + +#[test] +fn it_stands_still_on_its_springs_and_settles_after_a_drop() { + let (mut vehicle, mut body) = truck(DriveMode::FourHigh); + body.position.y = 0.35; + let road = flat(Surface::Dirt); + let mut deepest = 0.0_f32; + for _ in 0..360 { + vehicle.step(&mut body, &Default::default(), &road, DT); + deepest = deepest.max(vehicle.wheels[0].travel); + } + // It used a good part of its travel, and did not hit the stops hard enough to bounce off. + assert!(deepest > 0.08 && deepest < 0.2, "{deepest}"); + assert!(body.position.y.abs() < 0.02, "at {}", body.position.y); + assert!(body.velocity.length() < 0.05); + let loads: f32 = vehicle.wheels.iter().map(|wheel| wheel.load).sum(); + assert!((loads - 2800.0 * G).abs() < 300.0, "{loads}"); +} + +#[test] +fn on_the_road_it_is_as_quick_as_the_truck_is() { + // Ford's truck reaches 100 km/h in about four seconds, in four-wheel drive. + let (mut vehicle, mut body) = truck(DriveMode::FourHigh); + let road = flat(Surface::Asphalt); + let mut driver = Driver::new(true); + let asked = Asked { + throttle: 1.0, + ..Asked::default() + }; + let (mut seconds, mut to_100) = (0.0, None); + while seconds < 12.0 { + let controls = driver.drive(&asked, &vehicle, &body, G, DT); + vehicle.step(&mut body, &controls, &road, DT); + seconds += DT; + if to_100.is_none() && body.velocity.length() * 3.6 >= 100.0 { + to_100 = Some(seconds); + } + assert!(vehicle.rpm() < 7600.0, "over-revved"); + } + let to_100 = to_100.expect("it reaches 100 km/h"); + assert!((3.4..5.6).contains(&to_100), "{to_100} s to 100 km/h"); +} + +#[test] +fn a_light_foot_changes_up_early_and_does_not_hunt() { + let (mut vehicle, mut body) = truck(DriveMode::FourHigh); + let road = flat(Surface::Dirt); + let mut driver = Driver::new(true); + let asked = Asked { + throttle: 0.25, + ..Asked::default() + }; + let (mut changes, mut last, mut highest) = (0, 0, 0.0_f32); + for step in 0..1500 { + let controls = driver.drive(&asked, &vehicle, &body, G, DT); + vehicle.step(&mut body, &controls, &road, DT); + if vehicle.gear() != last { + assert!(vehicle.gear() > last, "it changed down at step {step}"); + changes += 1; + last = vehicle.gear(); + } + if step > 120 { + highest = highest.max(vehicle.rpm()); + } + } + assert!(changes >= 3, "only {changes} changes"); + assert!(highest < 4600.0, "it revved to {highest}"); +} + +#[test] +fn low_range_crawls() { + let top = |mode: DriveMode| { + let (mut vehicle, mut body) = truck(mode); + // Held in first. + vehicle.set_gear(1); + let road = flat(Surface::Dirt); + let controls = solstice_vehicle::Controls { + throttle: 1.0, + ..Default::default() + }; + for _ in 0..600 { + vehicle.step(&mut body, &controls, &road, DT); + } + body.velocity.length() + }; + let (high, low) = (top(DriveMode::FourHigh), top(DriveMode::FourLow)); + assert!((high / low - 2.64).abs() < 0.2, "{high} and {low}"); + assert!(low < 7.0, "first low tops out at {} km/h", low * 3.6); +} + +#[test] +fn a_tyre_sinks_into_mud_and_stands_on_rock() { + for (surface, low, high) in [ + (Surface::Rock, 0.0, 0.001), + (Surface::Dirt, 0.002, 0.01), + (Surface::Mud, 0.05, 0.1), + (Surface::Bog, 0.1, 0.2), + ] { + let (mut vehicle, mut body) = truck(DriveMode::FourHigh); + let ground = flat(surface); + for _ in 0..300 { + vehicle.step(&mut body, &Default::default(), &ground, DT); + } + for wheel in &vehicle.wheels { + assert!( + (low..=high).contains(&wheel.sink), + "{surface:?}: sunk {}", + wheel.sink + ); + } + // The body sits lower by what its tyres sank. + assert!( + (body.position.y + vehicle.wheels[0].sink).abs() < 0.03, + "{surface:?}: body at {}", + body.position.y + ); + } +} + +#[test] +fn a_bog_stops_two_wheel_drive_and_four_wheel_drive_gets_through() { + let across = |mode: DriveMode| { + let (mut vehicle, mut body) = truck(mode); + drive(&mut vehicle, &mut body, &flat(Surface::Bog), 0.7, 12.0) + }; + let (two, four) = (across(DriveMode::TwoHigh), across(DriveMode::FourHigh)); + assert!(two < 6.0, "two-wheel drive went {two} m through the bog"); + assert!(four > 15.0, "four-wheel drive went only {four} m"); + // Low range pulls through as well, slowly. + let low = across(DriveMode::FourLow); + assert!(low > 10.0, "low range went only {low} m"); +} + +#[test] +fn mud_holds_a_truck_back_and_a_dirt_track_does_not() { + let after = |surface: Surface| { + let (mut vehicle, mut body) = truck(DriveMode::FourHigh); + drive(&mut vehicle, &mut body, &flat(surface), 1.0, 6.0); + body.velocity.length() * 3.6 + }; + let (dirt, mud, bog) = ( + after(Surface::Dirt), + after(Surface::Mud), + after(Surface::Bog), + ); + assert!(dirt > 95.0, "{dirt} km/h on dirt"); + assert!(mud < dirt * 0.75 && mud > 25.0, "{mud} km/h in mud"); + assert!(bog < mud * 0.8, "{bog} km/h in the bog"); +} + +#[test] +fn rain_turns_a_clay_hill_from_a_climb_into_a_slide() { + // A 30% clay track: a dry climb in four-wheel drive. Soaked, two-wheel drive spins. + let climb = |mode: DriveMode, wetness: f32| { + let (mut vehicle, mut body) = truck_on(0.3, mode); + vehicle.set_wetness(wetness); + let hill = Hill { + grade: 0.3, + surface: Surface::Dirt, + }; + drive(&mut vehicle, &mut body, &hill, 0.8, 8.0) + }; + let dry = climb(DriveMode::FourHigh, 0.0); + let wet_two = climb(DriveMode::TwoHigh, 1.0); + let wet_four = climb(DriveMode::FourHigh, 1.0); + assert!(dry > 40.0, "dry, it climbed {dry} m"); + assert!(wet_four > 15.0, "wet, in four-wheel drive, {wet_four} m"); + assert!( + wet_two < wet_four * 0.5, + "wet, in two-wheel drive, {wet_two} m against {wet_four}" + ); +} + +#[test] +fn lockers_pull_it_off_a_split_of_rock_and_bog() { + // The left wheels on rock, the right ones in a bog, on a hill: open differentials send the + // drive to the side that spins. + struct SplitHill; + impl Ground for SplitHill { + fn cast(&self, from: Vec3, direction: Vec3, reach: f32) -> Option { + let hill = Hill { + grade: 0.25, + surface: Surface::Rock, + }; + let mut contact = hill.cast(from, direction, reach)?; + if (from + direction * contact.distance).x > 0.0 { + contact.surface = Surface::Bog; + } + Some(contact) + } + } + let climb = |locked: bool| { + let (mut vehicle, mut body) = truck_on(0.25, DriveMode::FourLow); + vehicle.set_lockers(locked, locked); + vehicle.set_wetness(1.0); + drive(&mut vehicle, &mut body, &SplitHill, 0.6, 8.0) + }; + let (open, locked) = (climb(false), climb(true)); + assert!( + locked > open * 1.25 && locked > 5.0, + "locked {locked} m, open {open} m" + ); + // On the level the same split is no trouble either way. + let (mut vehicle, mut body) = truck(DriveMode::FourHigh); + let level = Split { + left: Surface::Rock, + right: Surface::Mud, + }; + assert!(drive(&mut vehicle, &mut body, &level, 0.5, 5.0) > 20.0); +} + +#[test] +fn it_brakes_and_stays_straight_on_dirt() { + let (mut vehicle, mut body) = truck(DriveMode::FourHigh); + let road = flat(Surface::Dirt); + body.velocity = Vec3::NEG_Z * (80.0 / 3.6); + vehicle.set_gear(4); + vehicle.roll_with(&body); + let mut driver = Driver::new(true); + let asked = Asked { + brake: 1.0, + ..Asked::default() + }; + let start = body.position; + let mut seconds = 0.0; + while body.velocity.length() > 0.5 && seconds < 15.0 { + let controls = driver.drive(&asked, &vehicle, &body, G, DT); + vehicle.step(&mut body, &controls, &road, DT); + seconds += DT; + } + let distance = (start - body.position).z; + // About 0.65 g on hard dirt: 80 km/h in something under 45 m. + assert!((28.0..50.0).contains(&distance), "stopped in {distance} m"); + assert!( + body.position.x.abs() < 1.0, + "it pulled to {}", + body.position.x + ); +} diff --git a/crates/solstice-vehicle/tests/truck.vehicle b/crates/solstice-vehicle/tests/truck.vehicle new file mode 100644 index 0000000..53ecb65 --- /dev/null +++ b/crates/solstice-vehicle/tests/truck.vehicle @@ -0,0 +1,60 @@ +# A four-wheel-drive desert pickup: 2.8 tonnes, a supercharged 5.2-litre V8, a ten-speed +# automatic, a part-time transfer case with a 2.64 low range, and long-travel suspension on +# 35-inch all-terrain tyres. Its figures are those published for such a truck. It is test data +# for the vehicle model off the road, and the tests that drive it (truck.rs, ruts.rs, and +# solstice-game's things.rs) hold it to what such a truck does. + +mass 2800 # 2694 kg at the kerb, with a driver and some fuel +inertia 7600 8300 1800 # pitch, yaw, roll +centre 0 0.78 -0.38 # 56% of its weight on the front axle, high as a truck's is +body 1.96 1.3 5.0 at 0 1.27 0 # what it hits things with: its cab and tray, above the + # line from bumper to bumper that its wheels keep clear +tray 1.55 0.545 1.70 at 0 0.905 1.90 # the tray, inside, inside: what is + # put in it lies in it, and can be thrown out of it + +# Thirteen inches of wheel travel at the front and fourteen at the rear, on soft springs: about +# 1.3 Hz, with dampers firm enough that 2.8 tonnes settles in one move rather than bouncing. The +# rear is a live axle with next to no anti-roll bar, so that it can cross its wheels. +front at=2.003 track=1.872 radius=0.4365 inertia=3.6 driven=yes +front spring=52000 bump=5400 rebound=10200 bar=11000 travel=0.17,0.16 roll_centre=0.15 +front brake=3900 grip=1 +rear at=1.683 track=1.872 radius=0.4365 inertia=4.2 driven=yes +rear spring=44000 bump=4700 rebound=8900 bar=3000 travel=0.19,0.17 roll_centre=0.35 +rear brake=2300 grip=1 + +# An all-terrain tyre: about the friction of a road tyre, less than a slick's, gripping best at +# more slip and giving way gently. +tyre grip=1.0,0.95 peak=0.13,9 along=1.5,0.3 across=1.35,0.1 +tyre load=7000 sensitivity=0.1 relaxation=0.5 + +engine idle=700 limit=7000 inertia=0.5 friction=45,0.012 +torque 1000 520 +torque 1500 640 +torque 2000 720 +torque 2500 780 +torque 3000 820 +torque 3500 850 +torque 4250 868 # 640 lb ft +torque 5000 850 +torque 5500 830 +torque 6000 805 +torque 6650 771 # 537 kW: 720 hp +torque 7000 720 +torque 7400 600 + +gears 4.696 2.985 2.146 1.769 1.52 1.275 1 0.854 0.689 0.636 +final 4.1 +reverse 4.866 +gearbox shift=0.18 efficiency=0.88 clutch=1500 cruise=0.42 +# Both differentials are open until they are locked: one wheel in the air or in a bog takes the +# drive, which is what the lockers are for. +diff preload=40 power=0 coast=0 +front_diff preload=20 power=0 coast=0 +transfer low=2.64 front=0.5 lock=30000 locker=30000 + +aero drag=1.5 downforce=0 balance=0.5 +steering lock=34 ackermann=0.7 quick=0.55 +geometry anti_dive=0.2 anti_squat=0.25 +# Its traction control lets a wheel slip as far as the ground under it grips best at, as the +# truck's off-road modes do. No stability control: off the road a slide is how it turns. +assists abs=yes traction=yes stability=no descent=yes diff --git a/crates/solstice-vehicle/tests/wagon.vehicle b/crates/solstice-vehicle/tests/wagon.vehicle new file mode 100644 index 0000000..d76f060 --- /dev/null +++ b/crates/solstice-vehicle/tests/wagon.vehicle @@ -0,0 +1,45 @@ +# A big diesel four-wheel-drive wagon of the early 1990s, on coils and live axles: two tonnes, +# 315 N m, a five-speed gearbox and a transfer case, and no driver's aids. Its `hold` lines are +# the places things are carried in it. It is test data for what a blow does to a car +# (solstice-game's impact.rs and blows.rs). + +mass 2010 +inertia 3871 4228 904 +centre 0 0.76 -0.18 +body 1.84 1.30 4.87 at 0 1.21 0.12 +driver right +hold 0.743 0.420 0.430 at -0.461 0.860 -0.000 +hold 1.666 0.420 0.390 at 0.000 0.860 0.825 +hold 1.642 0.450 1.255 at 0.000 0.955 1.857 + +front at=1.485 track=1.560 radius=0.4000 inertia=2.77 driven=yes +front spring=46661 bump=4846 rebound=9153 bar=7896 travel=0.11,0.10 roll_centre=0.15 +front brake=2800 grip=1 +rear at=1.485 track=1.560 radius=0.4000 inertia=3.19 driven=yes +rear spring=39482 bump=4217 rebound=7986 bar=2154 travel=0.13,0.11 roll_centre=0.35 +rear brake=1651 grip=1 + +tyre grip=1.0,0.95 peak=0.13,9 along=1.5,0.3 across=1.35,0.1 +tyre load=5025 sensitivity=0.1 relaxation=0.5 + +engine idle=750 limit=4400 inertia=0.33 friction=27,0.012 +torque 1000 189 +torque 1400 283 +torque 1800 315 +torque 2600 315 +torque 3400 267 +torque 4000 205 +torque 4400 126 + +gears 3.93 2.33 1.45 1 0.82 +final 4.1 +reverse 4.2 +gearbox shift=0.35 efficiency=0.88 clutch=1077 cruise=0.42 +diff preload=40 power=0 coast=0 +front_diff preload=20 power=0 coast=0 +transfer low=2.3 front=0.5 lock=30000 locker=30000 + +aero drag=1.17 downforce=0 balance=0.5 +steering lock=33 ackermann=0.7 quick=0.55 +geometry anti_dive=0.2 anti_squat=0.25 +assists abs=no traction=no stability=no descent=no diff --git a/crates/solstice-world/src/input.rs b/crates/solstice-world/src/input.rs index 6240f04..6a444f9 100644 --- a/crates/solstice-world/src/input.rs +++ b/crates/solstice-world/src/input.rs @@ -19,6 +19,12 @@ use std::sync::Arc; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Played; +/// Marks one the player can play and is not playing now: a car whose driver has got out of +/// it, or the driver while they are in it. Its script hears nothing, and a car is asked for +/// nothing but its handbrake. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Idle; + /// Each action's value, which were pressed since the step before, where the game is watched /// from, and whether the player is away. Actions not mentioned are 0. #[derive(Clone, Debug, Default, PartialEq)] diff --git a/crates/solstice-world/src/lib.rs b/crates/solstice-world/src/lib.rs index c832088..7a625b0 100644 --- a/crates/solstice-world/src/lib.rs +++ b/crates/solstice-world/src/lib.rs @@ -20,7 +20,7 @@ pub use clock::{FixedClock, FrameSteps, MAX_STEPS_PER_FRAME, STEPS_PER_SECOND, S pub use events::{steps_for, TimerId}; pub use game::{Game, Schedule, TickGroup}; pub use hecs::{self, Entity}; -pub use input::{Input, Played, Recording}; +pub use input::{Idle, Input, Played, Recording}; pub use name::Name; pub use transform::{GlobalTransform, Parent, Snap, Transform, Walk}; pub use world::World; diff --git a/crates/solstice-world/src/transform.rs b/crates/solstice-world/src/transform.rs index 7dbaca0..28d465d 100644 --- a/crates/solstice-world/src/transform.rs +++ b/crates/solstice-world/src/transform.rs @@ -96,7 +96,8 @@ impl GlobalTransform { } /// How a walking character wants to move, in metres a second across the ground. Set by its script -/// each step, carried out by physics, and held until set again. +/// each step, carried out by physics, and held until set again. Its `y` is a jump: the speed +/// to leave the ground with, heeded only while the character stands on something. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct Walk(pub Vec3); diff --git a/docs/gameplay.md b/docs/gameplay.md index 012ffc7..e6decd5 100644 --- a/docs/gameplay.md +++ b/docs/gameplay.md @@ -1088,6 +1088,12 @@ Built for a racing game on the engine, (`kerb`, `grass`, `gravel`, `concrete`). From it each tyre knows what it is on, laps are timed with sectors, a lap that leaves the road does not count, and `reset` puts a car back. A car that falls far below its track is put back without asking. +- **Land that is no circuit** has a map of its ground instead, named by a scene's + `surfaces FILE` (`solstice_game::SurfaceMap`, `crates/solstice-game/src/ground.rs`): a grid + of squares, each of one surface, which each tyre reads the square it is on of. Besides a + circuit's four there are `dirt`, `mud`, `bog`, `litter`, `rock`, `ford` and `sand`, each + with how far a tyre sinks into it and what rain does to it. Where a scene has both, the + map is what the tyres read. Soft ground keeps the ruts driven into it (docs/ruts.md). - **The camera** follows the player's car. `camera` steps through four views behind it, each further out, and two on it. `look_round` and `look_over`, the right stick, swing it round the car and tip it over; `look_back` is the mirror. @@ -1135,6 +1141,42 @@ Built for a racing game on the engine, of what is in it. A scene without actors has no section, so it is written byte for byte as before. The bake checks every actor, setting and script, and stops at the first mistake, with its line. +- **What several scenes share.** A game's maps have things in common that are no part of any + of them: its truck, what its driver carries. Baked into each, they are in every map's file. + - `shared` at the end of an `actor` line says the actor's model is not in this scene's file + but in one beside it, `shared.solstice`, baked from a scene of its own that has an actor + of the same `.actor` file. The actor itself, its script, physics and place, is still the + scene's. + - Whatever reads the two joins them into one scene (`solstice_asset::join::join`): the + shared file's tables go after the scene's, renumbered, its pages are dealt in among the + scene's from coarse to fine, and its bytes are numbered on from wherever the reader says + (`Joined`), for a scene read from its file as it is drawn. The viewer does so + (`apps/viewer/src/shared.rs`, `read_source` in `main.rs`): the scene's actor is given + the instances that draw it, moved to where the scene puts it. A scene read from its file + as it is drawn (`--stream`) reads the shared file the same way, its bytes numbered on + from the end of the scene's. The viewer does not yet do so in a browser. + - A joined scene is drawn as any other, and the first scene's own numbers do not change. + What is refused: a scene split up for a browser, textures of different sizes, and + collision or glowing cards in the shared file. + - **Lending.** Maps have more in common than their truck: the same trees, grass and + stone, the same textures under the ground. A map's own instances are of these, so they + cannot simply be the shared scene's. Instead the shared scene lends + (`crates/solstice-bake/src/lend.rs`): + - `lends` in a scene's text makes it carry a list of every mesh and texture it has, each + with a key, a hash of what it is (the gameplay file `shared.lends`). + - A scene with a `shared` actor, baked beside that file, leaves out of its own whatever + has a key on the list: the mesh becomes an empty place that keeps its number, the + texture is dropped, and the scene carries a list of what it left (`shared.borrows`). + Nothing says which things are shared. What both have bit for bit is left out, and what + differs by anything is kept, so a map is never given the wrong tree. + - As the two are joined the places are filled (`solstice_asset::join::fill`): each empty + mesh is the lender's, each such material has the lender's layer. The map's instances + and materials keep their numbers. + - So the shared file is baked first, and a map baked beside one shared file is read with + that one: if the stock has changed since, the join says so, and both are baked again. + - With `SOLSTICE_WHOLE` set, the bake takes no notice of `shared`, leaves nothing out, and + the scene has everything in it: to look at a map on its own, or to tell a fault in the + joining from one in the map. - **Input** (`.input` files, or built-in actions). An action's value is the sum of its controls, times their scales. - Buttons and sticks add up to between -1 and 1. diff --git a/docs/ruts.md b/docs/ruts.md new file mode 100644 index 0000000..d286768 --- /dev/null +++ b/docs/ruts.md @@ -0,0 +1,225 @@ +# Ruts: ground that keeps what is driven into it, and mud that looks wet + +A truck driven through a bog leaves two ruts as deep as it sank, with what it pushed aside +heaped along them and its tread printed in the floor. The wheels behind ride in the ruts of the +wheels ahead, a wheel that spins digs itself down to its axle, and water stands in whatever is +deep enough. This says how that is built, what to tune, what it costs, and how to look at it. + +## Where everything is + +| What | Where | +| --- | --- | +| The map of what has been pressed into the ground | `crates/solstice-vehicle/src/rut.rs` (`Ruts`, `Press`) | +| How each surface takes a mark | `crates/solstice-vehicle/src/surface.rs` (`Soil`, `Surface::soil`) | +| A tyre standing in a rut, digging, and leaving its mark | `crates/solstice-vehicle/src/vehicle.rs` (`Ground::rut`, `Ground::press`, `Vehicle::mark`, the "floor" lines in `substep`) | +| The scene's map, and the belly dragging | `crates/solstice-physics/src/car.rs` (`SceneGround`, `drag_belly`), `Physics::ruts` | +| The map on the GPU | `crates/solstice-render/src/ruts.rs` (`RutMap`, `RutSource`), `Renderer::sync_ruts` | +| Drawing it, and mud as it lies | `crates/solstice-render/shaders/ground/ruts.wgsl`, called from `vg/resolve.wgsl` | +| Joining the game's map to the renderer | `apps/viewer/src/play.rs` (`draw_ruts`) | + +## The approach, and why + +The land is baked. It is virtual geometry: clusters of triangles made once, with points half a +metre apart and an eighth of a metre along a track, streamed in pages and never changed. A rut +is a tyre wide and a hand deep, its berm a few centimetres, its tread's print a centimetre. So: + +- **Moving the land's own points would not do it.** Even along a track there are two or three + points across a tyre, and off it none. And every pass that places a point would have to move + it the same way (both rasterizers, the shadow passes, culling bounds, the GI's voxels), as + swaying in the wind does, for a result too coarse to show a rut's edge. +- **Laying new geometry over the land would not either.** A rut is below the land's surface, + which would hide it. + +What is built is **a map of how far the ground has been pressed down or heaped up, read by the +wheels and by the shader that works out each pixel's material**: + +1. **One map for both** (`rut.rs`). Cells of 4 cm, in squares of 64 × 64 cells (2.56 m) that are + made only where something has been driven. Each cell holds the ground's height against how + it was made, the tread's print, how wet it is, and how much churned soil shows: eight + bytes, laid out as the renderer samples them, so the game's copy is copied to the GPU as + it is. +2. **The wheels read it and press it** (`vehicle.rs`). A wheel's ray meets the land as before; + the depth of the rut at that place is then the floor the tyre stands on. The tyre sinks + below that floor only as far as it would have sunk in ground nobody had pressed, and each + step presses the map to where the tyre's bottom now is. So the tyre sits in the rut that is + drawn, to the cell. +3. **The shader draws it** (`ground/ruts.wgsl`). For each pixel of ground, the eye's ray is + followed through the pressed ground to where it meets it (relief mapping, with the land's + own surface as the level nothing was pressed from). The ground's textures are laid there, + its facing is the pressed ground's, and it is shaded as what it is. A rut is seen into: its + near wall hides its floor, its berm stands in front of what is behind it, and the low sun + leaves its floor in shade. A tyre sunk in it is drawn where the physics has it, with the + land's surface hiding what is below the ground: it sits in the rut. + +What this does not give: the rut does not change the land's silhouette (a deep rut seen +exactly side on, at ground level, is flat), the sun's shadow maps and the GI do not know of it +(the shade in a rut is worked out in the shader and laid on the surface's colour), and things +other than wheels and a truck's belly do not fall into it: a loose thing or somebody walking +still stands on the land as it was made. + +## What the ground does + +### A tyre in soft ground + +`SurfaceGrip` (in `surface.rs`) already said how far a tyre sinks into each surface and how +much further a spinning one digs. That is unchanged, and on ground that keeps no ruts (the +circuit tests' `Flat`) nothing behaves differently. On ground that keeps them: + +- **The floor.** `Ground::rut` gives the depth of the rut under the tyre. The tyre stands on + it. If the tyre would sink further than that in fresh ground, it sinks the rest of the way + (taking `SINK_SECONDS`) and the rut is pressed deeper; if not, it rides in the rut as it is. + The wheels behind therefore ride in the ruts of those ahead, and a second truck down the + same ruts makes them no deeper. +- **Digging.** A wheel that spins reaches a little below the floor of the hole it is in + (`DIG_ON` times the surface's `dig`), each moment, so a wheel left spinning goes down + steadily: about 5 cm a second flat out in a bog, a quarter of that with traction control + holding the slip. It stops at `deepest`: `DIG_SOFT` times the surface's sink plus `DIG_SPUN` + times its dig, and never more than `DIG_RADIUS` of the tyre's radius, by when the truck is + on its belly. +- **Drag.** As before, `RUT_DRAG` times the tyre's depth over its radius, as a share of its + load. The depth is now the rut's, so a deep rut holds a truck back whoever made it. +- **Berms.** A tyre on a berm rides over it (the "depth" there is below zero) and, in soft + ground, squashes it. +- **The belly.** Where the truck's underside is within `BELLY_NEAR` of soft ground, the crown + between the ruts is pressed flat `BELLY_PRESSES` deep in a broad smear (`drag_belly`). The + truck's body still collides with the land as it was made. + +### The mark a tyre leaves (`Vehicle::mark`, `Ruts::press`) + +Once a step, each tyre on the ground presses a strip from where its contact was to where it +is: + +- **The rut**: flat under the tread, rounded at the shoulders (`profile`), as deep as the tyre + has sunk, and no deeper than that ground can be pressed, so a tyre climbing out of a bog on + to rock leaves the rock alone. The ground only ever goes down under a tread. +- **The berm**: the share of what was pressed out that the surface's `Soil::berm` says is + heaped rather than packed (half in mud, a fifth in leaf litter), in a ridge just outside each + shoulder, at most 0.6 of the rut's depth and 12 cm. A berm heaped where a rut already is + fills some of it. +- **The tread's print**: each cell under the tread takes where in the tread's pattern it was + pressed (the wheel's own angle, `TREAD_LUGS` lugs to a turn) and how crisp the print is: 1 + for a tyre that rolls, falling to 0 as its slip passes a third. So a rolling tyre prints + every lug, a spinning or locked one smears its own print and whatever was there, and the + rear tyres print over the fronts'. +- **Wet and churned**: `Surface::soil` says how wet what is churned up is and how wet it stays + (`Soil::wet`, `stays`), and how much bare soil is left showing (`churn`). A bog's ruts are + sodden and stay so; a clay track's are damp after rain and dry pale. +- **What the tyre carries**: a tyre out of a creek is wet, and one out of a bog muddy + (`Vehicle::carried`), for `CARRIES_WATER` and `CARRIES_MUD` metres of rolling. It leaves + wet, muddy tracks on whatever it rolls on next, rock included, with no rut under them. +- **Drying** (`Ruts::advance`): what is wetter than it stays dries towards it over + `DRY_SECONDS`, a few squares at a time. + +A game can lay lumps of thrown mud in the same map (`Ruts::splat`): a blot a few centimetres +across, wet, standing a little proud, covering whatever print was under it. + +Ruts last as long as the map is being played. They are not kept in a saved game, and a map +that is left and come back to is fresh. + +## How it looks (`ground/ruts.wgsl`) + +All of it is decided where a pixel's material is, before lighting, so the sun, the sky, the +lamps, reflections and the rain all light the pressed ground as they light anything. + +- **Churned soil** (`rut_shade`): where the ground was broken, soil the colour of the country + (`Renderer::set_rut_soil`, red clay unless told) shows in place of what covered it, in clods + and smears, lumpier and paler on a berm. +- **The print**: `rut_tread` is a mud tyre's pattern, blocks down the middle and lugs at the + shoulders, pressed in `RUT_PRINT_DEPTH` deep. It is drawn within `RUT_PRINT_TO` metres. +- **Shade**: low ground sees less sky (its cavity is deepened), and a few steps towards the + sun find whether a wall or a berm stands in the way. +- **Wet**: the cell's wetness goes through the same wet material as the sea's and the rain's + (`common/wetness.wgsl`): pores fill and the soil darkens, then a film forms and it shines. + A fresh rut in a bog is dark and glossy; one in a clay track after rain is dark and damp; + both dry paler. +- **Standing water**: water stands in a rut deeper than a brim that falls from 22 cm to + 2.5 cm as the cell's wetness goes from 0.55 to 1, and falls further as the rain fills the + puddles. It is brown with clay, level and smooth, with a wandering edge. So a bog's ruts + hold water at once, a clay track's after rain, and dry ground's never. +- **Mud nobody has driven on** (`mud_lies`): ground whose material is marked `Material::MUD` + is drawn as mud lies. Where there is most of it, it is wet clay: darker, with a sheen that + comes and goes across it, and water standing in its hollows. Towards its rim, where it + thins out, it has dried to a paler crust cracked into plates a hand or two across, each its + own shade, with finer cracks inside them. Rain wets all of it and closes the cracks. + **A map baked before this has no such mark**: its mud is drawn as before until it is baked + again. Ruts need no rebake. + +## Numbers to tune + +| Number | Where | Now | Does | +| --- | --- | --- | --- | +| `CELL` | `rut.rs` | 0.04 m | The map's fineness. Halving it quadruples memory and what is copied. | +| `TILES` | `render/src/ruts.rs` | 24 (12 in a browser, on a phone) | How far round the truck ruts are drawn: 61 m across (31 m). | +| `DRY_SECONDS` | `rut.rs` | 150 s | How long a fresh rut keeps its sheen. | +| `Soil` values | `surface.rs` | per surface | Wet, stays wet, churn, berm, print. | +| `SurfaceGrip::sink`, `dig` | `surface.rs` | per surface | How deep a tyre sinks and a spinning one digs: as before. | +| `DIG_ON` | `vehicle.rs` | 0.25 | How fast a spinning wheel goes down. | +| `DIG_SOFT`, `DIG_SPUN`, `DIG_RADIUS` | `vehicle.rs` | 1.5, 2.5, 0.7 | How deep it can dig itself. | +| `RUT_DRAG` | `vehicle.rs` | 0.35 | How hard a rut holds a truck back. | +| `TYRE_WIDTH` | `vehicle.rs` | 0.7 of the radius | The rut's width. | +| `CARRIES_WATER`, `CARRIES_MUD`, `WASHES_MUD` | `vehicle.rs` | 18, 30, 4 m | How long a tyre's tracks stay wet and muddy. | +| `BELLY_NEAR`, `BELLY_PRESSES` | `physics/src/car.rs` | 2, 2.5 cm | When the belly drags, and how deep its smear is. | +| `RUT_ABOVE`, `RUT_BELOW`, `RUT_REACH` | `ruts.wgsl` | 0.13, 0.42, 1.6 m | The slab the eye's ray is followed through. | +| `RUT_TRACED_TO` | `ruts.wgsl` | 45 m | Beyond it ruts are shaded but not seen into. | +| `RUT_PRINT_DEPTH`, `RUT_PRINT_TO` | `ruts.wgsl` | 7 mm, 14 m | The tread's print. | +| The brim (`rut_shade`) | `ruts.wgsl` | 22 cm to 2.5 cm | How deep a rut must be to hold water. | + +## Cost + +- **Where nobody has driven: next to nothing.** The map is an empty table: a wheel's look in + it returns at once. `Renderer::sync_ruts` returns at its first line. The shader tests one + number of the frame's constants (`rut_window.z`) for each pixel of ground and skips all of + it. Mud's own look (`mud_lies`) runs only on pixels of mud. +- **Memory.** A square of the map is 36 kB in the game (its cells, and how wet each stays), so + a kilometre of two ruts is some 30 MB. On the GPU, one texture of 1536² texels in two layers + with its smaller sizes: 25 MB on a desktop, 6 MB in a browser or on a phone, allocated + whether or not anything is driven. +- **Each step**: four strips pressed, some two hundred cells each, and four looks in the map + for each of ten short steps. +- **Each frame**: the squares that changed are copied to the GPU, at most 24 a frame, nearest + the truck first: under a moving truck, four to eight, 48 kB each with their smaller sizes. +- **The shader**: on ground with ruts within a metre or two, one look to find that out, up to + 22 steps of the eye's ray and 5 to settle where it meets, four for the facing, seven for + the shade, two for what is there, and six more for the tread's print close to the camera. + Elsewhere, the one look. + +Measured on an RTX 5080 at 1920 × 1080, on a flat map of bog made by the game these came from +(`gpu ms` in a `--capture` run's report): the resolve pass takes 0.32 ms with the bog in view +and nothing driven, and 0.39 ms with a truck in the bog and its ruts behind it across the +middle of the picture. Not measured: an integrated GPU, a browser, a phone. + +## Looking at it + +Ruts are kept wherever a car is driven on ground that takes a mark (`Surface::soil`): deep in +mud, a bog and sand, shallow on grass, gravel and dirt, and not at all on tarmac, concrete and +rock. The viewer draws them round whatever is driven (`play.rs`, `draw_ruts`). + +- On a circuit, what takes a mark is what its track says lies beside the road: the grass and + the gravel traps. +- Anywhere else, a scene's text names a map of its ground, `surfaces FILE` + (`solstice_game::SurfaceMap`, `crates/solstice-game/src/ground.rs`): a grid of squares, each + of one surface, which each tyre reads the square it is on of. A scene with such a map that + has mud in it, and a car, is all it takes. None of the engine's own scenes has one yet. + +## What is not right yet + +- **Deep ruts in a storm.** With the ground soaked the truck digs ruts of 25 to 30 cm, whose + berms are 12 cm high. Under an overcast sky, beside ground shining with rain, those berms + read as dark slabs. They want lumpier, paler crests, or less height. +- **A rut has no edge against the sky**, and the sun's shadow maps do not know of it: see + "The approach". +- **None of the engine's own scenes has mud or a bog**: this has been driven in the game it + was built for, and here only in tests. + +## Tests + +- `crates/solstice-vehicle/src/rut.rs`: pressing, berms, that a rut stays and only a deeper + wheel deepens it, crossings, the tread's print and its smearing, drying, the squares listed + as changed, and that the bytes the renderer is given are the height the wheels read. +- `crates/solstice-vehicle/tests/ruts.rs`: a truck on ground that keeps its ruts. A standing + truck's tyres are as deep as the map says; it leaves ruts and berms behind it; rear wheels + ride in the fronts' ruts; a spinning wheel digs in; four-wheel drive still crosses a bog and + two-wheel drive still does not; a deep rut slows a coasting truck; wet tracks on rock out of + a creek. +- `crates/solstice-render`: the frame's constants lay out as their shader twin, and every + shader compiles, with the ruts' among them. From 75820a566559bf2fb504b4807ffddf4bc42d5b58 Mon Sep 17 00:00:00 2001 From: SamG-Coder <13449963+SamG-Coder@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:11:10 +1100 Subject: [PATCH 2/3] Keep #88 from costing scenes that use none of it, and refuse damaged files - Glass is a blended material whose colour is see-through. One whose colour is opaque is drawn opaque, as before glass, and stays off the masked raster path, with the old warning. - The pack reader holds every length to the file's size, the surface map refuses runs that would wrap and rows past its own, and filling a borrowed scene checks its sums. - The ruts' texture is a one-square stand-in until something is first pressed, so a scene nobody drives on no longer allocates tens of megabytes for it; the resolve pass is bound again when it is made whole. - A square of ruts is counted changed, and copied to the GPU, only when its bytes change, so a car standing on grass no longer re-uploads its squares every frame; a square a strip changed nothing in is not kept. The strip's size guard saturates. Co-Authored-By: Claude Opus 5.5 --- crates/solstice-asset/src/join.rs | 11 +- crates/solstice-asset/src/pack.rs | 57 +++++++++- crates/solstice-game/src/ground.rs | 8 +- crates/solstice-import/src/material.rs | 20 +++- crates/solstice-import/src/tests.rs | 13 +++ crates/solstice-render/src/renderer.rs | 22 ++++ crates/solstice-render/src/ruts.rs | 90 +++++++++------ crates/solstice-render/tests/gpu.rs | 70 ++++++++++++ crates/solstice-vehicle/src/rut.rs | 150 +++++++++++++++++-------- 9 files changed, 343 insertions(+), 98 deletions(-) diff --git a/crates/solstice-asset/src/join.rs b/crates/solstice-asset/src/join.rs index 2f3abe1..72df106 100644 --- a/crates/solstice-asset/src/join.rs +++ b/crates/solstice-asset/src/join.rs @@ -108,21 +108,20 @@ pub fn fill( let theirs = *there.get(&(what, key)).ok_or_else(stale)?; match what { Lent::Mesh => { - let mesh = *scene - .meshes - .get((joined.meshes + theirs) as usize) - .ok_or_else(stale)?; + let at = joined.meshes.checked_add(theirs).ok_or_else(stale)?; + let mesh = *scene.meshes.get(at as usize).ok_or_else(stale)?; *scene.meshes.get_mut(index as usize).ok_or_else(stale)? = mesh; } Lent::Texture => { - if (joined.layers + theirs) as usize >= scene.base_textures.len() { + let at = joined.layers.checked_add(theirs).ok_or_else(stale)?; + if at as usize >= scene.base_textures.len() { return Err(stale()); } scene .materials .get_mut(index as usize) .ok_or_else(stale)? - .texture_layer = (joined.layers + theirs) as i32; + .texture_layer = i32::try_from(at).map_err(|_| stale())?; } } } diff --git a/crates/solstice-asset/src/pack.rs b/crates/solstice-asset/src/pack.rs index ad753bf..1dbcfa7 100644 --- a/crates/solstice-asset/src/pack.rs +++ b/crates/solstice-asset/src/pack.rs @@ -45,7 +45,10 @@ fn wrong(what: &str) -> io::Error { } /// Reads the list of what is in a pack, from its beginning. +/// Every length in it is held to what the file has, so a damaged pack is refused rather than +/// asking for more memory than the file could fill. pub fn read_list(file: &mut (impl Read + Seek)) -> io::Result> { + let size = file.seek(SeekFrom::End(0))?; file.seek(SeekFrom::Start(0))?; let mut head = [0; 12]; file.read_exact(&mut head)?; @@ -53,6 +56,9 @@ pub fn read_list(file: &mut (impl Read + Seek)) -> io::Result> { return Err(wrong("it is not a pack")); } let length = u32::from_le_bytes([head[8], head[9], head[10], head[11]]); + if 12 + u64::from(length) > size { + return Err(wrong("its list runs past its end")); + } let mut list = vec![0; length as usize]; file.read_exact(&mut list)?; let list = String::from_utf8(list).map_err(|_| wrong("its list is not text"))?; @@ -66,21 +72,35 @@ pub fn read_list(file: &mut (impl Read + Seek)) -> io::Result> { let length: u64 = length .parse() .map_err(|_| wrong("a length in its list is not a number"))?; - entries.push(Entry { + let entry = Entry { kind: kind.to_owned(), name: name.to_owned(), start, length, - }); - start += length; + }; + start = start + .checked_add(length) + .filter(|&end| end <= size) + .ok_or_else(|| wrong("a thing in its list runs past its end"))?; + entries.push(entry); } Ok(entries) } /// Reads one thing out of a pack. +/// An entry that runs past the file's end is refused before anything is read. pub fn read(file: &mut (impl Read + Seek), entry: &Entry) -> io::Result> { + let size = file.seek(SeekFrom::End(0))?; + if entry + .start + .checked_add(entry.length) + .is_none_or(|end| end > size) + { + return Err(wrong("that thing runs past the pack's end")); + } file.seek(SeekFrom::Start(entry.start))?; - let mut bytes = vec![0; entry.length as usize]; + let mut bytes = + vec![0; usize::try_from(entry.length).map_err(|_| wrong("that thing is too big"))?]; file.read_exact(&mut bytes)?; Ok(bytes) } @@ -111,4 +131,33 @@ mod tests { // What is not a pack is refused. assert!(read_list(&mut Cursor::new(b"not a pack at all".to_vec())).is_err()); } + + #[test] + fn a_damaged_pack_is_refused_not_believed() { + let good = write(&[("piece", "cab", &[1, 2, 3])]); + // A list longer than the file. + let mut long_list = good.clone(); + long_list[8..12].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(read_list(&mut Cursor::new(long_list)).is_err()); + // A thing longer than the file, and one so long its end overflows. + for length in ["4", "18446744073709551615"] { + let mut file = Vec::from(*MAGIC); + let list = format!( + "piece cab {length} +" + ); + file.extend((list.len() as u32).to_le_bytes()); + file.extend(list.as_bytes()); + file.extend([1, 2, 3]); + assert!(read_list(&mut Cursor::new(file)).is_err(), "{length}"); + } + // An entry made up by hand is held to the file too. + let entry = Entry { + kind: "piece".to_owned(), + name: "cab".to_owned(), + start: 0, + length: u64::MAX, + }; + assert!(read(&mut Cursor::new(good), &entry).is_err()); + } } diff --git a/crates/solstice-game/src/ground.rs b/crates/solstice-game/src/ground.rs index 9e1ad32..215291c 100644 --- a/crates/solstice-game/src/ground.rs +++ b/crates/solstice-game/src/ground.rs @@ -89,6 +89,9 @@ impl SurfaceMap { continue; }; // A row: runs, each a count and a letter. + if map.squares.len() >= (map.columns * map.rows) as usize { + return Err(error(format!("more than {} rows", map.rows))); + } let mut count = 0_u32; let mut filled = 0_u32; let mut digits = false; @@ -106,7 +109,7 @@ impl SurfaceMap { .filter(|&s| s < Surface::ALL.len() as u32) .ok_or_else(|| error(format!("`{letter}` is no surface")))?; let run = if digits { count } else { 1 }; - filled += run; + filled = filled.saturating_add(run); if filled > map.columns { return Err(error(format!("more than {} squares", map.columns))); } @@ -209,6 +212,9 @@ mod tests { ("surfaces 0 0 1 2 1\ni", 2, "1 squares"), ("surfaces 0 0 1 2 1\n2z", 2, "no surface"), ("surfaces 0 0 1 2 2\n2a", 2, "1 rows"), + ("surfaces 0 0 1 2 1\n2a\n2a", 3, "more than 1 rows"), + // A run that would wrap the count round to fit. + ("surfaces 0 0 1 2 1\n1a4294967295a", 2, "more than 2"), ("surfaces 0 0 0 2 1\n2a", 1, "above 0"), ("# nothing", 1, "no `surfaces`"), ] { diff --git a/crates/solstice-import/src/material.rs b/crates/solstice-import/src/material.rs index 8c2eb2e..dd1ecf4 100644 --- a/crates/solstice-import/src/material.rs +++ b/crates/solstice-import/src/material.rs @@ -185,6 +185,12 @@ impl<'a> MaterialTable<'a> { )); } + if source.alpha_mode() == gltf::material::AlphaMode::Blend && !is_glass(source) { + warnings.push(format!( + "material '{name}': alpha mode Blend with an opaque colour is drawn as opaque" + )); + } + let pbr = source.pbr_metallic_roughness(); let mut uses_other_uv_set = false; let mut image_of = |set: u32, index: usize| { @@ -258,11 +264,7 @@ impl<'a> MaterialTable<'a> { } else { 0 } - | if source.alpha_mode() == gltf::material::AlphaMode::Blend { - Material::GLASS - } else { - 0 - }, + | if is_glass(source) { Material::GLASS } else { 0 }, roughness: pbr.roughness_factor(), metallic: pbr.metallic_factor(), uv_scale: 1.0, @@ -497,6 +499,14 @@ fn texel(image: &ImageData, x: i64, y: i64) -> [f32; 4] { } } +/// Whether a material is glass: blended, and seen through by its colour's own alpha. Glass is +/// drawn as a share of its pixels, by that alpha alone, so a blended material whose colour is +/// opaque stays opaque, as it was before glass, and keeps off the masked path it would not use. +fn is_glass(material: &gltf::Material<'_>) -> bool { + material.alpha_mode() == gltf::material::AlphaMode::Blend + && material.pbr_metallic_roughness().base_color_factor()[3] < 1.0 +} + /// What a material's name says of it: one whose name begins `paint` is the paint of /// something driven, and one whose name begins `inside` is in its cab or under its bonnet /// (`Material::PAINT`, `Material::INSIDE`). A model is given such names when it is made ready. diff --git a/crates/solstice-import/src/tests.rs b/crates/solstice-import/src/tests.rs index f3962fd..7e3e5db 100644 --- a/crates/solstice-import/src/tests.rs +++ b/crates/solstice-import/src/tests.rs @@ -457,6 +457,19 @@ fn a_blended_material_is_glass() { assert!(imported.warnings.iter().all(|w| !w.contains("Blend"))); } +/// A blended material whose colour is opaque is not glass: it is drawn opaque, as before glass, +/// and says so. +#[test] +fn a_blended_material_with_an_opaque_colour_is_not_glass() { + let dir = TempDir::new(); + let materials = r#", "materials": [{"alphaMode": "BLEND", + "pbrMetallicRoughness": {"baseColorFactor": [0.4, 0.5, 0.2, 1.0]}}]"#; + let path = write_model(&dir, r#"[{"mesh": 0}]"#, r#", "material": 0"#, materials); + let imported = import(&path); + assert_eq!(imported.scene.materials[0].flags & Material::GLASS, 0); + assert!(imported.warnings.iter().any(|w| w.contains("Blend"))); +} + /// Writes a model with two images, each a flat 2x2 colour, and the given materials over them, /// with the cube using material 0. fn masked_model(dir: &TempDir, first: [u8; 4], second: [u8; 4], materials: &str) -> PathBuf { diff --git a/crates/solstice-render/src/renderer.rs b/crates/solstice-render/src/renderer.rs index b31b2de..d928eff 100644 --- a/crates/solstice-render/src/renderer.rs +++ b/crates/solstice-render/src/renderer.rs @@ -288,6 +288,8 @@ struct SizedResources { cull_scene: wgpu::BindGroup, raster: RasterBindings, resolve: ResolveBindings, + /// The [`crate::ruts::RutMap::generation`] whose texture `resolve` binds. + ruts_generation: u32, screen_gi: ScreenGiBindings, clouds: CloudBindings, deferred: [wgpu::BindGroup; 2], @@ -1617,6 +1619,25 @@ impl Renderer { && s.water.as_ref().map(WaterTargets::for_sea) == self.water_kind() }); if unchanged { + // The ruts' texture is made whole at the first press: only the resolve pass, + // which reads it, is bound again. + let generation = self.ruts.generation(); + if let Some(sized) = self + .sized + .as_mut() + .filter(|sized| sized.ruts_generation != generation) + { + sized.resolve = self.resolve.bindings( + gpu, + &self.frame_uniform, + &self.scene, + &sized.visibility, + &self.main_work, + &sized.gbuffer, + &self.ruts.view, + ); + sized.ruts_generation = generation; + } return; } let visibility = VisibilityBuffer::new(gpu, &self.rasterizer, render_size); @@ -1716,6 +1737,7 @@ impl Renderer { cull_scene, raster, resolve, + ruts_generation: self.ruts.generation(), screen_gi, clouds, deferred, diff --git a/crates/solstice-render/src/ruts.rs b/crates/solstice-render/src/ruts.rs index 440965b..900de1b 100644 --- a/crates/solstice-render/src/ruts.rs +++ b/crates/solstice-render/src/ruts.rs @@ -50,10 +50,18 @@ pub trait RutSource { } /// The squares of ruts round the camera, on the GPU. +/// +/// Until something is first pressed it holds a stand-in of one square, which the shader never +/// reads (the window is empty), so a scene nobody drives on does not pay for the whole of it: +/// tens of megabytes on a desktop. The first press makes the whole texture; whoever bound the +/// stand-in binds [`RutMap::view`] again when [`RutMap::generation`] changes. pub struct RutMap { + device: wgpu::Device, queue: wgpu::Queue, texture: wgpu::Texture, pub view: wgpu::TextureView, + /// Whether `texture` is the whole window, not the stand-in. + whole: bool, /// Which square of ground each place in the texture holds, and that square's count of /// changes when it was copied. `None` is untouched ground. held: Vec>, @@ -67,45 +75,13 @@ pub struct RutMap { impl RutMap { pub fn new(gpu: &Gpu) -> Self { - let side = TILES * TILE; - let texture = gpu.device.create_texture(&wgpu::TextureDescriptor { - label: Some("ruts"), - size: wgpu::Extent3d { - width: side, - height: side, - depth_or_array_layers: 2, - }, - mip_level_count: LEVELS, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::Rgba8Unorm, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - // Untouched ground is not all zeros: its height is the middle of the range. - for level in 0..LEVELS { - let side = side >> level; - for (layer, cell) in UNTOUCHED.iter().enumerate() { - let texels = cell.repeat((side * side) as usize); - write( - &gpu.queue, - &texture, - level, - layer as u32, - (0, 0), - side, - &texels, - ); - } - } - let view = texture.create_view(&wgpu::TextureViewDescriptor { - dimension: Some(wgpu::TextureViewDimension::D2Array), - ..Default::default() - }); + let (texture, view) = make(&gpu.device, &gpu.queue, TILE); Self { + device: gpu.device.clone(), queue: gpu.queue.clone(), texture, view, + whole: false, held: vec![None; (TILES * TILES) as usize], cell: 0.04, middle: (0, 0), @@ -113,6 +89,11 @@ impl RutMap { } } + /// Counts the textures made: 0 for the stand-in, 1 once the whole window is. + pub fn generation(&self) -> u32 { + u32::from(self.whole) + } + /// Brings the texture up to date with the map, round `centre`: the world's x and z of /// what is looked at. Returns how many squares were copied. pub fn sync(&mut self, centre: Vec2, source: &dyn RutSource) -> usize { @@ -121,6 +102,10 @@ impl RutMap { if source.is_empty() && self.filled == 0 { return 0; } + if !self.whole { + (self.texture, self.view) = make(&self.device, &self.queue, TILES * TILE); + self.whole = true; + } self.cell = source.cell(); let metres = TILE as f32 * self.cell; self.middle = ( @@ -223,6 +208,41 @@ impl RutMap { } } +/// A texture of ruts `side` texels a side, at every size, all of it untouched ground. +fn make( + device: &wgpu::Device, + queue: &wgpu::Queue, + side: u32, +) -> (wgpu::Texture, wgpu::TextureView) { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("ruts"), + size: wgpu::Extent3d { + width: side, + height: side, + depth_or_array_layers: 2, + }, + mip_level_count: LEVELS, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + // Untouched ground is not all zeros: its height is the middle of the range. + for level in 0..LEVELS { + let side = side >> level; + for (layer, cell) in UNTOUCHED.iter().enumerate() { + let texels = cell.repeat((side * side) as usize); + write(queue, &texture, level, layer as u32, (0, 0), side, &texels); + } + } + let view = texture.create_view(&wgpu::TextureViewDescriptor { + dimension: Some(wgpu::TextureViewDimension::D2Array), + ..Default::default() + }); + (texture, view) +} + /// Copies a square of texels into one size of one layer. fn write( queue: &wgpu::Queue, diff --git a/crates/solstice-render/tests/gpu.rs b/crates/solstice-render/tests/gpu.rs index 7a9942f..a4d3d6b 100644 --- a/crates/solstice-render/tests/gpu.rs +++ b/crates/solstice-render/tests/gpu.rs @@ -6204,3 +6204,73 @@ fn a_pick_finds_the_instance_under_a_point() { assert_eq!(pick(0.79, 0.5).instance, Some(2)); assert_eq!(pick(0.5, 0.05).instance, None, "the sky above them"); } + +/// A map of ruts with one square pressed a little everywhere. +struct OnePressedSquare; + +impl solstice_render::RutSource for OnePressedSquare { + fn cell(&self) -> f32 { + 0.04 + } + fn is_empty(&self) -> bool { + false + } + fn version(&self, tile: (i32, i32)) -> u32 { + u32::from(tile == (0, 0)) + } + fn levels(&self, tile: (i32, i32), layer: usize) -> Option>> { + use solstice_render::ruts::{LEVELS, TILE}; + (tile == (0, 0)).then(|| { + let cell: [u8; 4] = if layer == 0 { + [127, 0, 128, 200] + } else { + [128, 128, 200, 255] + }; + (0..LEVELS) + .map(|level| cell.repeat(((TILE >> level) * (TILE >> level)) as usize)) + .collect() + }) + } +} + +/// The ruts' texture is a stand-in until the first press, and is made whole then: the frames +/// either side of that draw without errors, with the resolve pass bound to the new texture. +#[test] +fn ruts_are_drawn_from_the_first_press_without_errors() { + let Some(gpu) = request_gpu() else { return }; + let mesh = build_virtual_mesh(&sphere(2), &BuildOptions::default()); + let scene = SceneAsset { + meshes: vec![mesh], + materials: vec![white_material()], + instances: vec![instance(0, Mat4::IDENTITY)], + ..Default::default() + }; + let camera = Camera { + position: Vec3::new(0.0, 0.0, 5.0), + ..Default::default() + }; + let errors: Arc>> = Default::default(); + let sink = errors.clone(); + gpu.device + .on_uncaptured_error(Arc::new(move |error: wgpu::Error| { + sink.lock().unwrap().push(error.to_string()); + })); + let mut renderer = Renderer::new(&gpu, &paginate(&scene), FORMAT, RendererSettings::default()); + let target = test_target(&gpu, 64); + let view = target.create_view(&Default::default()); + for _ in 0..2 { + renderer.render(&gpu, &camera, &darkness(), &view, (64, 64), 1.0 / 60.0); + } + assert_eq!(renderer.sync_ruts(glam::Vec2::ZERO, &OnePressedSquare), 1); + for _ in 0..2 { + renderer.render(&gpu, &camera, &darkness(), &view, (64, 64), 1.0 / 60.0); + } + // Nothing changed since: nothing is copied again. + assert_eq!(renderer.sync_ruts(glam::Vec2::ZERO, &OnePressedSquare), 0); + renderer.render(&gpu, &camera, &darkness(), &view, (64, 64), 1.0 / 60.0); + gpu.device + .poll(wgpu::PollType::wait_indefinitely()) + .unwrap(); + let errors = errors.lock().unwrap(); + assert!(errors.is_empty(), "GPU errors: {}", errors.join("\n")); +} diff --git a/crates/solstice-vehicle/src/rut.rs b/crates/solstice-vehicle/src/rut.rs index 0b16c16..d705e9c 100644 --- a/crates/solstice-vehicle/src/rut.rs +++ b/crates/solstice-vehicle/src/rut.rs @@ -132,6 +132,25 @@ impl Tile { (f32::from(raw) - f32::from(HEIGHT_ZERO)) * HEIGHT_UNIT } + /// Everything a cell keeps: both layers' bytes, and how wet it stays. + fn cell_bytes(&self, cell: usize) -> [u8; 9] { + let (a, b) = ( + &self.layers[0][cell * 4..][..4], + &self.layers[1][cell * 4..][..4], + ); + [ + a[0], + a[1], + a[2], + a[3], + b[0], + b[1], + b[2], + b[3], + self.stays[cell], + ] + } + fn set_height(&mut self, cell: usize, height: f32) { let raw = (height.clamp(-DEEPEST, HIGHEST) / HEIGHT_UNIT).round() + f32::from(HEIGHT_ZERO); let bytes = (raw as u16).to_be_bytes(); @@ -351,7 +370,7 @@ impl Ruts { ); // A strip is a tyre's width and a step's length: anything far larger is a mistake, // a car put somewhere else between two steps. - if (i1 - i0) > 400 || (j1 - j0) > 400 { + if i1.saturating_sub(i0) > 400 || j1.saturating_sub(j0) > 400 { return; } let wet = byte(press.wet); @@ -366,6 +385,10 @@ impl Ruts { // The square is taken out of the map while it is pressed, and made only if // the strip turns out to reach it. let mut held: Option = None; + // Whether the square was in the map already, and whether this changed it: a + // square is counted changed, and copied again, only when its bytes are. + let mut existed = false; + let mut dirty = false; let rows = j0.max(tile_j * side_cells)..=j1.min(tile_j * side_cells + side_cells - 1); for j in rows { @@ -399,58 +422,71 @@ impl Ruts { } let cell = Self::cell_at(i, j).1; let tile = held.get_or_insert_with(|| { - self.tiles.remove(&key).unwrap_or_else(|| Tile::new(clock)) + let kept = self.tiles.remove(&key); + existed = kept.is_some(); + kept.unwrap_or_else(|| Tile::new(clock)) }); - let before = tile.height(cell); - let mut after = before; - if target < 0.0 { - after = before.min(target); - } else if target > 0.0 { - after = before.max((before + target).min(target)); - } - if after != before { - tile.set_height(cell, after); - } - // What the tyre reaches takes its print and its wet: the floor - // where the tread stands on it, and the berm it heaped. - let touched = if under { - target <= before + 0.003 - } else { - after != before - }; - if !touched { - continue; - } - let layers = &mut tile.layers; - layers[1][cell * 4 + 3] = 255; - if wet > layers[0][cell * 4 + 3] { - layers[0][cell * 4 + 3] = wet; - tile.damp = true; - } - tile.stays[cell] = tile.stays[cell].max(stays); - // Soil shows where the ground was broken: by how deep, a tyre's - // print in dust being soil too. - let broken = churn * (0.35 + 0.65 * smoothstep(0.0, 0.03, depth * weight)); - layers[1][cell * 4 + 2] = layers[1][cell * 4 + 2].max(byte(broken)); - // The stretch this step newly rolled over takes the tread's print. - if under && beyond <= 0.0 { - let phase = press.phase.0 + (press.phase.1 - press.phase.0) * passed; - // Crisp under the tread, gone at its shoulders. - let crisp = - print * (1.0 - smoothstep(0.8, 1.0, t.abs() / press.half_width)); - layers[1][cell * 4] = byte(0.5 + 0.5 * crisp * phase.cos()); - layers[1][cell * 4 + 1] = byte(0.5 + 0.5 * crisp * phase.sin()); - layers[0][cell * 4 + 2] = byte(0.5 + 0.5 * t / ACROSS_REACH); + let was = tile.cell_bytes(cell); + 'cell: { + let before = tile.height(cell); + let mut after = before; + if target < 0.0 { + after = before.min(target); + } else if target > 0.0 { + after = before.max((before + target).min(target)); + } + if after != before { + tile.set_height(cell, after); + } + // What the tyre reaches takes its print and its wet: the floor + // where the tread stands on it, and the berm it heaped. + let touched = if under { + target <= before + 0.003 + } else { + after != before + }; + if !touched { + break 'cell; + } + let layers = &mut tile.layers; + layers[1][cell * 4 + 3] = 255; + if wet > layers[0][cell * 4 + 3] { + layers[0][cell * 4 + 3] = wet; + tile.damp = true; + } + tile.stays[cell] = tile.stays[cell].max(stays); + // Soil shows where the ground was broken: by how deep, a tyre's + // print in dust being soil too. + let broken = + churn * (0.35 + 0.65 * smoothstep(0.0, 0.03, depth * weight)); + layers[1][cell * 4 + 2] = layers[1][cell * 4 + 2].max(byte(broken)); + // The stretch this step newly rolled over takes the tread's print. + if under && beyond <= 0.0 { + let phase = + press.phase.0 + (press.phase.1 - press.phase.0) * passed; + // Crisp under the tread, gone at its shoulders. + let crisp = print + * (1.0 - smoothstep(0.8, 1.0, t.abs() / press.half_width)); + layers[1][cell * 4] = byte(0.5 + 0.5 * crisp * phase.cos()); + layers[1][cell * 4 + 1] = byte(0.5 + 0.5 * crisp * phase.sin()); + layers[0][cell * 4 + 2] = byte(0.5 + 0.5 * t / ACROSS_REACH); + } } + dirty |= tile.cell_bytes(cell) != was; } } if let Some(mut tile) = held { - tile.version = tile.version.wrapping_add(1).max(1); - if !tile.listed { - tile.listed = true; - self.changed.push(key); + if dirty { + tile.version = tile.version.wrapping_add(1).max(1); + if !tile.listed { + tile.listed = true; + self.changed.push(key); + } + } + // A square made for a strip that changed nothing is not kept. + if dirty || existed { + self.tiles.insert(key, tile); } - self.tiles.insert(key, tile); } } } @@ -826,6 +862,26 @@ mod tests { assert_eq!(tracked.wet(1.0, 1.0), 0.0); } + /// A car standing still presses the same strip each step: once it has settled (the + /// second press wets the tread's edge the first heaped), that changes no byte, so no + /// square is counted changed and none is copied to the GPU again. + #[test] + fn pressing_what_is_already_pressed_changes_nothing() { + let mut ruts = Ruts::new(); + let press = rolled(0.1, 0.0, 2.0); + ruts.press(&press); + ruts.press(&press); + let changed = ruts.take_changed(); + assert!(!changed.is_empty()); + let versions: Vec = changed.iter().map(|&tile| ruts.version(tile)).collect(); + for _ in 0..3 { + ruts.press(&press); + } + assert!(ruts.take_changed().is_empty()); + let after: Vec = changed.iter().map(|&tile| ruts.version(tile)).collect(); + assert_eq!(after, versions); + } + #[test] fn changed_squares_are_listed_once_and_counted() { let mut ruts = Ruts::new(); From d1bea3d4eacd82beee717a956a94bf2925fd5566 Mon Sep 17 00:00:00 2001 From: SamG-Coder <13449963+SamG-Coder@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:15:30 +1100 Subject: [PATCH 3/3] The streamed importer makes glass by the same rule: blended, with a see-through colour Co-Authored-By: Claude Opus 5.5 --- crates/solstice-import/src/material.rs | 2 +- crates/solstice-import/src/streamed.rs | 2 +- crates/solstice-import/src/tests.rs | 7 +++++++ 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/solstice-import/src/material.rs b/crates/solstice-import/src/material.rs index dd1ecf4..22a0fd8 100644 --- a/crates/solstice-import/src/material.rs +++ b/crates/solstice-import/src/material.rs @@ -502,7 +502,7 @@ fn texel(image: &ImageData, x: i64, y: i64) -> [f32; 4] { /// Whether a material is glass: blended, and seen through by its colour's own alpha. Glass is /// drawn as a share of its pixels, by that alpha alone, so a blended material whose colour is /// opaque stays opaque, as it was before glass, and keeps off the masked path it would not use. -fn is_glass(material: &gltf::Material<'_>) -> bool { +pub(crate) fn is_glass(material: &gltf::Material<'_>) -> bool { material.alpha_mode() == gltf::material::AlphaMode::Blend && material.pbr_metallic_roughness().base_color_factor()[3] < 1.0 } diff --git a/crates/solstice-import/src/streamed.rs b/crates/solstice-import/src/streamed.rs index e04a9e8..a66f74b 100644 --- a/crates/solstice-import/src/streamed.rs +++ b/crates/solstice-import/src/streamed.rs @@ -1172,7 +1172,7 @@ fn convert_material( 0 } | if masked { Material::MASKED } else { 0 } - | if source.alpha_mode() == gltf::material::AlphaMode::Blend { + | if crate::material::is_glass(&source) { Material::GLASS } else { 0 diff --git a/crates/solstice-import/src/tests.rs b/crates/solstice-import/src/tests.rs index 7e3e5db..d0a42fa 100644 --- a/crates/solstice-import/src/tests.rs +++ b/crates/solstice-import/src/tests.rs @@ -468,6 +468,13 @@ fn a_blended_material_with_an_opaque_colour_is_not_glass() { let imported = import(&path); assert_eq!(imported.scene.materials[0].flags & Material::GLASS, 0); assert!(imported.warnings.iter().any(|w| w.contains("Blend"))); + // The streamed importer agrees. + let output = dir.0.join("out.solstice"); + streamed::bake_large(&path, &output, &large_options()).unwrap(); + let scene = solstice_asset::file::decode(&std::fs::read(&output).unwrap()) + .unwrap() + .scene; + assert_eq!(scene.materials[0].flags & Material::GLASS, 0); } /// Writes a model with two images, each a flat 2x2 colour, and the given materials over them,