Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

114 changes: 114 additions & 0 deletions apps/bake/src/kit.rs
Original file line number Diff line number Diff line change
@@ -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::<String, String>(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(())
}
79 changes: 79 additions & 0 deletions apps/bake/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
mod collision_view;
mod forest;
mod gallery;
mod kit;
mod plants;
mod scene;

Expand Down Expand Up @@ -86,6 +87,8 @@ struct Options {
/// A character to check, and its rig's role file.
check_character: Option<PathBuf>,
roles: Option<PathBuf>,
/// A truck built of pieces to pack: its actor file (`kit.rs`).
kit: Option<PathBuf>,
}

/// Writes the file a browser reads for a scene too large for its memory: the manifest without
Expand Down Expand Up @@ -164,6 +167,7 @@ fn parse_args() -> Result<Options, String> {
large: Default::default(),
check_character: None,
roles: None,
kit: None,
};
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
Expand All @@ -182,6 +186,7 @@ fn parse_args() -> Result<Options, String> {
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()?)),
Expand Down Expand Up @@ -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<String, String> {
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() {
Expand All @@ -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());
Expand All @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions apps/viewer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
52 changes: 46 additions & 6 deletions apps/viewer/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,16 @@ mod native {
request: &StreamRequest,
) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
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 {
Expand Down Expand Up @@ -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<Source, Box<dyn std::error::Error>> {
let path = &options.scene;
let beside = path.with_file_name(solstice_viewer::shared::FILE);
let missing = |error: Box<dyn std::error::Error>| {
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<dyn std::error::Error>> {
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(());
Expand Down
Loading
Loading