Skip to main content

qualia_core_db/q42/emf_profiles/
spatial.rs

1//! Explicit full-cell dimensions and brick addressing; local records are XYZ
2//! row-major inside each clipped brick, independently of directory curve order.
3use super::*;
4use crate::q42::m64_matter::brick3d::{decode_hilbert3d_u64, encode_hilbert3d_u64};
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6pub enum GridIndexing {
7    Linear,
8    Morton { order: u32 },
9    Hilbert { order: u32 },
10}
11impl GridIndexing {
12    pub fn name(self) -> &'static str {
13        match self {
14            Self::Linear => "linear",
15            Self::Morton { .. } => "morton3",
16            Self::Hilbert { .. } => "hilbert3",
17        }
18    }
19    pub fn order(self) -> u32 {
20        match self {
21            Self::Linear => 0,
22            Self::Morton { order } | Self::Hilbert { order } => order,
23        }
24    }
25    pub fn common_order(self) -> Option<u32> {
26        match self {
27            Self::Linear => Some(0),
28            Self::Morton { .. } => Some(1),
29            Self::Hilbert { .. } => None,
30        }
31    }
32}
33#[derive(Clone, Copy, Debug, PartialEq)]
34pub struct GridSpec {
35    pub dimensions: [u32; 3],
36    pub brick_dimensions: [u32; 3],
37    pub spacing_m: [f64; 3],
38    pub indexing: GridIndexing,
39}
40#[derive(Clone, Copy, Debug, PartialEq)]
41pub struct GridLayout {
42    spec: GridSpec,
43    brick_grid: [u32; 3],
44    brick_count: u64,
45}
46impl GridSpec {
47    pub fn validate(self) -> Result<GridLayout, Error> {
48        let mut brick_grid = [0; 3];
49        let mut cells = 1u64;
50        let mut brick_count = 1u64;
51        for axis in 0..3 {
52            let n = self.dimensions[axis];
53            let b = self.brick_dimensions[axis];
54            let spacing = self.spacing_m[axis];
55            if n == 0 || b == 0 || !spacing.is_finite() || spacing <= 0.0 {
56                return Err(Error::Shape);
57            }
58            brick_grid[axis] = n / b + u32::from(n % b != 0);
59            cells = cells.checked_mul(u64::from(n)).ok_or(Error::Overflow)?;
60            brick_count = brick_count
61                .checked_mul(u64::from(brick_grid[axis]))
62                .ok_or(Error::Overflow)?;
63        }
64        if self.indexing != GridIndexing::Linear {
65            let order = self.indexing.order();
66            if order > 21 {
67                return Err(Error::Shape);
68            }
69            let side = 1u32 << order;
70            if brick_grid.iter().any(|&n| n > side) {
71                return Err(Error::Shape);
72            }
73        }
74        let _ = cells;
75        Ok(GridLayout {
76            spec: self,
77            brick_grid,
78            brick_count,
79        })
80    }
81}
82impl GridLayout {
83    pub fn spec(self) -> GridSpec {
84        self.spec
85    }
86    pub fn brick_grid_dimensions(self) -> [u32; 3] {
87        self.brick_grid
88    }
89    pub fn brick_count(self) -> u64 {
90        self.brick_count
91    }
92    pub fn encode_key(self, coordinate: [u32; 3]) -> Result<u64, Error> {
93        if (0..3).any(|i| coordinate[i] >= self.brick_grid[i]) {
94            return Err(Error::Index);
95        }
96        Ok(match self.spec.indexing {
97            GridIndexing::Linear => {
98                (u64::from(coordinate[2]) * u64::from(self.brick_grid[1])
99                    + u64::from(coordinate[1]))
100                    * u64::from(self.brick_grid[0])
101                    + u64::from(coordinate[0])
102            }
103            GridIndexing::Morton { order } => {
104                let mut key = 0;
105                for bit in 0..order {
106                    for axis in 0..3 {
107                        key |= u64::from((coordinate[axis] >> bit) & 1) << (3 * bit + axis as u32);
108                    }
109                }
110                key
111            }
112            GridIndexing::Hilbert { order } => {
113                encode_hilbert3d_u64(coordinate[0], coordinate[1], coordinate[2], order)
114            }
115        })
116    }
117    pub fn decode_key(self, key: u64) -> Result<[u32; 3], Error> {
118        let coordinate = match self.spec.indexing {
119            GridIndexing::Linear => {
120                if key >= self.brick_count {
121                    return Err(Error::Index);
122                }
123                let x = key % u64::from(self.brick_grid[0]);
124                let yz = key / u64::from(self.brick_grid[0]);
125                [
126                    x as u32,
127                    (yz % u64::from(self.brick_grid[1])) as u32,
128                    (yz / u64::from(self.brick_grid[1])) as u32,
129                ]
130            }
131            GridIndexing::Morton { order } => {
132                check_curve_key(key, order)?;
133                let mut coordinate = [0; 3];
134                for bit in 0..order {
135                    for axis in 0..3 {
136                        coordinate[axis] |= (((key >> (3 * bit + axis as u32)) & 1) as u32) << bit;
137                    }
138                }
139                coordinate
140            }
141            GridIndexing::Hilbert { order } => {
142                check_curve_key(key, order)?;
143                let (x, y, z) = decode_hilbert3d_u64(key, order);
144                [x, y, z]
145            }
146        };
147        if (0..3).any(|i| coordinate[i] >= self.brick_grid[i])
148            || self.encode_key(coordinate)? != key
149        {
150            return Err(Error::Index);
151        }
152        Ok(coordinate)
153    }
154    pub fn brick(self, key: u64) -> Result<BrickLayout, Error> {
155        let coordinate = self.decode_key(key)?;
156        let mut origin = [0; 3];
157        let mut shape = [0; 3];
158        let mut cells = 1u64;
159        for axis in 0..3 {
160            origin[axis] = coordinate[axis]
161                .checked_mul(self.spec.brick_dimensions[axis])
162                .ok_or(Error::Overflow)?;
163            shape[axis] =
164                self.spec.brick_dimensions[axis].min(self.spec.dimensions[axis] - origin[axis]);
165            cells = cells
166                .checked_mul(u64::from(shape[axis]))
167                .ok_or(Error::Overflow)?;
168        }
169        Ok(BrickLayout {
170            grid: self,
171            origin,
172            shape,
173            cells,
174        })
175    }
176}
177fn check_curve_key(key: u64, order: u32) -> Result<(), Error> {
178    if order > 21 || key >> (3 * order) != 0 {
179        return Err(Error::Index);
180    }
181    Ok(())
182}
183#[derive(Clone, Copy, Debug, PartialEq)]
184pub struct BrickLayout {
185    grid: GridLayout,
186    origin: [u32; 3],
187    shape: [u32; 3],
188    cells: u64,
189}
190impl BrickLayout {
191    /// The immutable validated grid used to decode this brick.
192    pub fn grid_layout(self) -> GridLayout {
193        self.grid
194    }
195    pub fn origin_cells(self) -> [u32; 3] {
196        self.origin
197    }
198    pub fn shape(self) -> [u32; 3] {
199        self.shape
200    }
201    pub fn cell_count(self) -> u64 {
202        self.cells
203    }
204    /// X fastest. Callers apply the time index separately, never Morton/Hilbert
205    /// permute these local rows just because the directory is curve-addressed.
206    pub fn global_cell(self, index: u64) -> Result<[u32; 3], Error> {
207        if index >= self.cells {
208            return Err(Error::Index);
209        }
210        let x = index % u64::from(self.shape[0]);
211        let yz = index / u64::from(self.shape[0]);
212        Ok([
213            self.origin[0] + x as u32,
214            self.origin[1] + (yz % u64::from(self.shape[1])) as u32,
215            self.origin[2] + (yz / u64::from(self.shape[1])) as u32,
216        ])
217    }
218    pub fn local_position_m(self, index: u64) -> Result<[f64; 3], Error> {
219        let cell = self.global_cell(index)?;
220        let mut p = [0.0; 3];
221        for axis in 0..3 {
222            p[axis] = f64::from(cell[axis]) * self.grid.spec.spacing_m[axis];
223            if !p[axis].is_finite() {
224                return Err(Error::NonFinite);
225            }
226        }
227        Ok(p)
228    }
229}
230pub(super) fn from_metadata(frame: Block<'_>, ext: Block<'_>) -> Result<GridLayout, Error> {
231    semantics::validate_fields(ext, super::extension_rules()).map_err(Error::Shared)?;
232    let dimensions = typed(frame, 6, 1, 3)?;
233    let spacing = typed(frame, 5, 5, 3)?;
234    let full = typed(ext, 8, 2, 3)?;
235    let brick = typed(ext, 9, 1, 3)?;
236    let mut dims = [0; 3];
237    let mut bricks = [0; 3];
238    let mut spacings = [0.0; 3];
239    for axis in 0..3 {
240        dims[axis] = u32_at(dimensions, axis * 4);
241        if u64_at(full, axis * 8) != u64::from(dims[axis]) {
242            return Err(Error::Frame);
243        }
244        bricks[axis] = u32_at(brick, axis * 4);
245        spacings[axis] = f64_at(spacing, axis * 8);
246    }
247    let order = scalar32(ext, 10)?;
248    let indexing = match text(required(ext, 7)?)? {
249        "linear" if order == 0 => GridIndexing::Linear,
250        "morton3" => GridIndexing::Morton { order },
251        "hilbert3" => GridIndexing::Hilbert { order },
252        _ => return Err(Error::UnsupportedProfile),
253    };
254    match (indexing.common_order(), field(frame, 7)) {
255        (Some(order), Some(value)) => {
256            if value.type_tag() != 1
257                || value.element_count() != 1
258                || value.flags() & 1 == 0
259                || u32_at(value.value(), 0) != order
260            {
261                return Err(Error::Frame);
262            }
263        }
264        (None, None) => {}
265        _ => return Err(Error::Frame),
266    }
267    GridSpec {
268        dimensions: dims,
269        brick_dimensions: bricks,
270        spacing_m: spacings,
271        indexing,
272    }
273    .validate()
274}
275fn typed<'a>(block: Block<'a>, key: u16, tag: u8, count: u32) -> Result<&'a [u8], Error> {
276    let f = required(block, key)?;
277    if f.type_tag() != tag || f.element_count() != count || f.flags() & 1 == 0 {
278        return Err(Error::Frame);
279    }
280    Ok(f.value())
281}