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
53 changes: 50 additions & 3 deletions native/shared/src/compressed_texture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,15 @@ impl CompressedImage {
/// Parse a KTX2 file. `None` for anything that is not a plain 2D ASTC or
/// BC7 texture without supercompression, or whose levels are truncated.
pub fn from_ktx2(bytes: &[u8]) -> Option<Self> {
Self::from_ktx2_from(bytes, 0)
}

/// As [`Self::from_ktx2`], but only the levels from `first_level` down are
/// copied: the image is the same texture with its largest levels left
/// out (`width`, `height` those of `first_level`, clamped to the last
/// level). Every level is still checked. `u32::MAX` copies none and keeps
/// the full size: the shape only, with one empty level per level.
pub fn from_ktx2_from(bytes: &[u8], first_level: u32) -> Option<Self> {
if !is_ktx2(bytes) {
return None;
}
Expand All @@ -173,6 +182,8 @@ impl CompressedImage {
if supercompression != 0 || level_count > u32::BITS - width.max(height).leading_zeros() {
return None;
}
let shape_only = first_level == u32::MAX;
let first = (first_level as usize).min(level_count as usize - 1);
let mut levels = Vec::with_capacity(level_count as usize);
for index in 0..level_count as usize {
let entry = 80 + index * 24;
Expand All @@ -182,12 +193,26 @@ impl CompressedImage {
if length != format.level_bytes(level_width, level_height) {
return None;
}
levels.push(bytes.get(offset..offset.checked_add(length)?)?.to_vec());
let level = bytes.get(offset..offset.checked_add(length)?)?;
if shape_only {
levels.push(Vec::new());
} else if index >= first {
levels.push(level.to_vec());
}
}
if shape_only {
return Some(Self {
format,
width,
height,
srgb,
levels,
});
}
Some(Self {
format,
width,
height,
width: (width >> first).max(1),
height: (height >> first).max(1),
srgb,
levels,
})
Expand Down Expand Up @@ -363,6 +388,28 @@ mod tests {
}
}

#[test]
fn reading_from_a_level_equals_trimming_the_whole_read() {
let format = BlockFormat::Astc {
width: 4,
height: 4,
};
let image = sample(format, true);
let bytes = image.to_ktx2().expect("serialises");
let whole = CompressedImage::from_ktx2(&bytes).expect("parses");
for level in 0..whole.levels.len() as u32 + 2 {
let part = CompressedImage::from_ktx2_from(&bytes, level).expect("parses");
let trimmed = crate::renderer::texture_streaming::sub_image(&whole, level);
assert_eq!((part.width, part.height), (trimmed.width, trimmed.height));
assert_eq!(part.levels, trimmed.levels, "level {level}");
}
let shape = CompressedImage::from_ktx2_from(&bytes, u32::MAX).expect("parses");
assert_eq!((shape.width, shape.height), (whole.width, whole.height));
assert_eq!(shape.levels.len(), whole.levels.len());
assert!(shape.levels.iter().all(Vec::is_empty));
assert!(CompressedImage::from_ktx2_from(&bytes[..bytes.len() - 1], 3).is_none());
}

#[test]
fn truncated_or_foreign_files_are_rejected() {
let bytes = sample(
Expand Down
4 changes: 3 additions & 1 deletion native/shared/src/ffi_core/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ macro_rules! __bloom_ffi_models {
let path = $crate::string_header::str_from_header(path_ptr);
let resolved =bloom_resolve_asset_path(path);
let resolved_path = std::path::Path::new(resolved.as_ref());
match std::fs::read(resolved_path) {
// mapped, not read: only the pages the load touches come in from disk
// SAFETY: an asset file, not rewritten while one model loads from it.
match unsafe { $crate::file_map::read(resolved_path) } {
Ok(data) => {
let eng = engine();
let $crate::engine::EngineState { ref mut models, ref mut renderer, .. } = *eng;
Expand Down
110 changes: 110 additions & 0 deletions native/shared/src/file_map.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
//! A file's bytes for loading, memory-mapped where the platform allows.
//!
//! A model file is mostly texture levels, and with texture streaming on most
//! of those are never uploaded (only the small levels are, the rest is read
//! later and only when needed). Reading the whole file brought every byte in
//! from disk and held it in memory for the load. A read-only mapping brings
//! in only the pages the loader touches, and those are clean file pages:
//! iOS does not count them against the app's memory limit.
//!
//! The mapping lives as long as the `FileBytes` (the load), so a file must not
//! be truncated while it is being loaded (reading past its new end would
//! fault). Elsewhere (Windows, the web) the file is read whole as before.

use std::ops::Deref;
use std::path::Path;

/// The bytes of a file (see [`read`]). The mapping is private to this module.
pub struct FileBytes(Inner);

enum Inner {
#[cfg(unix)]
Mapped {
ptr: *const u8,
len: usize,
},
Owned(Vec<u8>),
}

impl Deref for FileBytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
match &self.0 {
#[cfg(unix)]
Inner::Mapped { ptr, len } => {
// SAFETY: ptr/len describe a live read-only mapping owned by self.
unsafe { std::slice::from_raw_parts(*ptr, *len) }
}
Inner::Owned(bytes) => bytes,
}
}
}

impl Drop for FileBytes {
fn drop(&mut self) {
#[cfg(unix)]
if let Inner::Mapped { ptr, len } = self.0 {
// SAFETY: the mapping was made by `read` with this address and length.
unsafe {
libc::munmap(ptr as *mut libc::c_void, len);
}
}
}
}

/// The bytes of the file at `path`: mapped on Unix-like systems (falling back
/// to a read when the mapping fails), read whole elsewhere.
///
/// # Safety
///
/// While the returned `FileBytes` lives, the file must not be truncated or
/// rewritten by anyone: a mapping is not a snapshot, and reading a page past
/// a new end of file faults. Engine loads hold it only for the load of one
/// model from the game's own assets.
pub unsafe fn read(path: &Path) -> std::io::Result<FileBytes> {
#[cfg(unix)]
{
use std::os::unix::io::AsRawFd;
let file = std::fs::File::open(path)?;
let len = file.metadata()?.len() as usize;
if len > 0 {
// SAFETY: a private read-only mapping of an open file; the fd may be
// closed afterwards, the mapping keeps the file.
let ptr = unsafe {
libc::mmap(
std::ptr::null_mut(),
len,
libc::PROT_READ,
libc::MAP_PRIVATE,
file.as_raw_fd(),
0,
)
};
if ptr != libc::MAP_FAILED {
return Ok(FileBytes(Inner::Mapped {
ptr: ptr as *const u8,
len,
}));
}
}
}
std::fs::read(path).map(|bytes| FileBytes(Inner::Owned(bytes)))
}

#[cfg(test)]
mod tests {
#[test]
fn a_mapped_file_reads_as_its_bytes() {
let dir = std::env::temp_dir().join(format!("bloom-file-map-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("bytes.bin");
let bytes: Vec<u8> = (0..100_000u32).map(|i| (i * 31 % 251) as u8).collect();
std::fs::write(&path, &bytes).unwrap();
// SAFETY (all three): the test's own files, not changed while mapped.
assert_eq!(&*unsafe { super::read(&path) }.unwrap(), &bytes[..]);
std::fs::write(&path, b"").unwrap();
assert!(unsafe { super::read(&path) }.unwrap().is_empty());
assert!(unsafe { super::read(&dir.join("missing")) }.is_err());
let _ = std::fs::remove_dir_all(&dir);
}
}
1 change: 1 addition & 0 deletions native/shared/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub mod emoji;
pub mod ffi;
#[cfg(not(target_arch = "wasm32"))]
pub mod ffi_core;
pub mod file_map;
pub mod handles;
pub mod input;
pub mod locale;
Expand Down
47 changes: 26 additions & 21 deletions native/shared/src/models_gltf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//! animation update, procedural mesh gen) stays in `models.rs`.

use super::*;
use std::borrow::Cow;

#[path = "models_gltf_layered_pbr.rs"]
mod layered_pbr_import;
Expand Down Expand Up @@ -98,7 +99,7 @@ fn walk_scene_collect_instances(

fn read_accessor_f32(
_gltf: &gltf::Gltf,
buffer_data: &[Vec<u8>],
buffer_data: &[Cow<[u8]>],
accessor: &gltf::Accessor,
) -> Vec<f32> {
let view = match accessor.view() {
Expand Down Expand Up @@ -148,17 +149,21 @@ fn read_accessor_f32(
/// of a load). Inline base64 buffers are decoded; an external `.bin` next to
/// the file is read from `base_dir` (with `strict`, a missing one fails the
/// load; otherwise it is an empty buffer).
fn take_buffers(
fn take_buffers<'a>(
gltf: &mut gltf::Gltf,
glb_bin: Option<&'a [u8]>,
base_dir: Option<&std::path::Path>,
strict: bool,
) -> Option<Vec<Vec<u8>>> {
let mut bin = gltf.blob.take();
let mut buffer_data: Vec<Vec<u8>> = Vec::new();
) -> Option<Vec<Cow<'a, [u8]>>> {
let mut bin: Option<Cow<'a, [u8]>> = match glb_bin {
Some(b) => Some(Cow::Borrowed(b)),
None => gltf.blob.take().map(Cow::Owned),
};
let mut buffer_data: Vec<Cow<'a, [u8]>> = Vec::new();
for buffer in gltf.buffers() {
let bytes = match buffer.source() {
let bytes: Cow<'a, [u8]> = match buffer.source() {
gltf::buffer::Source::Bin => bin.take().unwrap_or_default(),
gltf::buffer::Source::Uri(uri) => {
gltf::buffer::Source::Uri(uri) => Cow::Owned({
if let Some(encoded) = uri.strip_prefix("data:application/octet-stream;base64,") {
let mut decoded = Vec::new();
let _ = base64_decode(encoded, &mut decoded);
Expand All @@ -172,16 +177,16 @@ fn take_buffers(
} else {
Vec::new()
}
}
}),
};
buffer_data.push(bytes);
}
Some(buffer_data)
}

pub fn load_gltf_animation(data: &[u8]) -> Option<ModelAnimation> {
let mut gltf = parse::parse_gltf(data)?;
let buffer_data = take_buffers(&mut gltf, None, false)?;
let (mut gltf, glb_bin) = parse::parse_borrowed(data)?;
let buffer_data = take_buffers(&mut gltf, glb_bin, None, false)?;
animation_from(&gltf, &buffer_data)
}

Expand All @@ -195,7 +200,7 @@ pub fn load_gltf_animation_file(path: &std::path::Path) -> Option<ModelAnimation
load_gltf_animation(&std::fs::read(path).ok()?)
}

fn animation_from(gltf: &gltf::Gltf, buffer_data: &[Vec<u8>]) -> Option<ModelAnimation> {
fn animation_from(gltf: &gltf::Gltf, buffer_data: &[Cow<[u8]>]) -> Option<ModelAnimation> {
// Parse skeleton from the first skin
let skeleton = if let Some(skin) = gltf.skins().next() {
let joints_nodes: Vec<_> = skin.joints().collect();
Expand Down Expand Up @@ -360,7 +365,7 @@ fn animation_from(gltf: &gltf::Gltf, buffer_data: &[Vec<u8>]) -> Option<ModelAni
}
}
for channel in anim.channels() {
let buffers = |b: gltf::Buffer| buffer_data.get(b.index()).map(|d| d.as_slice());
let buffers = |b: gltf::Buffer| buffer_data.get(b.index()).map(|d| d.as_ref());
if let Some(track) = morph::read_weight_channel(&channel, buffers, &morph_slots) {
duration = duration.max(track.times.last().copied().unwrap_or(0.0));
morph_tracks.push(track);
Expand Down Expand Up @@ -515,11 +520,11 @@ pub(super) fn load_gltf_with_textures(
base_dir: Option<&std::path::Path>,
source_label: Option<&str>,
) -> Option<ModelData> {
let mut gltf = parse::parse_gltf(data)?;
let (mut gltf, glb_bin) = parse::parse_borrowed(data)?;
emit_unsupported_material_extension_diagnostics(&gltf, source_label.unwrap_or("<memory glTF>"));

// Get buffer data
let buffer_data = take_buffers(&mut gltf, base_dir, false)?;
let buffer_data = take_buffers(&mut gltf, glb_bin, base_dir, false)?;
let source_geometry_sha256 = complete_geometry_source_hash(data, &gltf, &buffer_data);

// Pre-walk materials to identify which image indices are normal
Expand Down Expand Up @@ -791,7 +796,7 @@ pub(super) fn load_gltf_with_textures(
continue;
}
let reader =
primitive.reader(|buf| buffer_data.get(buf.index()).map(|d| d.as_slice()));
primitive.reader(|buf| buffer_data.get(buf.index()).map(|d| d.as_ref()));
let positions: Vec<[f32; 3]> = match reader.read_positions() {
Some(iter) => iter.collect(),
None => continue,
Expand Down Expand Up @@ -1072,10 +1077,10 @@ fn load_gltf_staged_impl(
) -> Option<crate::staging::StagedModel> {
use crate::staging::{StagedModel, StagedTexture};

let mut gltf = parse::parse_gltf(data)?;
let (mut gltf, glb_bin) = parse::parse_borrowed(data)?;
emit_unsupported_material_extension_diagnostics(&gltf, source_label);

let buffer_data = take_buffers(&mut gltf, base_dir, true)?;
let buffer_data = take_buffers(&mut gltf, glb_bin, base_dir, true)?;
let source_geometry_sha256 = complete_geometry_source_hash(data, &gltf, &buffer_data);

// Pre-walk materials for the image indices used as normal maps — they
Expand Down Expand Up @@ -1222,7 +1227,7 @@ fn load_gltf_staged_impl(
let morph_slots = morph::morph_slots(&gltf);
for mesh in gltf.meshes() {
for primitive in mesh.primitives() {
let reader = primitive.reader(|buf| buffer_data.get(buf.index()).map(|d| d.as_slice()));
let reader = primitive.reader(|buf| buffer_data.get(buf.index()).map(|d| d.as_ref()));
let positions: Vec<[f32; 3]> = match reader.read_positions() {
Some(iter) => iter.collect(),
None => continue,
Expand Down Expand Up @@ -1508,11 +1513,11 @@ fn stage_image_variants(
}

pub(super) fn load_gltf(data: &[u8]) -> Option<ModelData> {
let mut gltf = parse::parse_gltf(data)?;
let (mut gltf, glb_bin) = parse::parse_borrowed(data)?;
emit_unsupported_material_extension_diagnostics(&gltf, "<memory glTF>");

// Get buffer data (for .glb, embedded; for .gltf, inline base64)
let buffer_data = take_buffers(&mut gltf, None, false)?;
let buffer_data = take_buffers(&mut gltf, glb_bin, None, false)?;
let source_geometry_sha256 = complete_geometry_source_hash(data, &gltf, &buffer_data);

let mut source_meshes: Vec<Vec<(u32, MeshData)>> =
Expand All @@ -1521,7 +1526,7 @@ pub(super) fn load_gltf(data: &[u8]) -> Option<ModelData> {
let morph_slots = morph::morph_slots(&gltf);
for mesh in gltf.meshes() {
for primitive in mesh.primitives() {
let reader = primitive.reader(|buf| buffer_data.get(buf.index()).map(|d| d.as_slice()));
let reader = primitive.reader(|buf| buffer_data.get(buf.index()).map(|d| d.as_ref()));

let positions: Vec<[f32; 3]> = match reader.read_positions() {
Some(iter) => iter.collect(),
Expand Down
6 changes: 5 additions & 1 deletion native/shared/src/models_gltf_anim_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,11 @@ pub(super) fn load(path: &Path) -> Option<Option<ModelAnimation>> {
f.seek(SeekFrom::Start(bin_off + o as u64)).ok()?;
f.read_exact(&mut bin[o..o + l]).ok()?;
}
let buffer_data = if bin_len > 0 { vec![bin] } else { Vec::new() };
let buffer_data = if bin_len > 0 {
vec![std::borrow::Cow::Owned(bin)]
} else {
Vec::new()
};
Some(super::animation_from(&gltf, &buffer_data))
}

Expand Down
4 changes: 2 additions & 2 deletions native/shared/src/models_gltf_bake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub fn require_source_geometry_hash() {
pub(super) fn complete_geometry_source_hash(
source_bytes: &[u8],
gltf: &gltf::Gltf,
buffers: &[Vec<u8>],
buffers: &[std::borrow::Cow<[u8]>],
) -> Option<[u8; 32]> {
if !cfg!(test)
&& !SOURCE_HASH_REQUIRED.load(std::sync::atomic::Ordering::Relaxed)
Expand All @@ -41,7 +41,7 @@ pub(super) fn complete_geometry_source_hash(
{
return None;
}
let slices = buffers.iter().map(Vec::as_slice).collect::<Vec<&[u8]>>();
let slices = buffers.iter().map(|b| b.as_ref()).collect::<Vec<&[u8]>>();
Some(bloom_geometry_format::geometry_source_sha256(
source_bytes,
&slices,
Expand Down
Loading
Loading