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
8 changes: 4 additions & 4 deletions native/shared/src/audio/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@ pub fn parse_wav(data: &[u8]) -> Option<SoundData> {
let samples = match bits_per_sample {
16 => pcm_data
.chunks_exact(2)
.map(|chunk| i16::from_le_bytes([chunk[0], chunk[1]]) as f32 / 32768.0)
.map(|chunk| i16::from_le_bytes([chunk[0], chunk[1]]))
.collect(),
8 => pcm_data
.iter()
.map(|&b| (b as f32 - 128.0) / 128.0)
.map(|&b| (i16::from(b) - 128) << 8)
.collect(),
_ => return None,
};
Expand Down Expand Up @@ -67,7 +67,7 @@ pub fn parse_mp3(data: &[u8]) -> Option<SoundData> {
channels = frame.channels as u16;
}
for &s in &frame.data {
samples.push(s as f32 / 32768.0);
samples.push(s);
}
}
Err(minimp3::Error::Eof) => break,
Expand Down Expand Up @@ -95,7 +95,7 @@ pub fn parse_ogg(data: &[u8]) -> Option<SoundData> {

while let Ok(Some(packet)) = reader.read_dec_packet_itl() {
for &sample in &packet {
samples.push(sample as f32 / 32768.0);
samples.push(sample);
}
}

Expand Down
6 changes: 5 additions & 1 deletion native/shared/src/audio/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,11 @@ mod tests {
let n = (seconds * SR) as usize;
SoundData {
samples: (0..n)
.map(|i| 0.5 * (2.0 * std::f32::consts::PI * freq * i as f32 / SR).sin())
.map(|i| {
crate::audio::pcm16(
0.5 * (2.0 * std::f32::consts::PI * freq * i as f32 / SR).sin(),
)
})
.collect(),
sample_rate: SR as u32,
channels: 1,
Expand Down
25 changes: 21 additions & 4 deletions native/shared/src/audio/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,29 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;

/// A loaded sound effect or music track (PCM samples).
///
/// Kept as 16-bit integers: every decoder (WAV 8/16-bit, MP3, Vorbis)
/// produces 16-bit samples, so this is lossless and half the memory of
/// `f32` (a game's effects held about 95 MB as floats).
pub struct SoundData {
pub samples: Vec<f32>,
pub samples: Vec<i16>,
pub sample_rate: u32,
pub channels: u16,
}

impl SoundData {
/// Sample `i` in [-1, 1).
#[inline]
pub fn sample(&self, i: usize) -> f32 {
f32::from(self.samples[i]) * (1.0 / 32768.0)
}
}

/// A float sample in [-1, 1] as 16-bit PCM (tests and generated sounds).
pub fn pcm16(x: f32) -> i16 {
(x * 32768.0).round().clamp(-32768.0, 32767.0) as i16
}

/// Render-side playback state readable from the control side.
pub struct MusicShared {
pub playing: AtomicBool,
Expand Down Expand Up @@ -702,7 +719,7 @@ mod tests {
fn tone(len: usize) -> SoundData {
SoundData {
samples: (0..len)
.map(|i| if i % 2 == 0 { 0.5 } else { -0.5 })
.map(|i| if i % 2 == 0 { pcm16(0.5) } else { pcm16(-0.5) })
.collect(),
sample_rate: 44_100,
channels: 1,
Expand Down Expand Up @@ -1053,7 +1070,7 @@ mod tests {
/// All-0.5 mono signal: peaks read gains directly.
fn flat(len: usize) -> SoundData {
SoundData {
samples: vec![0.5; len],
samples: vec![pcm16(0.5); len],
sample_rate: 44_100,
channels: 1,
}
Expand All @@ -1062,7 +1079,7 @@ mod tests {
fn sine(freq: f32, len: usize) -> SoundData {
SoundData {
samples: (0..len)
.map(|i| (2.0 * std::f32::consts::PI * freq * i as f32 / 44_100.0).sin())
.map(|i| pcm16((2.0 * std::f32::consts::PI * freq * i as f32 / 44_100.0).sin()))
.collect(),
sample_rate: 44_100,
channels: 1,
Expand Down
10 changes: 5 additions & 5 deletions native/shared/src/audio/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,10 +311,10 @@ impl Voice {
#[inline]
fn frame(&self, idx: usize) -> (f32, f32) {
if self.data.channels <= 1 {
let s = self.data.samples[idx];
let s = self.data.sample(idx);
(s, s)
} else {
(self.data.samples[idx * 2], self.data.samples[idx * 2 + 1])
(self.data.sample(idx * 2), self.data.sample(idx * 2 + 1))
}
}
}
Expand Down Expand Up @@ -1081,7 +1081,7 @@ impl AudioRenderer {
while i < output.len() && *position < data.samples.len() {
if data.channels == 1 {
let sample =
filt(i, data.samples[*position]) * (g0 + dg * (i / 2) as f32);
filt(i, data.sample(*position)) * (g0 + dg * (i / 2) as f32);
output[i] += sample;
if i + 1 < output.len() {
output[i + 1] += sample;
Expand All @@ -1090,7 +1090,7 @@ impl AudioRenderer {
i += 2;
} else {
output[i] +=
filt(i, data.samples[*position]) * (g0 + dg * (i / 2) as f32);
filt(i, data.sample(*position)) * (g0 + dg * (i / 2) as f32);
*position += 1;
i += 1;
}
Expand Down Expand Up @@ -1177,7 +1177,7 @@ mod tests {

fn dummy_sound() -> Arc<SoundData> {
Arc::new(SoundData {
samples: vec![0.0; 16],
samples: vec![0; 16],
sample_rate: 44_100,
channels: 1,
})
Expand Down
5 changes: 1 addition & 4 deletions native/shared/src/ffi_core/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -640,10 +640,7 @@ macro_rules! __bloom_ffi_models {
$crate::ffi::guard("bloom_load_model_animation", move || {
let path = $crate::string_header::str_from_header(path_ptr);
let path: &str = &bloom_resolve_asset_path(path);
match std::fs::read(path) {
Ok(data) => engine().models.load_model_animation(&data),
Err(_) => 0.0,
}
engine().models.load_model_animation_file(std::path::Path::new(path))
})
}
#[cfg(not(feature = "models3d"))]
Expand Down
13 changes: 11 additions & 2 deletions native/shared/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -552,8 +552,8 @@ pub use crate::anim_mixer::AnimMixer;
mod gltf_load;
#[cfg(feature = "models3d")]
pub use gltf_load::{
load_gltf_animation, load_gltf_staged, load_gltf_staged_from_source_path,
require_source_geometry_hash,
load_gltf_animation, load_gltf_animation_file, load_gltf_staged,
load_gltf_staged_from_source_path, require_source_geometry_hash,
};

pub struct ModelAnimation {
Expand Down Expand Up @@ -1210,6 +1210,15 @@ impl ModelManager {
}
}

/// As `load_model_animation`, reading only what the clips need from the file.
#[cfg(feature = "models3d")]
pub fn load_model_animation_file(&mut self, path: &std::path::Path) -> f64 {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
match gltf_load::load_gltf_animation_file(path) {
Some(anim) => self.animations.alloc(anim),
None => 0.0,
}
}

/// EN-055 — a new animation INSTANCE over an already-loaded clip set.
/// The parsed data (skeleton, keyframe tracks, rest rotations) is shared
/// via `Arc`; the mixer, joint matrices and mask cache are fresh — so N
Expand Down
133 changes: 50 additions & 83 deletions native/shared/src/models_gltf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ use material_import::{
apply_transmission_hack, emit_unsupported_material_extension_diagnostics,
transmission_from_material,
};
#[path = "models_gltf_anim_file.rs"]
mod anim_file;
#[path = "models_gltf_bake.rs"]
mod bake;
#[path = "models_gltf_morph.rs"]
Expand Down Expand Up @@ -141,30 +143,59 @@ fn read_accessor_f32(
result
}

pub fn load_gltf_animation(data: &[u8]) -> Option<ModelAnimation> {
let gltf = parse::parse_gltf(data)?;

// Get buffer data
/// The glTF's buffers, in order. The GLB binary chunk is moved out of the
/// parsed file, not cloned (a clone was a third copy of the file at the peak
/// 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(
gltf: &mut gltf::Gltf,
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();
for buffer in gltf.buffers() {
match buffer.source() {
gltf::buffer::Source::Bin => {
if let Some(blob) = gltf.blob.as_ref() {
buffer_data.push(blob.clone());
}
}
let bytes = match buffer.source() {
gltf::buffer::Source::Bin => bin.take().unwrap_or_default(),
gltf::buffer::Source::Uri(uri) => {
if let Some(encoded) = uri.strip_prefix("data:application/octet-stream;base64,") {
let mut decoded = Vec::new();
let _ = base64_decode(encoded, &mut decoded);
buffer_data.push(decoded);
decoded
} else if let Some(dir) = base_dir {
match std::fs::read(dir.join(uri)) {
Ok(bytes) => bytes,
Err(_) if strict => return None,
Err(_) => Vec::new(),
}
} else {
buffer_data.push(Vec::new());
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)?;
animation_from(&gltf, &buffer_data)
}

/// A GLB's skeleton and clips read from the file itself: the JSON and only the
/// byte ranges the skin and the animations use (models_gltf_anim_file.rs).
/// Anything that does not handle falls back to reading the whole file.
pub fn load_gltf_animation_file(path: &std::path::Path) -> Option<ModelAnimation> {
if let Some(anim) = anim_file::load(path) {
return anim;
}
load_gltf_animation(&std::fs::read(path).ok()?)
}

fn animation_from(gltf: &gltf::Gltf, buffer_data: &[Vec<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 @@ -484,36 +515,11 @@ pub(super) fn load_gltf_with_textures(
base_dir: Option<&std::path::Path>,
source_label: Option<&str>,
) -> Option<ModelData> {
let gltf = parse::parse_gltf(data)?;
let mut gltf = parse::parse_gltf(data)?;
emit_unsupported_material_extension_diagnostics(&gltf, source_label.unwrap_or("<memory glTF>"));

// Get buffer data
let mut buffer_data: Vec<Vec<u8>> = Vec::new();
for buffer in gltf.buffers() {
match buffer.source() {
gltf::buffer::Source::Bin => {
if let Some(blob) = gltf.blob.as_ref() {
buffer_data.push(blob.clone());
}
}
gltf::buffer::Source::Uri(uri) => {
if let Some(encoded) = uri.strip_prefix("data:application/octet-stream;base64,") {
let mut decoded = Vec::new();
let _ = base64_decode(encoded, &mut decoded);
buffer_data.push(decoded);
} else if let Some(dir) = base_dir {
// External .bin file alongside the .gltf.
let path = dir.join(uri);
match std::fs::read(&path) {
Ok(bytes) => buffer_data.push(bytes),
Err(_) => buffer_data.push(Vec::new()),
}
} else {
buffer_data.push(Vec::new());
}
}
}
}
let buffer_data = take_buffers(&mut gltf, 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 @@ -1066,30 +1072,10 @@ fn load_gltf_staged_impl(
) -> Option<crate::staging::StagedModel> {
use crate::staging::{StagedModel, StagedTexture};

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

let mut buffer_data: Vec<Vec<u8>> = Vec::new();
for buffer in gltf.buffers() {
match buffer.source() {
gltf::buffer::Source::Bin => {
if let Some(blob) = gltf.blob.as_ref() {
buffer_data.push(blob.clone());
}
}
gltf::buffer::Source::Uri(uri) => {
if let Some(encoded) = uri.strip_prefix("data:application/octet-stream;base64,") {
let mut decoded = Vec::new();
let _ = base64_decode(encoded, &mut decoded);
buffer_data.push(decoded);
} else if let Some(dir) = base_dir {
buffer_data.push(std::fs::read(dir.join(uri)).ok()?);
} else {
buffer_data.push(Vec::new());
}
}
}
}
let buffer_data = take_buffers(&mut gltf, 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 @@ -1522,30 +1508,11 @@ fn stage_image_variants(
}

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

// Get buffer data (for .glb, embedded; for .gltf, inline base64)
let mut buffer_data: Vec<Vec<u8>> = Vec::new();
for buffer in gltf.buffers() {
match buffer.source() {
gltf::buffer::Source::Bin => {
if let Some(blob) = gltf.blob.as_ref() {
buffer_data.push(blob.clone());
}
}
gltf::buffer::Source::Uri(uri) => {
if let Some(encoded) = uri.strip_prefix("data:application/octet-stream;base64,") {
// Try to decode base64 inline data
let mut decoded = Vec::new();
let _ = base64_decode(encoded, &mut decoded);
buffer_data.push(decoded);
} else {
buffer_data.push(Vec::new());
}
}
}
}
let buffer_data = take_buffers(&mut gltf, None, false)?;
let source_geometry_sha256 = complete_geometry_source_hash(data, &gltf, &buffer_data);

let mut source_meshes: Vec<Vec<(u32, MeshData)>> =
Expand Down
Loading
Loading