Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Octahedron normals #18

Closed
wants to merge 2 commits into from
Closed
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
146 changes: 56 additions & 90 deletions src/normals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ impl NormalPrecisionMode {
/// let dev_5_deg = NormalPrecisionMode::from_deg_dev(5.0);
/// ```
pub fn from_deg_dev(deg: FloatType) -> Self {
// TODO: use correct calculation here
let prec = ((90.0 / deg).log2().ceil() as u8).max(1);
Self(prec)
}
Expand All @@ -34,6 +35,7 @@ impl NormalPrecisionMode {
/// let dev_0_point_05_rad = NormalPrecisionMode::from_rad_dev(0.05);
/// ```
pub fn from_rad_dev(rad: FloatType) -> Self {
// TODO: use correct calculation here
let prec = (FRAC_PI_2 / rad).log2().ceil() as u8;
Self(prec)
}
Expand Down Expand Up @@ -64,73 +66,40 @@ pub fn normalize_arr(normals: &mut [Vector3]) {
*normal = normalize(*normal);
}
}
pub(crate) fn normal_to_encoding(
normal: Vector3,
precision: &NormalPrecisionMode,
) -> (u64, u64, bool, bool, bool) {
pub(crate) fn normal_to_encoding(normal: Vector3, precision: &NormalPrecisionMode) -> (u64, u64) {
let multiplier = ((1 << precision.0) - 1) as FloatType;
//Calculate asine
let xy = (normal.0.abs(), normal.1.abs());
let xy_mag = (xy.0 * xy.0 + xy.1 * xy.1).sqrt();
let xy = (xy.0 / xy_mag, xy.1 / xy_mag);
let asine = xy.0.asin();

let asine = asine / (PI / 2.0);
//
let asine = (asine * multiplier) as u64;
let z = (normal.2.abs() * multiplier) as u64;
let sx = normal.0 < 0.0;
let sy = normal.1 < 0.0;
let sz = normal.2 < 0.0;
(asine, z, sx, sy, sz)
let norm = normal.0.abs() + normal.1.abs() + normal.2.abs();
let mut nx = normal.0 / norm;
let mut ny = normal.1 / norm;
if !normal.2.is_sign_positive() {
// fold over negative z
(nx, ny) = ((1.0 - ny.abs()) * nx.signum(),
(1.0 - nx.abs()) * ny.signum());
}
nx = (nx * 0.5 + 0.5) * multiplier;
ny = (ny * 0.5 + 0.5) * multiplier;
(nx as u64, ny as u64)
}
pub(crate) fn normal_from_encoding(
asine: u64,
z: u64,
sx: bool,
sy: bool,
sz: bool,
precision: NormalPrecisionMode,
) -> Vector3 {
pub(crate) fn normal_from_encoding(a: u64, b: u64, precision: NormalPrecisionMode) -> Vector3 {
let divisor = ((1_u64 << precision.0) - 1) as FloatType;
//Read raw asine
let asine = (asine as FloatType) / divisor;
//Convert asine form 0-1 to 0-tau
let asine = asine * (PI / 2.0);
//Read xyz component
let z = (z as FloatType) / divisor;
#[cfg(feature = "fast_trig")]
let x = fsin(asine as fprec) as FloatType;
#[cfg(feature = "fast_trig")]
let y = (1.0 - x * x).sqrt();
#[cfg(not(feature = "fast_trig"))]
let (x, y) = asine.sin_cos();
// Calculate XY magnitude
let xy_mag = (1.0 - z * z).sqrt();
// Adjust x an y
let y = y * xy_mag;
let x = x * xy_mag;
// Set signs
let x = if sx { -x } else { x };
let y = if sy { -y } else { y };
let z = if sz { -z } else { z };
(x, y, z)
let mut x = (a as FloatType) / divisor * 2.0 - 1.0;
let mut y = (b as FloatType) / divisor * 2.0 - 1.0;
let z = 1.0 - x.abs() - y.abs();
x += x.signum() * z.min(0.0);
y += y.signum() * z.min(0.0);
normalize((x, y, z))
}
const PI: FloatType = std::f64::consts::PI as FloatType;
#[inline(always)]
fn save_normal<W: Write>(
normal: Vector3,
precision: NormalPrecisionMode,
writer: &mut UnalignedWriter<W>,
) -> std::io::Result<()> {
let (asine, z, sx, sy, sz) = normal_to_encoding(normal, &precision);
let (a, b) = normal_to_encoding(normal, &precision);
let main_prec = UnalignedRWMode::precision_bits(precision.0);

writer.write_bit(sx)?;
writer.write_bit(sy)?;
writer.write_bit(sz)?;
writer.write_unaligned(main_prec, asine)?;
writer.write_unaligned(main_prec, z)?;
writer.write_unaligned(main_prec, a)?;
writer.write_unaligned(main_prec, b)?;

Ok(())
}
Expand All @@ -140,12 +109,8 @@ fn read_normal<R: Read>(
reader: &mut UnalignedReader<R>,
) -> std::io::Result<Vector3> {
let main_prec = UnalignedRWMode::precision_bits(precision.0);
// Get signs of x y z component
let sx = reader.read_bit()?;
let sy = reader.read_bit()?;
let sz = reader.read_bit()?;
let (asine, z) = reader.read2_unaligned(main_prec)?;
Ok(normal_from_encoding(asine, z, sx, sy, sz, precision))
let (a, b) = reader.read2_unaligned(main_prec)?;
Ok(normal_from_encoding(a, b, precision))
}
pub(crate) fn save_normal_array<W: Write>(
normals: &[Vector3],
Expand Down Expand Up @@ -184,25 +149,43 @@ pub(crate) fn read_normal_array<R: Read>(reader: &mut R) -> Result<Box<[Vector3]
#[cfg(test)]
mod test_normal {
use super::*;
pub const NORM_PREC_HIGH: NormalPrecisionMode = NormalPrecisionMode(13);
const NORM_PREC_HIGH: NormalPrecisionMode = NormalPrecisionMode(13);
const PI: FloatType = std::f64::consts::PI as FloatType;
fn dot(a: Vector3, b: Vector3) -> FloatType {
a.0 * b.0 + a.1 * b.1 + a.2 * b.2
}
/// Angle between two vectors in degrees.
fn ang_between(a: Vector3, b: Vector3) -> FloatType {
dot(a, b).clamp(0.0, 1.0).acos() * 180.0 / PI
}
fn test_save(normal: Vector3) {
let mut res = Vec::with_capacity(64);
let precision = NormalPrecisionMode(14);
let precision = NormalPrecisionMode::from_deg_dev(0.01);
{
let mut writter = UnalignedWriter::new(&mut res);
save_normal(normal, precision, &mut writter).unwrap();
let mut writer = UnalignedWriter::new(&mut res);
save_normal(normal, precision, &mut writer).unwrap();
}
let mut reader = UnalignedReader::new(&res as &[u8]);
let r_normal = read_normal(precision, &mut reader).unwrap();
let n_dot = (1.0 - dot(r_normal, normal)) * 180.0;
let ang_diff = ang_between(r_normal, normal);
assert!(
n_dot < 0.01,
"expected:{normal:?} != read:{r_normal:?} angle:{n_dot}"
ang_diff < 0.01,
"expected:{normal:?} != read:{r_normal:?} angle:{ang_diff}"
);
}
/// Generator function for random normals (normalized).
fn random_normals() -> impl Iterator<Item = Vector3> {
use rand::{thread_rng, Rng};
let mut rng = thread_rng();
std::iter::from_fn(move || {
Some((
rng.gen::<FloatType>() * 2.0 - 1.0,
rng.gen::<FloatType>() * 2.0 - 1.0,
rng.gen::<FloatType>() * 2.0 - 1.0,
))
})
.map(normalize)
}
#[test]
fn x_axis_rw() {
test_save((1.0, 0.0, 0.0));
Expand All @@ -220,15 +203,7 @@ mod test_normal {
}
#[test]
fn random_axis_rw() {
use rand::{thread_rng, Rng};
let mut rng = thread_rng();
for _ in 0..100_000 {
let norm = (
rng.gen::<FloatType>() * 2.0 - 1.0,
rng.gen::<FloatType>() * 2.0 - 1.0,
rng.gen::<FloatType>() * 2.0 - 1.0,
);
let norm = normalize(norm);
for norm in random_normals().take(100_000) {
test_save(norm);
}
}
Expand All @@ -238,25 +213,16 @@ mod test_normal {
let mut rng = thread_rng();
let count = ((rng.gen::<crate::IndexType>() % 0x800) + 0x800) as usize;
let mut res = Vec::with_capacity(count);
let mut normals = Vec::with_capacity(count);
for _ in 0..count {
let norm = (
rng.gen::<FloatType>() * 2.0 - 1.0,
rng.gen::<FloatType>() * 2.0 - 1.0,
rng.gen::<FloatType>() * 2.0 - 1.0,
);
let norm = normalize(norm);
normals.push(norm);
}
let normals: Vec<_> = random_normals().take(count).collect();
save_normal_array(&normals, &mut res, NORM_PREC_HIGH).unwrap();
let r_normals = read_normal_array(&mut (&res as &[u8])).unwrap();
for i in 0..count {
let r_normal = r_normals[i];
let normal = normals[i];
let n_dot = (1.0 - dot(r_normal, normal)) * 180.0;
let ang_diff = ang_between(r_normal, normal);
assert!(
n_dot < 0.1,
"expected:{normal:?} != read:{r_normal:?} angle:{n_dot}"
ang_diff < 0.1,
"expected:{normal:?} != read:{r_normal:?} angle:{ang_diff}"
);
}
}
Expand Down
46 changes: 12 additions & 34 deletions src/tangents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,25 +42,13 @@ fn ht_from_bool(src: bool) -> HandednessType {
}
/// A representation of a Tangent.
pub type Tangent = (crate::Vector3, HandednessType);
fn tangent_to_encoding(
tangent: Tangent,
prec: TangentPrecisionMode,
) -> (u64, u64, bool, bool, bool, bool) {
fn tangent_to_encoding(tangent: Tangent, prec: TangentPrecisionMode) -> (u64, u64, bool) {
let normal = crate::normals::normal_to_encoding(tangent.0, &prec.normal_precision());
let handeness = ht_to_bool(tangent.1);
(normal.0, normal.1, normal.2, normal.3, normal.4, handeness)
}
fn tangent_from_encoding(
asine: u64,
z: u64,
sx: bool,
sy: bool,
sz: bool,
handenes: bool,
prec: TangentPrecisionMode,
) -> Tangent {
let normal =
crate::normals::normal_from_encoding(asine, z, sx, sy, sz, prec.normal_precision());
(normal.0, normal.1, handeness)
}
fn tangent_from_encoding(a: u64, b: u64, handenes: bool, prec: TangentPrecisionMode) -> Tangent {
let normal = crate::normals::normal_from_encoding(a, b, prec.normal_precision());
let handeness = ht_from_bool(handenes);
(normal, handeness)
}
Expand All @@ -76,13 +64,10 @@ pub(crate) fn save_tangents<W: std::io::Write>(
let mut writer = UnalignedWriter::new(target);
let bits_prec = UnalignedRWMode::precision_bits(bits_prec);
for tangent in tangents {
let (asine, z, sx, sy, sz, handeness) = tangent_to_encoding(*tangent, prec);
let (a, b, handeness) = tangent_to_encoding(*tangent, prec);
writer.write_bit(handeness)?;
writer.write_bit(sx)?;
writer.write_bit(sy)?;
writer.write_bit(sz)?;
writer.write_unaligned(bits_prec, asine)?;
writer.write_unaligned(bits_prec, z)?;
writer.write_unaligned(bits_prec, a)?;
writer.write_unaligned(bits_prec, b)?;
}
writer.flush()?;
Ok(())
Expand All @@ -96,23 +81,16 @@ pub(crate) fn read_tangents<R: std::io::Read>(src: &mut R) -> std::io::Result<Bo
let mut tangents = Vec::with_capacity(count as usize);
for _ in 0..count {
let handeness = reader.read_bit()?;
let sx = reader.read_bit()?;
let sy = reader.read_bit()?;
let sz = reader.read_bit()?;
let asine = reader.read_unaligned(prec)?;
let z = reader.read_unaligned(prec)?;
tangents.push(tangent_from_encoding(
asine, z, sx, sy, sz, handeness, tan_prec,
));
let a = reader.read_unaligned(prec)?;
let b = reader.read_unaligned(prec)?;
tangents.push(tangent_from_encoding(a, b, handeness, tan_prec));
}
Ok(tangents.into())
}
#[cfg(test)]
fn test_tangent(tangent: Tangent, prec: TangentPrecisionMode) -> FloatType {
let encoded = tangent_to_encoding(tangent, prec);
let decoded = tangent_from_encoding(
encoded.0, encoded.1, encoded.2, encoded.3, encoded.4, encoded.5, prec,
);
let decoded = tangent_from_encoding(encoded.0, encoded.1, encoded.2, prec);
assert_eq!(ht_to_bool(tangent.1), ht_to_bool(decoded.1));
(1.0 - crate::utilis::dot(decoded.0, tangent.0)) * 180.0
}
Expand Down