use std::io::Write as _;
use flate2::Compression as GzLevel;
use flate2::write::GzEncoder;
use geolith::error::{GeolithError, Result};
use crate::splat::ply::SplatCloud;
const SPZ_MAGIC: u32 = 0x5053_474e;
const SPZ_STREAM_VERSION: u32 = 3;
const FRACTIONAL_BITS: u8 = 12;
const FIXED24_LIMIT: i32 = (1 << 23) - 1;
const HEADER_BYTES: usize = 16;
const COLOR_SCALE: f32 = 0.15;
const SCALE_LOG_MIN: f32 = -10.0;
const SCALE_LOG_QUANTIZATION: f32 = 16.0;
const SQRT_HALF: f32 = std::f32::consts::FRAC_1_SQRT_2;
const MAG_SCALE: f32 = 511.0;
#[must_use]
fn sigmoid(x: f32) -> f32 {
1.0 / (1.0 + (-x).exp())
}
#[must_use]
fn quantize_opacity(logit: f32) -> u8 {
let alpha = sigmoid(logit).clamp(0.0, 1.0);
f32::round(alpha * 255.0).clamp(0.0, 255.0) as u8
}
#[must_use]
fn quantize_color(coefficient: f32) -> u8 {
let scaled = coefficient * COLOR_SCALE * 255.0 + 0.5 * 255.0;
f32::round(scaled).clamp(0.0, 255.0) as u8
}
#[must_use]
fn quantize_scale(log_scale: f32) -> u8 {
let scaled = (log_scale - SCALE_LOG_MIN) * SCALE_LOG_QUANTIZATION;
f32::round(scaled).clamp(0.0, 255.0) as u8
}
#[must_use]
fn quantize_rest_sh(coefficient: f32) -> u8 {
f32::round(coefficient * 128.0 + 128.0).clamp(0.0, 255.0) as u8
}
fn quantize_position(local: f32) -> Result<[u8; 3]> {
let fixed = f32::round(local * f32::from(1_u16 << FRACTIONAL_BITS)) as i64;
if fixed.unsigned_abs() > FIXED24_LIMIT as u64 {
let limit = f64::from(FIXED24_LIMIT) / f64::from(1_u32 << FRACTIONAL_BITS);
return Err(GeolithError::SplatTiles(format!(
"tile-local coordinate {local} exceeds the SPZ 24-bit fixed-point range +/-{limit:.3}"
)));
}
let fixed = fixed as i32;
Ok([
(fixed & 0xFF) as u8,
((fixed >> 8) & 0xFF) as u8,
((fixed >> 16) & 0xFF) as u8,
])
}
#[must_use]
fn pack_quaternion_smallest_three(quaternion: [f32; 4]) -> [u8; 4] {
let [mut x, mut y, mut z, mut w] = quaternion;
let len2 = x * x + y * y + z * z + w * w;
if len2 < 1e-40 {
(x, y, z, w) = (0.0, 0.0, 0.0, 1.0);
} else {
let inv = 1.0 / len2.sqrt();
x *= inv;
y *= inv;
z *= inv;
w *= inv;
}
let components = [x, y, z, w];
let mut largest = 0_usize;
for index in 1..4 {
if components[index].abs() > components[largest].abs() {
largest = index;
}
}
let negate = components[largest] < 0.0;
let mut packed = largest as u32;
for (index, value) in components.iter().enumerate() {
if index == largest {
continue;
}
let neg_bit = u32::from((*value < 0.0) != negate);
let magnitude = (MAG_SCALE * (value.abs() / SQRT_HALF) + 0.5).floor();
let magnitude = (magnitude.clamp(0.0, MAG_SCALE)) as u32;
packed = (packed << 10) | (neg_bit << 9) | magnitude;
}
packed.to_le_bytes()
}
pub fn encode_spz(cloud: &SplatCloud, antialiased: bool) -> Result<Vec<u8>> {
let n = cloud.len();
if cloud.colors.len() != n
|| cloud.opacities.len() != n
|| cloud.scales.len() != n
|| cloud.rotations.len() != n
{
return Err(GeolithError::SplatTiles(format!(
"inconsistent splat attribute lengths: positions={n}, colors={}, \
opacities={}, scales={}, rotations={}",
cloud.colors.len(),
cloud.opacities.len(),
cloud.scales.len(),
cloud.rotations.len()
)));
}
if cloud.sh_degree > 3 {
return Err(GeolithError::SplatTiles(format!(
"SPZ supports spherical harmonic degree up to 3, got {}",
cloud.sh_degree
)));
}
let rest_per_channel = cloud.sh_rest_per_channel();
let rest_stride = rest_per_channel * 3;
if cloud.sh.len() != n * rest_stride {
return Err(GeolithError::SplatTiles(format!(
"spherical harmonic buffer has {} values, expected {}",
cloud.sh.len(),
n * rest_stride
)));
}
let mut packet = Vec::with_capacity(HEADER_BYTES + n * (9 + 1 + 3 + 3 + 4 + rest_stride));
packet.extend_from_slice(&SPZ_MAGIC.to_le_bytes());
packet.extend_from_slice(&SPZ_STREAM_VERSION.to_le_bytes());
packet.extend_from_slice(&(n as u32).to_le_bytes());
packet.push(cloud.sh_degree);
packet.push(FRACTIONAL_BITS);
packet.push(u8::from(antialiased));
packet.push(0);
for position in &cloud.positions {
for component in position {
packet.extend_from_slice(&quantize_position(*component)?);
}
}
for opacity in &cloud.opacities {
packet.push(quantize_opacity(*opacity));
}
for color in &cloud.colors {
for channel in color {
packet.push(quantize_color(*channel));
}
}
for scale in &cloud.scales {
for axis in scale {
packet.push(quantize_scale(*axis));
}
}
for rotation in &cloud.rotations {
packet.extend_from_slice(&pack_quaternion_smallest_three(*rotation));
}
for coefficient in &cloud.sh {
packet.push(quantize_rest_sh(*coefficient));
}
let mut encoder = GzEncoder::new(Vec::with_capacity(packet.len() / 2), GzLevel::new(6));
encoder.write_all(&packet)?;
Ok(encoder.finish()?)
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read as _;
fn unit_cloud(n: usize) -> SplatCloud {
SplatCloud {
positions: (0..n).map(|i| [i as f32 * 0.5, 1.0, -1.0]).collect(),
colors: vec![[0.5, -0.25, 1.0]; n],
opacities: vec![2.0; n],
scales: vec![[-3.0, -3.5, -4.0]; n],
rotations: vec![[0.0, 0.0, 0.0, 1.0]; n],
sh: Vec::new(),
sh_degree: 0,
vertical_axis: None,
}
}
fn gunzip(bytes: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
flate2::read::GzDecoder::new(bytes)
.read_to_end(&mut out)
.expect("valid gzip stream");
out
}
#[test]
fn header_matches_the_spz_contract() {
let packet = gunzip(&encode_spz(&unit_cloud(3), false).expect("encodes"));
assert_eq!(
u32::from_le_bytes(packet[0..4].try_into().expect("magic")),
SPZ_MAGIC,
"NGSP magic identifies the packet"
);
assert_eq!(
u32::from_le_bytes(packet[4..8].try_into().expect("version")),
3,
"spz_2 carries an SPZ stream version 3 packet"
);
assert_eq!(
u32::from_le_bytes(packet[8..12].try_into().expect("count")),
3
);
assert_eq!(packet[12], 0, "sh degree");
assert_eq!(packet[13], FRACTIONAL_BITS);
assert_eq!(packet[14], 0, "antialiased flag clear");
assert_eq!(packet[15], 0, "reserved byte");
}
#[test]
fn antialiased_flag_is_recorded() {
let packet = gunzip(&encode_spz(&unit_cloud(1), true).expect("encodes"));
assert_eq!(packet[14], 1);
}
#[test]
fn packet_length_grows_with_sh_degree() {
let plain = gunzip(&encode_spz(&unit_cloud(5), false).expect("encodes"));
assert_eq!(
plain.len(),
16 + 5 * (9 + 1 + 3 + 3 + 4),
"degree 0"
);
let mut cloud = unit_cloud(2);
cloud.sh_degree = 1;
cloud.sh = vec![0.25; 2 * 9];
let packet = gunzip(&encode_spz(&cloud, false).expect("encodes"));
let expected = 16 + 2 * (9 + 1 + 3 + 3 + 4 + 9);
assert_eq!(packet.len(), expected);
assert_eq!(packet[12], 1, "sh degree recorded in the header");
}
#[test]
fn positions_are_24bit_fixed_point() {
let mut cloud = unit_cloud(1);
cloud.positions[0] = [1.0, 0.0, -1.0];
let packet = gunzip(&encode_spz(&cloud, false).expect("encodes"));
let x = i32::from_le_bytes([packet[16], packet[17], packet[18], 0]);
assert_eq!(x, 1 << FRACTIONAL_BITS, "1.0 m maps to 4096 fixed units");
let y = i32::from_le_bytes([packet[19], packet[20], packet[21], 0]);
assert_eq!(y, 0);
let z_raw = i32::from_le_bytes([packet[22], packet[23], packet[24], 0]);
let z = (z_raw << 8) >> 8;
assert_eq!(
z,
-(1 << FRACTIONAL_BITS),
"negatives sign-extend correctly"
);
}
#[test]
fn positions_beyond_fixed_point_range_are_rejected() {
let mut cloud = unit_cloud(1);
cloud.positions[0] = [5000.0, 0.0, 0.0];
let err = encode_spz(&cloud, false).expect_err("out of range");
assert!(matches!(err, GeolithError::SplatTiles(_)), "{err}");
}
#[test]
fn opacity_passes_through_the_sigmoid() {
assert_eq!(quantize_opacity(0.0), 128, "logit 0 is alpha 0.5");
assert_eq!(quantize_opacity(-40.0), 0);
assert_eq!(quantize_opacity(40.0), 255);
}
#[test]
fn colour_quantisation_matches_the_reference_formula() {
assert_eq!(quantize_color(0.0), 128, "zero DC is mid grey");
assert_eq!(quantize_color(-100.0), 0, "clamps rather than wrapping");
assert_eq!(quantize_color(100.0), 255);
assert_eq!(quantize_color(1.0), 166);
}
#[test]
fn scale_quantisation_matches_the_reference_formula() {
assert_eq!(quantize_scale(SCALE_LOG_MIN), 0);
assert_eq!(quantize_scale(-9.0), 16, "one log unit is 16 steps");
assert_eq!(quantize_scale(100.0), 255, "clamps at the byte ceiling");
}
#[test]
fn rest_sh_quantisation_centres_on_128() {
assert_eq!(quantize_rest_sh(0.0), 128);
assert_eq!(quantize_rest_sh(1.0), 255);
assert_eq!(quantize_rest_sh(-1.0), 0);
}
#[test]
fn identity_quaternion_packs_with_w_as_largest() {
let packed = pack_quaternion_smallest_three([0.0, 0.0, 0.0, 1.0]);
let value = u32::from_le_bytes(packed);
let largest = value >> 30;
assert_eq!(largest, 3, "w is the dropped component");
}
#[test]
fn quaternion_packing_is_sign_invariant() {
let positive = pack_quaternion_smallest_three([0.1, 0.2, 0.3, 0.9]);
let negated = pack_quaternion_smallest_three([-0.1, -0.2, -0.3, -0.9]);
assert_eq!(
positive, negated,
"q and -q are the same rotation and must pack identically"
);
}
#[test]
fn quaternion_packing_normalises_input() {
let unit = pack_quaternion_smallest_three([0.0, 0.0, 0.0, 1.0]);
let scaled = pack_quaternion_smallest_three([0.0, 0.0, 0.0, 5.0]);
assert_eq!(unit, scaled, "magnitude is normalised away");
}
#[test]
fn degenerate_quaternion_falls_back_to_identity() {
let degenerate = pack_quaternion_smallest_three([0.0, 0.0, 0.0, 0.0]);
let identity = pack_quaternion_smallest_three([0.0, 0.0, 0.0, 1.0]);
assert_eq!(degenerate, identity);
}
#[test]
fn inconsistent_attribute_lengths_are_rejected() {
let mut cloud = unit_cloud(3);
cloud.opacities.pop();
let err = encode_spz(&cloud, false).expect_err("length mismatch");
assert!(format!("{err}").contains("inconsistent"), "{err}");
}
#[test]
fn mismatched_sh_buffer_is_rejected() {
let mut cloud = unit_cloud(2);
cloud.sh_degree = 1;
cloud.sh = vec![0.0; 5];
let err = encode_spz(&cloud, false).expect_err("sh length mismatch");
assert!(format!("{err}").contains("spherical harmonic"), "{err}");
}
#[test]
fn unsupported_sh_degree_is_rejected() {
let mut cloud = unit_cloud(1);
cloud.sh_degree = 4;
assert!(encode_spz(&cloud, false).is_err());
}
#[test]
fn empty_cloud_encodes_to_a_header_only_packet() {
let packet = gunzip(&encode_spz(&SplatCloud::default(), false).expect("encodes"));
assert_eq!(packet.len(), HEADER_BYTES);
assert_eq!(
u32::from_le_bytes(packet[8..12].try_into().expect("count")),
0
);
}
#[test]
fn output_is_gzip_framed() {
let bytes = encode_spz(&unit_cloud(2), false).expect("encodes");
assert_eq!(
&bytes[0..2],
&[0x1F, 0x8B],
"SPZ packets ship gzip-compressed"
);
}
}