1pub const SECTION_VOLUME: usize = 4096;
20
21#[inline]
24#[must_use]
25pub const fn block_index(x: i32, y: i32, z: i32) -> usize {
26 (((y & 15) << 8) | ((z & 15) << 4) | (x & 15)) as usize
27}
28
29#[derive(Clone)]
31pub struct Indexed {
32 idx: [u8; SECTION_VOLUME],
34 palette: [u16; 256],
36 len: u16,
38 non_air: u16,
40}
41
42#[derive(Clone)]
44pub struct Direct {
45 states: [u16; SECTION_VOLUME],
46 non_air: u16,
48}
49
50#[derive(Clone)]
52pub enum Section {
53 Uniform(u16),
55 Indexed(Box<Indexed>),
57 Direct(Box<Direct>),
59}
60
61impl std::fmt::Debug for Section {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 match self {
64 Section::Uniform(s) => f.debug_tuple("Uniform").field(s).finish(),
65 Section::Indexed(b) => f
66 .debug_struct("Indexed")
67 .field("palette", &&b.palette[..usize::from(b.len)])
68 .field("non_air", &b.non_air)
69 .finish(),
70 Section::Direct(b) => f
71 .debug_struct("Direct")
72 .field("non_air", &b.non_air)
73 .finish(),
74 }
75 }
76}
77
78impl Section {
79 #[inline]
81 #[must_use]
82 pub fn get(&self, i: usize) -> u16 {
83 let i = i & (SECTION_VOLUME - 1);
84 match self {
85 Section::Uniform(s) => *s,
86 Section::Indexed(b) => b.palette[usize::from(b.idx[i])],
87 Section::Direct(b) => b.states[i],
88 }
89 }
90
91 #[must_use]
93 pub fn non_air(&self) -> u16 {
94 match self {
95 Section::Uniform(_) => SECTION_VOLUME as u16,
96 Section::Indexed(b) => b.non_air,
97 Section::Direct(b) => b.non_air,
98 }
99 }
100
101 #[must_use]
103 pub fn heap_bytes(&self) -> usize {
104 match self {
105 Section::Uniform(_) => 0,
106 Section::Indexed(_) => size_of::<Indexed>(),
107 Section::Direct(_) => size_of::<Direct>(),
108 }
109 }
110
111 pub fn any_state(&self, f: impl Fn(u16) -> bool) -> bool {
115 match self {
116 Section::Uniform(s) => f(*s),
117 Section::Indexed(b) => b.palette[..usize::from(b.len)].iter().any(|&s| f(s)),
118 Section::Direct(b) => b.states.iter().any(|&s| f(s)),
119 }
120 }
121
122 pub fn for_each(&self, mut f: impl FnMut(usize, u16)) {
124 match self {
125 Section::Uniform(s) => (0..SECTION_VOLUME).for_each(|i| f(i, *s)),
126 Section::Indexed(b) => {
127 for (i, &p) in b.idx.iter().enumerate() {
128 f(i, b.palette[usize::from(p)]);
129 }
130 }
131 Section::Direct(b) => {
132 for (i, &s) in b.states.iter().enumerate() {
133 f(i, s);
134 }
135 }
136 }
137 }
138
139 pub fn set(&mut self, i: usize, state: u16) -> bool {
142 let i = i & (SECTION_VOLUME - 1);
143 match self {
144 Section::Uniform(u) => {
145 if *u == state {
146 return true;
147 }
148 let mut b = Box::new(Indexed {
149 idx: [0; SECTION_VOLUME],
150 palette: [0; 256],
151 len: 2,
152 non_air: SECTION_VOLUME as u16,
153 });
154 b.palette[0] = *u;
155 b.palette[1] = state;
156 b.idx[i] = 1;
157 if state == 0 {
158 b.non_air -= 1;
159 }
160 *self = Section::Indexed(b);
161 true
162 }
163 Section::Indexed(b) => {
164 let old = b.palette[usize::from(b.idx[i])];
165 if old == state {
166 return true;
167 }
168 let p = match b.find_or_insert(state) {
169 Some(p) => p,
170 None => {
171 let mut d = Box::new(Direct {
173 states: [0; SECTION_VOLUME],
174 non_air: b.non_air,
175 });
176 for (dst, &p) in d.states.iter_mut().zip(b.idx.iter()) {
177 *dst = b.palette[usize::from(p)];
178 }
179 *self = Section::Direct(d);
180 return self.set(i, state);
181 }
182 };
183 b.idx[i] = p;
184 adjust(&mut b.non_air, old, state);
185 b.non_air != 0
186 }
187 Section::Direct(b) => {
188 let old = b.states[i];
189 b.states[i] = state;
190 adjust(&mut b.non_air, old, state);
191 b.non_air != 0
192 }
193 }
194 }
195
196 #[must_use]
198 pub fn single(i: usize, state: u16) -> Option<Section> {
199 if state == 0 {
200 return None;
201 }
202 let mut b = Box::new(Indexed {
203 idx: [0; SECTION_VOLUME],
204 palette: [0; 256],
205 len: 2,
206 non_air: 1,
207 });
208 b.palette[1] = state;
209 b.idx[i & (SECTION_VOLUME - 1)] = 1;
210 Some(Section::Indexed(b))
211 }
212}
213
214#[inline]
215fn adjust(non_air: &mut u16, old: u16, new: u16) {
216 match (old == 0, new == 0) {
217 (true, false) => *non_air += 1,
218 (false, true) => *non_air -= 1,
219 _ => {}
220 }
221}
222
223impl Indexed {
224 fn find_or_insert(&mut self, state: u16) -> Option<u8> {
227 let len = usize::from(self.len);
228 if let Some(p) = self.palette[..len].iter().position(|&s| s == state) {
229 return Some(p as u8);
230 }
231 if len == 256 {
232 self.compact();
233 }
234 let len = usize::from(self.len);
235 if len == 256 {
236 return None;
237 }
238 self.palette[len] = state;
239 self.len += 1;
240 Some(len as u8)
241 }
242
243 fn compact(&mut self) {
245 let mut used = [false; 256];
246 for &p in &self.idx {
247 used[usize::from(p)] = true;
248 }
249 let mut remap = [0u8; 256];
250 let mut palette = [0u16; 256];
251 let mut n = 0usize;
252 for p in 0..usize::from(self.len) {
253 if used[p] {
254 remap[p] = n as u8;
255 palette[n] = self.palette[p];
256 n += 1;
257 }
258 }
259 for p in &mut self.idx {
260 *p = remap[usize::from(*p)];
261 }
262 self.palette = palette;
263 self.len = n as u16;
264 }
265}
266
267#[cfg_attr(
271 not(any(feature = "v1_8", feature = "v1_12", feature = "v1_16_5")),
272 allow(dead_code)
273)]
274pub(crate) struct SectionBuilder {
275 lookup: Vec<u16>,
278}
279
280#[cfg_attr(
281 not(any(feature = "v1_8", feature = "v1_12", feature = "v1_16_5")),
282 allow(dead_code)
283)]
284impl SectionBuilder {
285 pub(crate) fn new(state_space: usize) -> Self {
286 SectionBuilder {
287 lookup: vec![0; state_space],
288 }
289 }
290
291 pub(crate) fn build(&mut self, states: &[u16; SECTION_VOLUME]) -> Option<Section> {
294 let space = self.lookup.len();
295 let mut non_air = 0u16;
296 for &s in states {
297 non_air += u16::from(s != 0);
298 }
299 if non_air == 0 {
300 return None;
301 }
302 let mut ix = Box::new(Indexed {
303 idx: [0; SECTION_VOLUME],
304 palette: [0; 256],
305 len: 0,
306 non_air,
307 });
308 let mut len = 0usize;
309 let mut overflow = false;
310 for (dst, &s) in ix.idx.iter_mut().zip(states.iter()) {
311 let s = if usize::from(s) < space { s } else { 0 };
312 let slot = &mut self.lookup[usize::from(s)];
313 if *slot == 0 {
314 if len == 256 {
315 overflow = true;
316 break;
317 }
318 ix.palette[len] = s;
319 len += 1;
320 *slot = len as u16;
321 }
322 *dst = (*slot - 1) as u8;
323 }
324 self.reset(&ix.palette[..len]);
325 if overflow {
326 let mut d = Box::new(Direct {
327 states: *states,
328 non_air: 0,
329 });
330 let mut n = 0u16;
331 for s in &mut d.states {
332 if usize::from(*s) >= space {
333 *s = 0;
334 }
335 n += u16::from(*s != 0);
336 }
337 d.non_air = n;
338 return (n != 0).then_some(Section::Direct(d));
339 }
340 if len == 1 {
341 return Some(Section::Uniform(ix.palette[0]));
342 }
343 if ix.palette[..len].contains(&0) {
345 let air = ix.palette[..len].iter().position(|&s| s == 0).unwrap_or(0) as u8;
346 ix.non_air = ix.idx.iter().filter(|&&p| p != air).count() as u16;
347 if ix.non_air == 0 {
348 return None;
349 }
350 }
351 ix.len = len as u16;
352 Some(Section::Indexed(ix))
353 }
354
355 #[cfg_attr(not(feature = "v1_16_5"), allow(dead_code))]
359 pub(crate) fn build_packed(
360 &mut self,
361 remap: &[u16],
362 bits: u32,
363 data: &[u8],
364 ) -> Option<Section> {
365 self.build_packed_layout(remap, bits, data, false)
366 }
367
368 #[cfg_attr(not(any(feature = "v1_12", feature = "v1_16_5")), allow(dead_code))]
371 pub(crate) fn build_packed_layout(
372 &mut self,
373 remap: &[u16],
374 bits: u32,
375 data: &[u8],
376 spanning: bool,
377 ) -> Option<Section> {
378 debug_assert!((4..=8).contains(&bits));
379 let reachable = 1usize << bits;
380 let mut palette = [0u16; 256];
382 let mut len = 0usize;
383 let mut to_palette = [0u8; 256];
384 let space = self.lookup.len();
385 for (w, slot_out) in to_palette.iter_mut().enumerate().take(reachable) {
386 let s = remap.get(w).copied().unwrap_or(0);
387 let s = if usize::from(s) < space { s } else { 0 };
388 let slot = &mut self.lookup[usize::from(s)];
389 if *slot == 0 {
390 palette[len] = s;
391 len += 1;
392 *slot = len as u16;
393 }
394 *slot_out = (*slot - 1) as u8;
395 if w >= remap.len() {
396 let air = *slot_out;
398 to_palette[w..reachable].fill(air);
399 break;
400 }
401 }
402 self.reset(&palette[..len]);
403
404 let mut ix = Box::new(Indexed {
405 idx: [0; SECTION_VOLUME],
406 palette: [0; 256],
407 len: 0,
408 non_air: 0,
409 });
410 let mut hist = [0u16; 256];
411 let mut put = |i: usize, v: u32| {
412 let p = to_palette[(v & 255) as usize];
413 ix.idx[i] = p;
414 hist[usize::from(p)] += 1;
415 };
416 if spanning {
417 crate::packed::unpack_spanning_be(bits, data, SECTION_VOLUME, &mut put);
418 } else {
419 crate::packed::unpack_be(bits, data, SECTION_VOLUME, &mut put);
420 }
421 let mut remap2 = [0u8; 256];
423 let mut n = 0usize;
424 let mut non_air = 0u16;
425 for p in 0..len {
426 if hist[p] != 0 {
427 remap2[p] = n as u8;
428 ix.palette[n] = palette[p];
429 if palette[p] != 0 {
430 non_air += hist[p];
431 }
432 n += 1;
433 }
434 }
435 if non_air == 0 {
436 return None;
437 }
438 if n == 1 {
439 return Some(Section::Uniform(ix.palette[0]));
440 }
441 if n != len {
442 for p in &mut ix.idx {
443 *p = remap2[usize::from(*p)];
444 }
445 }
446 ix.len = n as u16;
447 ix.non_air = non_air;
448 Some(Section::Indexed(ix))
449 }
450
451 fn reset(&mut self, palette: &[u16]) {
452 for &s in palette {
453 self.lookup[usize::from(s)] = 0;
454 }
455 }
456}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
461
462 fn check_eq(s: &Option<Section>, expect: &[u16]) {
463 for (i, &e) in expect.iter().enumerate() {
464 let got = s.as_ref().map_or(0, |s| s.get(i));
465 assert_eq!(got, e, "index {i}");
466 }
467 let non_air = expect.iter().filter(|&&v| v != 0).count();
468 assert_eq!(s.as_ref().map_or(0, |s| usize::from(s.non_air())), non_air);
469 }
470
471 #[test]
472 fn build_variants() {
473 let mut b = SectionBuilder::new(4096);
474 assert!(b.build(&[0; 4096]).is_none());
475 assert!(matches!(b.build(&[16; 4096]), Some(Section::Uniform(16))));
476 let v: Vec<u16> = (0..4096).map(|i| (i % 7) as u16 * 16).collect();
477 let s = b.build(v.as_slice().try_into().unwrap());
478 assert!(matches!(s, Some(Section::Indexed(_))));
479 check_eq(&s, &v);
480 let v: Vec<u16> = (0..4096).map(|i| (i % 300) as u16).collect();
481 let s = b.build(v.as_slice().try_into().unwrap());
482 assert!(matches!(s, Some(Section::Direct(_))));
483 check_eq(&s, &v);
484 assert!(b.lookup.iter().all(|&x| x == 0));
486 }
487
488 #[test]
489 fn set_transitions() {
490 let mut b = SectionBuilder::new(4096);
491 let mut expect = vec![1u16; 4096];
492 let mut s = b.build(&[1; 4096]);
493 for (i, e) in expect.iter_mut().enumerate() {
495 let v = (i % 400) as u16;
496 *e = v;
497 let alive = s.as_mut().unwrap().set(i, v);
498 assert!(alive);
499 }
500 check_eq(&s, &expect);
501 assert!(matches!(s, Some(Section::Direct(_))));
502 for i in 0..4096usize {
503 let alive = s.as_mut().unwrap().set(i, 0);
504 assert_eq!(alive, i != 4095);
505 }
506 }
507
508 #[test]
509 fn palette_compaction_keeps_indexed() {
510 let mut b = SectionBuilder::new(4096);
511 let mut s = b.build(&[1; 4096]).unwrap();
512 for v in 2..1000u16 {
514 s.set(0, v);
515 }
516 assert!(matches!(s, Section::Indexed(_)), "{s:?}");
517 assert_eq!(s.get(0), 999);
518 assert_eq!(s.get(1), 1);
519 }
520
521 #[test]
522 fn single() {
523 let s = Section::single(block_index(1, 2, 3), 5).unwrap();
524 assert_eq!(s.get(block_index(1, 2, 3)), 5);
525 assert_eq!(s.get(0), 0);
526 assert_eq!(s.non_air(), 1);
527 assert!(Section::single(0, 0).is_none());
528 }
529}