Repository navigation
Expand file tree
/
Copy pathpumpkin-memory.patch
More file actions
1674 lines (1587 loc) · 66.6 KB
/
Copy pathpumpkin-memory.patch
File metadata and controls
1674 lines (1587 loc) · 66.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Subject: [PATCH] Reduce Pumpkin template, chunk, and idle pathfinder memory
Loaded structure templates previously retained a block-state description for
every block and a second placement list. Store palette indices, share the first
palette's block array with the placement accessors, and borrow descriptions for
queries. Share immutable block-entity NBT until a placement needs an owned copy.
Update template consumers and cover ordering, multiple palettes, round trips,
entity data, and copy-on-placement behavior.
Retain generation chunks as uniform or indexed sections instead of full-height
dense arrays. Use a dense scratch buffer only during the active noise pass to
avoid per-voxel palette bookkeeping, then compact it before retaining the chunk.
Generation dependencies, dimensions, and block values remain unchanged.
Use packed in-memory palette indices, share light arrays with copy-on-write,
allocate carving-mask words on demand, and grow pathfinding heaps only when
needed. Preserve block values, lighting initialization, and search behavior.
Limit pooled density buffers by bytes and prune structure-start entries that
no active generation task references. Concurrent cache misses share a canonical
collector so pointer-based structure deduplication remains valid.
Base-commit: b5b9b9d7010e793806a83c495af223c67e1d35ee
---
diff --git a/crates/pumpkin-world/src/chunk/format/mod.rs b/crates/pumpkin-world/src/chunk/format/mod.rs
index 68432e19..cd52b03b 100644
--- a/crates/pumpkin-world/src/chunk/format/mod.rs
+++ b/crates/pumpkin-world/src/chunk/format/mod.rs
@@ -2,7 +2,7 @@ use std::{
path::PathBuf,
str::FromStr,
sync::{
- RwLock,
+ Arc, LazyLock, RwLock,
atomic::{AtomicBool, AtomicU64, Ordering},
},
};
@@ -256,9 +256,9 @@ impl ChunkData {
});
block_lights[index] =
- block_light.map_or(LightContainer::Empty(0), LightContainer::Full);
+ block_light.map_or(LightContainer::Empty(0), LightContainer::new);
sky_lights[index] =
- sky_light.map_or(LightContainer::Empty(0), LightContainer::Full);
+ sky_light.map_or(LightContainer::Empty(0), LightContainer::new);
if let Some(bs_compound) = section_compound.get_compound("block_states") {
let data = bs_compound
@@ -810,7 +810,8 @@ pub struct ChunkSectionBlockStates {
#[derive(Debug, Clone)]
pub enum LightContainer {
Empty(u8),
- Full(Box<[u8]>),
+ // Clones share immutable data; writes detach through Arc::make_mut.
+ Full(Arc<[u8]>),
}
impl LightContainer {
@@ -830,14 +831,38 @@ impl LightContainer {
"Data length must be {}",
Self::ARRAY_SIZE
);
- Self::Full(data)
+ let value = data[0];
+ if value >> 4 == value & 15 && data.iter().all(|&byte| byte == value) {
+ Self::new_filled(value & 15)
+ } else {
+ Self::Full(data.into())
+ }
}
#[must_use]
pub fn new_filled(default: u8) -> Self {
assert!(default <= 15, "Default value must be between 0 and 15");
- let value = default << 4 | default;
- Self::Full([value; Self::ARRAY_SIZE].into())
+ // Keep initialized uniform light distinct from Empty: packet masks and
+ // saved light data must retain the same semantics as a full array.
+ static UNIFORM: LazyLock<[Arc<[u8]>; 16]> = LazyLock::new(|| {
+ std::array::from_fn(|value| vec![(value as u8) * 17; LightContainer::ARRAY_SIZE].into())
+ });
+ Self::Full(Arc::clone(&UNIFORM[default as usize]))
+ }
+
+ /// Intern arrays that became uniform while lighting was propagated.
+ pub fn compact(&mut self) {
+ if let Self::Full(data) = self {
+ // Shared uniform arrays are already interned. Other shared arrays
+ // remain unchanged until a writer detaches them.
+ if Arc::strong_count(data) != 1 || data.len() != Self::ARRAY_SIZE {
+ return;
+ }
+ let value = data[0];
+ if value >> 4 == value & 15 && data.iter().all(|&byte| byte == value) {
+ *self = Self::new_filled(value & 15);
+ }
+ }
}
#[must_use]
@@ -869,7 +894,10 @@ impl LightContainer {
let index = Self::index(x, y, z);
let shift = 4 * (index & 1);
let mask = 0x0F << shift;
- data[index >> 1] = (data[index >> 1] & !mask) | (value << shift);
+ let updated = (data[index >> 1] & !mask) | (value << shift);
+ if data[index >> 1] != updated {
+ Arc::make_mut(data)[index >> 1] = updated;
+ }
}
Self::Empty(default) => {
if value != *default {
@@ -898,6 +926,10 @@ impl LightContainer {
let mask = 0x0F << shift;
let val = (value & 0x0F) << shift;
let mut byte_idx = (y_start * 256 + z * 16 + x) >> 1;
+ if (0..y_end - y_start).all(|dy| data[byte_idx + dy * 128] & mask == val) {
+ return;
+ }
+ let data = Arc::make_mut(data);
for _ in y_start..y_end {
data[byte_idx] = (data[byte_idx] & !mask) | val;
byte_idx += 128;
@@ -931,6 +963,58 @@ mod tests {
use pumpkin_nbt::compound::NbtCompound;
use pumpkin_nbt::tag::NbtTag;
+ #[test]
+ fn propagated_uniform_light_is_compacted_without_becoming_empty() {
+ let mut light = LightContainer::new_empty(0);
+ for x in 0..16 {
+ for z in 0..16 {
+ light.set_column_y_range(x, z, 0, 16, 15);
+ }
+ }
+ light.compact();
+ let shared = LightContainer::new_filled(15);
+ let (LightContainer::Full(a), LightContainer::Full(b)) = (&light, &shared) else {
+ panic!("compaction must preserve initialized light");
+ };
+ assert!(Arc::ptr_eq(a, b));
+ assert!(a.iter().all(|&value| value == 255));
+ light.set(0, 0, 0, 0);
+ assert_eq!(shared.get(0, 0, 0), 15);
+ }
+
+ #[test]
+ fn uniform_light_is_shared_without_changing_initialized_state() {
+ let mut a = LightContainer::new_filled(15);
+ let b = LightContainer::new(vec![255; LightContainer::ARRAY_SIZE].into_boxed_slice());
+ assert!(!a.is_empty());
+ let (LightContainer::Full(a_data), LightContainer::Full(b_data)) = (&a, &b) else {
+ panic!("initialized light must remain Full");
+ };
+ assert!(Arc::ptr_eq(a_data, b_data));
+ a.set(1, 2, 3, 15);
+ let LightContainer::Full(a_data) = &a else {
+ unreachable!()
+ };
+ assert!(Arc::ptr_eq(a_data, b_data));
+ a.set(1, 2, 3, 7);
+ assert_eq!(a.get(1, 2, 3), 7);
+ assert_eq!(a.get(0, 2, 3), 15);
+ assert_eq!(b.get(1, 2, 3), 15);
+ }
+
+ #[test]
+ fn cloned_light_columns_do_not_mutate_the_source() {
+ let mut source = LightContainer::new_filled(0);
+ source.set(4, 3, 2, 6);
+ let mut copy = source.clone();
+ copy.set_column_y_range(4, 2, 0, 16, 12);
+ for y in 0..16 {
+ assert_eq!(copy.get(4, y, 2), 12);
+ assert_eq!(copy.get(5, y, 2), 0);
+ assert_eq!(source.get(4, y, 2), if y == 3 { 6 } else { 0 });
+ }
+ }
+
#[test]
fn extract_u16_array_from_vanilla_compound_palette() {
let mut entry1 = NbtCompound::new();
diff --git a/crates/pumpkin-world/src/chunk/palette.rs b/crates/pumpkin-world/src/chunk/palette.rs
index 39ed39a7..911e320d 100644
--- a/crates/pumpkin-world/src/chunk/palette.rs
+++ b/crates/pumpkin-world/src/chunk/palette.rs
@@ -51,7 +51,66 @@ pub struct HeterogeneousPaletteData<V: Hash + Eq + Copy, const DIM: usize> {
#[derive(Clone)]
enum PaletteStorage<V, const DIM: usize> {
Dense(Box<AbstractCube<V, DIM>>),
- Indexed(Box<AbstractCube<u8, DIM>>),
+ Indexed(PackedIndices),
+}
+
+/// In-memory palette indices use 1, 2, 4, or 8 bits per block. Wire-format
+/// packing remains independent because Minecraft pads entries within each u64.
+#[derive(Clone)]
+struct PackedIndices {
+ bytes: Box<[u8]>,
+ len: usize,
+ bits: u8,
+}
+
+impl PackedIndices {
+ fn width(palette_len: usize) -> u8 {
+ match palette_len {
+ 0..=2 => 1,
+ 3..=4 => 2,
+ 5..=16 => 4,
+ _ => 8,
+ }
+ }
+
+ fn new(len: usize, palette_len: usize) -> Self {
+ let bits = Self::width(palette_len);
+ Self {
+ bytes: vec![0; len.div_ceil(8 / bits as usize)].into_boxed_slice(),
+ len,
+ bits,
+ }
+ }
+
+ fn from_slice(indices: &[u8], palette_len: usize) -> Self {
+ let mut packed = Self::new(indices.len(), palette_len);
+ for (i, &index) in indices.iter().enumerate() {
+ packed.set(i, index);
+ }
+ packed
+ }
+
+ #[inline]
+ fn get(&self, index: usize) -> u8 {
+ let bit = index * self.bits as usize;
+ (self.bytes[bit >> 3] >> (bit & 7)) & (u8::MAX >> (8 - self.bits))
+ }
+
+ #[inline]
+ fn set(&mut self, index: usize, value: u8) {
+ if value > (u8::MAX >> (8 - self.bits)) {
+ let mut wider = Self::new(self.len, value as usize + 1);
+ for i in 0..self.len {
+ wider.set(i, self.get(i));
+ }
+ *self = wider;
+ }
+ let bit = index * self.bits as usize;
+ let shift = bit & 7;
+ let mask = (u8::MAX >> (8 - self.bits)) << shift;
+ let byte = &mut self.bytes[bit >> 3];
+ *byte = (*byte & !mask) | (value << shift);
+ }
}
impl<V: Hash + Eq + Copy + Default, const DIM: usize> HeterogeneousPaletteData<V, DIM> {
@@ -62,7 +121,9 @@ impl<V: Hash + Eq + Copy + Default, const DIM: usize> HeterogeneousPaletteData<V
match &self.storage {
PaletteStorage::Dense(cube) => cube[y][z][x],
- PaletteStorage::Indexed(indices) => self.palette[indices[y][z][x] as usize],
+ PaletteStorage::Indexed(indices) => {
+ self.palette[indices.get((y * DIM + z) * DIM + x) as usize]
+ }
}
}
@@ -101,7 +162,7 @@ impl<V: Hash + Eq + Copy + Default, const DIM: usize> HeterogeneousPaletteData<V
}
PaletteStorage::Indexed(indices) => {
if new_index <= 255 {
- indices[y][z][x] = new_index as u8;
+ indices.set((y * DIM + z) * DIM + x, new_index as u8);
} else {
// Upgrade to Dense
let mut cube = Box::new([[[V::default(); DIM]; DIM]; DIM]);
@@ -111,10 +172,7 @@ impl<V: Hash + Eq + Copy + Default, const DIM: usize> HeterogeneousPaletteData<V
.iter_mut()
.enumerate()
{
- let y = i / (DIM * DIM);
- let z = (i / DIM) % DIM;
- let x = i % DIM;
- *v = self.palette[indices[y][z][x] as usize];
+ *v = self.palette[indices.get(i) as usize];
}
cube[y][z][x] = value;
self.storage = PaletteStorage::Dense(cube);
@@ -138,13 +196,9 @@ impl<V: Hash + Eq + Copy + Default, const DIM: usize> HeterogeneousPaletteData<V
// If we are indexed, we need to update all indices because swap_remove changed indices
if !upgraded && let PaletteStorage::Indexed(indices) = &mut self.storage {
- for row in indices.iter_mut() {
- for col in row.iter_mut() {
- for idx in col.iter_mut() {
- if *idx as usize == last_index {
- *idx = original_index as u8;
- }
- }
+ for i in 0..indices.len {
+ if indices.get(i) as usize == last_index {
+ indices.set(i, original_index as u8);
}
}
}
@@ -194,7 +248,10 @@ impl<V: Hash + Eq + Copy + Default, const DIM: usize> PalettedContainer<V, DIM>
indices.as_flattened_mut().as_flattened_mut()[i] = idx as u8;
}
Self::Heterogeneous(Box::new(HeterogeneousPaletteData {
- storage: PaletteStorage::Indexed(indices),
+ storage: PaletteStorage::Indexed(PackedIndices::from_slice(
+ indices.as_flattened().as_flattened(),
+ palette.len(),
+ )),
palette,
counts,
}))
@@ -241,7 +298,10 @@ impl<V: Hash + Eq + Copy + Default, const DIM: usize> PalettedContainer<V, DIM>
}
let storage = if palette.len() <= 256 && std::mem::size_of::<V>() > 1 {
- PaletteStorage::Indexed(indices)
+ PaletteStorage::Indexed(PackedIndices::from_slice(
+ indices.as_flattened().as_flattened(),
+ palette.len(),
+ ))
} else {
PaletteStorage::Dense(cube)
};
@@ -286,19 +346,16 @@ impl<V: Hash + Eq + Copy + Default, const DIM: usize> PalettedContainer<V, DIM>
})
})
.collect(),
- PaletteStorage::Indexed(indices) => indices
- .as_flattened()
- .as_flattened()
- .chunks(blocks_per_i64 as usize)
- .map(|chunk| {
- chunk.iter().enumerate().fold(0, |acc, (index, key_index)| {
- let key_index = *key_index as usize;
- debug_assert!((1 << bits_per_entry) > key_index);
-
- let packed_offset_index =
- (key_index as u64) << (bits_per_entry as u64 * index as u64);
- acc | packed_offset_index as i64
- })
+ PaletteStorage::Indexed(indices) => (0..indices.len)
+ .step_by(blocks_per_i64 as usize)
+ .map(|start| {
+ (start..(start + blocks_per_i64 as usize).min(indices.len))
+ .enumerate()
+ .fold(0i64, |word, (offset, i)| {
+ word | ((indices.get(i) as u64)
+ << (bits_per_entry as usize * offset))
+ as i64
+ })
})
.collect(),
};
@@ -352,14 +409,15 @@ impl<V: Hash + Eq + Copy + Default, const DIM: usize> PalettedContainer<V, DIM>
counts[idx] += 1;
} else {
warn!("Lookup index out of bounds! Defaulting...");
- // value is already 0, and counts[0] will be updated correctly if we track it
+ counts[0] += 1;
}
}
- // fix counts[0] if it was skipped in out-of-bounds cases (rare)
- // But actually we should just ensure it's correct.
return Self::Heterogeneous(Box::new(HeterogeneousPaletteData {
- storage: PaletteStorage::Indexed(indices),
+ storage: PaletteStorage::Indexed(PackedIndices::from_slice(
+ indices.as_flattened().as_flattened(),
+ palette.len(),
+ )),
palette: palette.to_vec(),
counts,
}));
@@ -459,13 +517,9 @@ impl<V: Hash + Eq + Copy + Default, const DIM: usize> PalettedContainer<V, DIM>
PaletteStorage::Dense(cube) => {
Box::new(cube.as_flattened().as_flattened().iter().copied())
}
- PaletteStorage::Indexed(indices) => Box::new(
- indices
- .as_flattened()
- .as_flattened()
- .iter()
- .map(|&idx| data.palette[idx as usize]),
- ),
+ PaletteStorage::Indexed(indices) => {
+ Box::new((0..indices.len).map(move |i| data.palette[indices.get(i) as usize]))
+ }
},
}
}
@@ -494,13 +548,9 @@ impl<'a, V: Hash + Eq + Copy + Default, const DIM: usize> IntoIterator
PaletteStorage::Dense(cube) => {
Box::new(cube.as_flattened().as_flattened().iter().copied())
}
- PaletteStorage::Indexed(indices) => Box::new(
- indices
- .as_flattened()
- .as_flattened()
- .iter()
- .map(|&idx| data.palette[idx as usize]),
- ),
+ PaletteStorage::Indexed(indices) => {
+ Box::new((0..indices.len).map(move |i| data.palette[indices.get(i) as usize]))
+ }
},
}
}
@@ -1004,7 +1054,7 @@ pub(crate) const BIOME_NETWORK_MAX_BITS: u8 = 7;
#[cfg(test)]
mod tests {
- use super::{BlockPalette, NetworkPalette};
+ use super::{BlockPalette, NetworkPalette, PackedIndices, PaletteStorage, PalettedContainer};
use pumpkin_data::{Block, BlockStateId};
fn network_palette_values(palette: NetworkPalette<u16>) -> Option<Box<[u16]>> {
@@ -1047,6 +1097,65 @@ mod tests {
);
}
+ #[test]
+ fn packed_palette_growth_remapping_and_serialization_preserve_values() {
+ for colors in [2usize, 3, 5, 17, 257] {
+ let mut palette = PalettedContainer::<u16, 16>::from_fn(|x, y, z| {
+ (((y * 16 + z) * 16 + x) % colors) as u16
+ });
+ let mut expected: Vec<u16> = (0..4096).map(|i| (i % colors) as u16).collect();
+ assert_eq!(palette.iter().collect::<Vec<_>>(), expected);
+ if colors <= 256 {
+ let PalettedContainer::Heterogeneous(data) = &palette else {
+ unreachable!()
+ };
+ let PaletteStorage::Indexed(indices) = &data.storage else {
+ unreachable!()
+ };
+ assert_eq!(
+ indices.bytes.len(),
+ 4096 * PackedIndices::width(colors) as usize / 8
+ );
+ }
+ for i in [0, 1, 15, 16, 63, 255, 1024, 4095] {
+ let value = (colors + i % 7) as u16;
+ let old = palette.set(i % 16, i / 256, i / 16 % 16, value);
+ assert_eq!(old, expected[i]);
+ expected[i] = value;
+ }
+ assert_eq!(palette.iter().collect::<Vec<_>>(), expected);
+ let bits = palette.bits_per_entry().max(4);
+ let (keys, words) = palette.to_palette_and_packed_data(bits);
+ let decoded =
+ PalettedContainer::<u16, 16>::from_palette_and_packed_data(&keys, &words, 4);
+ assert_eq!(decoded.iter().collect::<Vec<_>>(), expected);
+ for i in 0..4096 {
+ palette.set(i % 16, i / 256, i / 16 % 16, 7);
+ }
+ assert!(matches!(palette, PalettedContainer::Homogeneous(7)));
+ }
+ }
+
+ #[test]
+ fn packed_indices_expand_across_all_widths() {
+ let mut indices = PackedIndices::new(27, 2);
+ for value in [1, 3, 15, 255] {
+ for i in [0, 1, 7, 8, 26] {
+ indices.set(i, value);
+ }
+ for i in 0..27 {
+ assert_eq!(
+ indices.get(i),
+ if [0, 1, 7, 8, 26].contains(&i) {
+ value
+ } else {
+ 0
+ }
+ );
+ }
+ }
+ }
+
#[test]
fn bulk_palette_matches_individual_mutations() {
let states = [
diff --git a/crates/pumpkin-world/src/generation/carver/mask.rs b/crates/pumpkin-world/src/generation/carver/mask.rs
index f9ccd277..8e47504f 100644
--- a/crates/pumpkin-world/src/generation/carver/mask.rs
+++ b/crates/pumpkin-world/src/generation/carver/mask.rs
@@ -1,6 +1,7 @@
pub struct CarvingMask {
min_y: i32,
mask: Vec<u64>,
+ words: usize,
}
impl CarvingMask {
@@ -11,7 +12,8 @@ impl CarvingMask {
let num_u64s = (total_bits as usize).div_ceil(64);
Self {
min_y,
- mask: vec![0; num_u64s],
+ mask: Vec::new(),
+ words: num_u64s,
}
}
@@ -27,6 +29,14 @@ impl CarvingMask {
let bit_index = self.get_bit_index(x, y, z);
let u64_idx = bit_index / 64;
let bit_in_u64 = bit_index % 64;
+ assert!(
+ u64_idx < self.words,
+ "Carving mask position is outside the chunk"
+ );
+ if u64_idx >= self.mask.len() {
+ self.mask.reserve_exact(u64_idx + 1 - self.mask.len());
+ self.mask.resize(u64_idx + 1, 0);
+ }
self.mask[u64_idx] |= 1 << bit_in_u64;
}
@@ -35,6 +45,38 @@ impl CarvingMask {
let bit_index = self.get_bit_index(x, y, z);
let u64_idx = bit_index / 64;
let bit_in_u64 = bit_index % 64;
- (self.mask[u64_idx] >> bit_in_u64) & 1 != 0
+ assert!(
+ u64_idx < self.words,
+ "Carving mask position is outside the chunk"
+ );
+ self.mask
+ .get(u64_idx)
+ .is_some_and(|word| (word >> bit_in_u64) & 1 != 0)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::CarvingMask;
+
+ #[test]
+ fn uncarved_space_needs_no_backing_array() {
+ let mut mask = CarvingMask::new(384, -64);
+ assert!(!mask.get(0, 319, 0));
+ assert!(mask.mask.is_empty());
+ mask.set(-1, -64, 17);
+ assert!(mask.get(15, -64, 1));
+ assert!(!mask.get(14, -64, 1));
+ assert!(!mask.get(15, 319, 1));
+ assert!(mask.mask.capacity() < mask.words);
+ mask.set(15, 319, 15);
+ assert!(mask.get(15, 319, 15));
+ assert!(mask.get(15, -64, 1));
+ }
+
+ #[test]
+ #[should_panic(expected = "outside the chunk")]
+ fn reads_outside_the_dimension_still_fail() {
+ let _ = CarvingMask::new(384, -64).get(0, -65, 0);
}
}
diff --git a/crates/pumpkin-world/src/generation/feature/features/fossil.rs b/crates/pumpkin-world/src/generation/feature/features/fossil.rs
index 226ee183..0e774e8b 100644
--- a/crates/pumpkin-world/src/generation/feature/features/fossil.rs
+++ b/crates/pumpkin-world/src/generation/feature/features/fossil.rs
@@ -169,7 +169,7 @@ fn place_fossil_template<T: GenerationCache>(
random: &mut RandomGenerator,
placement_box: &BlockBox,
) {
- for block in &template.blocks {
+ for block in template.blocks.iter() {
let local_pos = rotation.transform_pos(block.pos, template.size);
let world_pos = origin + local_pos;
diff --git a/crates/pumpkin-world/src/generation/noise/router/density_volume.rs b/crates/pumpkin-world/src/generation/noise/router/density_volume.rs
index 106a65d5..10f24c74 100644
--- a/crates/pumpkin-world/src/generation/noise/router/density_volume.rs
+++ b/crates/pumpkin-world/src/generation/noise/router/density_volume.rs
@@ -6,9 +6,10 @@ pub use pumpkin_util::noise::volume::DensityVolume;
const BUFFER_SIZE_INCREMENT: usize = 16;
const MAX_REUSE_SIZE_FACTOR: usize = 2;
const MAX_POOLED_BUFFERS: usize = 1024;
+const MAX_POOLED_BYTES: usize = 4 * 1024 * 1024;
thread_local! {
- static DENSITY_BUFFER_POOL: RefCell<Vec<Box<[f32]>>> = const { RefCell::new(Vec::new()) };
+ static DENSITY_BUFFER_POOL: RefCell<BufferPool> = const { RefCell::new(BufferPool { buffers: Vec::new(), bytes: 0 }) };
}
fn take_best(
@@ -31,6 +32,27 @@ fn take_best(
best_index.map(|i| pool.remove(i))
}
+struct BufferPool {
+ buffers: Vec<Box<[f32]>>,
+ bytes: usize,
+}
+
+impl BufferPool {
+ fn take(&mut self, min: usize, max: usize) -> Option<Box<[f32]>> {
+ let buffer = take_best(&mut self.buffers, min, max)?;
+ self.bytes -= std::mem::size_of_val(&*buffer);
+ Some(buffer)
+ }
+
+ fn put(&mut self, buffer: Box<[f32]>) {
+ let bytes = std::mem::size_of_val(&*buffer);
+ if self.buffers.len() < MAX_POOLED_BUFFERS && bytes <= MAX_POOLED_BYTES - self.bytes {
+ self.bytes += bytes;
+ self.buffers.push(buffer);
+ }
+ }
+}
+
pub struct DensityBuffer {
values: Box<[f32]>,
len: usize,
@@ -47,11 +69,8 @@ impl DensityBuffer {
let min_capacity = len.next_multiple_of(BUFFER_SIZE_INCREMENT);
let values = DENSITY_BUFFER_POOL
.with(|pool| {
- take_best(
- &mut pool.borrow_mut(),
- min_capacity,
- min_capacity * MAX_REUSE_SIZE_FACTOR,
- )
+ pool.borrow_mut()
+ .take(min_capacity, min_capacity * MAX_REUSE_SIZE_FACTOR)
})
.unwrap_or_else(|| vec![0.0; min_capacity].into_boxed_slice());
Self { values, len }
@@ -83,10 +102,43 @@ impl Drop for DensityBuffer {
fn drop(&mut self) {
let values = std::mem::take(&mut self.values);
DENSITY_BUFFER_POOL.with(|pool| {
- let mut pool = pool.borrow_mut();
- if pool.len() < MAX_POOLED_BUFFERS {
- pool.push(values);
- }
+ pool.borrow_mut().put(values);
});
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn retained_buffers_obey_byte_budget_and_return_credit_on_reuse() {
+ let mut pool = BufferPool {
+ buffers: Vec::new(),
+ bytes: 0,
+ };
+ let len = MAX_POOLED_BYTES / std::mem::size_of::<f32>();
+ pool.put(vec![7.0; len].into_boxed_slice());
+ pool.put(vec![0.0; 16].into_boxed_slice());
+ assert_eq!(pool.buffers.len(), 1);
+ assert_eq!(pool.bytes, MAX_POOLED_BYTES);
+ assert!(pool.take(16, 32).is_none());
+ assert_eq!(pool.bytes, MAX_POOLED_BYTES);
+ let buffer = pool.take(len, len).unwrap();
+ assert_eq!(pool.bytes, 0);
+ assert!(buffer.iter().all(|&value| value == 7.0));
+ pool.put(buffer);
+ assert_eq!(pool.bytes, MAX_POOLED_BYTES);
+ }
+
+ #[test]
+ fn oversized_buffers_are_not_retained() {
+ let mut pool = BufferPool {
+ buffers: Vec::new(),
+ bytes: 0,
+ };
+ pool.put(vec![0.0; MAX_POOLED_BYTES / 4 + 16].into_boxed_slice());
+ assert!(pool.buffers.is_empty());
+ assert_eq!(pool.bytes, 0);
+ }
+}
diff --git a/crates/pumpkin-world/src/generation/proto_chunk.rs b/crates/pumpkin-world/src/generation/proto_chunk.rs
index 727a58a3..cc4c8e77 100644
--- a/crates/pumpkin-world/src/generation/proto_chunk.rs
+++ b/crates/pumpkin-world/src/generation/proto_chunk.rs
@@ -38,6 +38,7 @@ use super::{
};
use crate::biome::{BiomeSupplier, MultiNoiseBiomeSupplier, end::TheEndBiomeSupplier};
use crate::chunk::format::LightContainer;
+use crate::chunk::palette::BlockPalette;
use crate::chunk::{ChunkData, ChunkHeightmapType, ChunkLight};
use crate::chunk_system::{StagedChunkEnum, generation_cache::SurfaceBiomeNeighborhood};
use crate::generation::height_limit::HeightLimitView;
@@ -138,7 +139,12 @@ pub struct ProtoChunk {
pub z: i32,
pub default_block: &'static BlockState,
biome_mixer_seed: i64,
- pub(crate) flat_block_map: Box<[BlockStateId]>,
+ // Generation retains many surrounding chunks. Keep untouched sections
+ // uniform and use the same indexed storage as finished chunks.
+ block_sections: Box<[BlockPalette]>,
+ // Only the active noise pass uses a dense scratch buffer. Palette mutation
+ // bookkeeping is expensive when writing every voxel in a chunk.
+ noise_blocks: Option<Box<[BlockStateId]>>,
pub flat_biome_map: Box<[u8]>,
pub flat_surface_height_map: [i16; CHUNK_AREA],
pub flat_ocean_floor_height_map: [i16; CHUNK_AREA],
@@ -235,8 +241,9 @@ impl ProtoChunk {
z,
default_block,
biome_mixer_seed,
- flat_block_map: vec![BlockStateId::AIR; CHUNK_AREA * height as usize]
+ block_sections: vec![BlockPalette::Homogeneous(BlockStateId::AIR); section_count]
.into_boxed_slice(),
+ noise_blocks: None,
flat_biome_map: vec![
Biome::PLAINS.id;
biome_coords::from_block(CHUNK_DIM as i32) as usize
@@ -506,13 +513,6 @@ impl ProtoChunk {
x as usize * CHUNK_DIM as usize + z as usize
}
- #[inline]
- const fn local_pos_to_block_index(&self, x: i32, y: i32, z: i32) -> usize {
- self.height() as usize * CHUNK_DIM as usize * x as usize
- + CHUNK_DIM as usize * y as usize
- + z as usize
- }
-
#[inline]
#[must_use]
pub const fn local_biome_pos_to_biome_index(&self, x: i32, y: i32, z: i32) -> usize {
@@ -531,8 +531,10 @@ impl ProtoChunk {
#[inline]
#[must_use]
pub fn get_block_state_raw(&self, x: i32, y: i32, z: i32) -> BlockStateId {
- let index = self.local_pos_to_block_index(x, y, z);
- self.flat_block_map[index]
+ if let Some(blocks) = &self.noise_blocks {
+ return blocks[(x as usize * self.height as usize + y as usize) * 16 + z as usize];
+ }
+ self.block_sections[y as usize / 16].get(x as usize, y as usize & 15, z as usize)
}
#[inline]
@@ -573,8 +575,17 @@ impl ProtoChunk {
}
}
- let index = self.local_pos_to_block_index(local_x, local_y, local_z);
- self.flat_block_map[index] = block_state.id;
+ if let Some(blocks) = &mut self.noise_blocks {
+ blocks[(local_x as usize * self.height as usize + local_y as usize) * 16
+ + local_z as usize] = block_state.id;
+ } else {
+ self.block_sections[local_y as usize / 16].set(
+ local_x as usize,
+ local_y as usize & 15,
+ local_z as usize,
+ block_state.id,
+ );
+ }
}
#[inline]
@@ -869,6 +880,18 @@ impl ProtoChunk {
let volume = *noise_sampler.volume();
let densities = noise_sampler.sample_density();
+ let height = self.height as usize;
+ let mut blocks = vec![BlockStateId::AIR; CHUNK_AREA * height];
+ for x in 0..16 {
+ for y in 0..height {
+ for z in 0..16 {
+ blocks[(x * height + y) * 16 + z] =
+ self.get_block_state_raw(x as i32, y as i32, z as i32);
+ }
+ }
+ }
+ self.noise_blocks = Some(blocks.into_boxed_slice());
+
for z in 0..volume.size_z {
let block_z = volume.block_z(z);
for x in 0..volume.size_x {
@@ -889,6 +912,11 @@ impl ProtoChunk {
}
}
}
+ let blocks = self.noise_blocks.take().unwrap();
+ for (section, palette) in self.block_sections.iter_mut().enumerate() {
+ *palette =
+ BlockPalette::from_fn(|x, y, z| blocks[(x * height + section * 16 + y) * 16 + z]);
+ }
}
pub fn spawn_mobs<T: GenerationCache>(cache: &mut T, block_registry: &dyn WorldPortalExt) {
diff --git a/crates/pumpkin-world/src/generation/structure/placement.rs b/crates/pumpkin-world/src/generation/structure/placement.rs
index 250263ff..c96f1ad3 100644
--- a/crates/pumpkin-world/src/generation/structure/placement.rs
+++ b/crates/pumpkin-world/src/generation/structure/placement.rs
@@ -10,7 +10,8 @@ use pumpkin_util::{
},
};
use std::f64::consts::PI;
-use std::sync::OnceLock;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, OnceLock};
use crate::ProtoChunk;
use dashmap::DashMap;
@@ -31,6 +32,7 @@ pub struct GlobalStructureCache {
/// world seed, so it is computed once here instead of being recomputed for every
/// surrounding chunk whose structure references overlap it.
structure_starts: OnceLock<DashMap<(StructureKeys, i32, i32), Option<StructurePosition>>>,
+ inserted_starts: AtomicUsize,
}
impl GlobalStructureCache {
/// Creates a new, empty global structure cache.
@@ -39,6 +41,7 @@ impl GlobalStructureCache {
Self {
stronghold_chunks: OnceLock::new(),
structure_starts: OnceLock::new(),
+ inserted_starts: AtomicUsize::new(0),
}
}
@@ -66,8 +69,29 @@ impl GlobalStructureCache {
return cached.value().clone();
}
let computed = compute();
- cache.insert((key, chunk_x, chunk_z), computed.clone());
- computed
+ // Concurrent requests must share the same collector: generation deduplicates
+ // structure references by Arc identity.
+ let result = cache
+ .entry((key, chunk_x, chunk_z))
+ .or_insert(computed)
+ .clone();
+ if self.inserted_starts.fetch_add(1, Ordering::Relaxed) % 256 == 255 && cache.len() > 2048 {
+ self.evict_unused_starts();
+ }
+ result
+ }
+
+ fn evict_unused_starts(&self) {
+ if let Some(cache) = self.structure_starts.get() {
+ // Active generation keeps its own Arc. Never replace a collector that
+ // another chunk can still use; idle placements can be recomputed from
+ // their world seed and start coordinates.
+ cache.retain(|_, position| {
+ position
+ .as_ref()
+ .is_some_and(|position| Arc::strong_count(&position.collector) > 1)
+ });
+ }
}
/// Retrieves the list of chunk coordinates for Concentric Ring structures.
@@ -450,3 +474,77 @@ mod tests {
));
}
}
+
+#[cfg(test)]
+mod cache_tests {
+ use super::*;
+ use crate::generation::structure::structures::StructurePiecesCollector;
+ use pumpkin_util::math::position::BlockPos;
+ use std::sync::Mutex;
+
+ fn position() -> StructurePosition {
+ StructurePosition {
+ start_pos: BlockPos::new(1, 2, 3),
+ collector: Arc::new(Mutex::new(StructurePiecesCollector::new())),
+ }
+ }
+
+ #[test]
+ fn exploration_releases_idle_entries_but_preserves_active_collectors() {
+ let cache = GlobalStructureCache::new();
+ let active = cache
+ .get_or_compute_structure_start(StructureKeys::Monument, -1, -1, || Some(position()))
+ .unwrap();
+ for x in 0..10_000 {
+ assert!(
+ cache
+ .get_or_compute_structure_start(StructureKeys::Monument, x, 0, || None)
+ .is_none()
+ );
+ }
+ assert!(cache.structure_starts.get().unwrap().len() <= 2304);
+ cache.evict_unused_starts();
+ let reused = cache
+ .get_or_compute_structure_start(StructureKeys::Monument, -1, -1, || {
+ panic!("active collector was evicted")
+ })
+ .unwrap();
+ assert!(Arc::ptr_eq(&active.collector, &reused.collector));
+ drop(reused);
+ drop(active);
+ cache.evict_unused_starts();
+ assert!(cache.structure_starts.get().unwrap().is_empty());
+ let rebuilt = cache
+ .get_or_compute_structure_start(StructureKeys::Monument, -1, -1, || Some(position()))
+ .unwrap();
+ assert_eq!(rebuilt.start_pos, BlockPos::new(1, 2, 3));
+ }
+
+ #[test]
+ fn concurrent_misses_return_one_canonical_collector() {
+ let cache = GlobalStructureCache::new();
+ let barrier = std::sync::Barrier::new(2);
+ std::thread::scope(|scope| {
+ let a = scope.spawn(|| {
+ cache
+ .get_or_compute_structure_start(StructureKeys::Monument, 0, 0, || {
+ barrier.wait();
+ Some(position())
+ })
+ .unwrap()
+ });
+ let b = scope.spawn(|| {
+ cache
+ .get_or_compute_structure_start(StructureKeys::Monument, 0, 0, || {
+ barrier.wait();
+ Some(position())
+ })
+ .unwrap()
+ });
+ assert!(Arc::ptr_eq(
+ &a.join().unwrap().collector,
+ &b.join().unwrap().collector
+ ));
+ });
+ }
+}
diff --git a/crates/pumpkin-world/src/generation/structure/structures/end_city/layout.rs b/crates/pumpkin-world/src/generation/structure/structures/end_city/layout.rs
index a7f29d8d..ca0dc47d 100644
--- a/crates/pumpkin-world/src/generation/structure/structures/end_city/layout.rs
+++ b/crates/pumpkin-world/src/generation/structure/structures/end_city/layout.rs
@@ -663,7 +663,7 @@ mod tests {
"tower_top",
] {
let template = get_template(&format!("end_city/{name}")).unwrap();
- for palette in &template.palette {
+ for palette in template.palette.iter() {
for rotation in [
Rotation::None,
Rotation::Clockwise90,
diff --git a/crates/pumpkin-world/src/generation/structure/structures/end_city/mod.rs b/crates/pumpkin-world/src/generation/structure/structures/end_city/mod.rs
index 8089b3e6..9bb82ed9 100644
--- a/crates/pumpkin-world/src/generation/structure/structures/end_city/mod.rs
+++ b/crates/pumpkin-world/src/generation/structure/structures/end_city/mod.rs
@@ -98,7 +98,7 @@ impl EndCityTemplatePiece {
random: &mut RandomGenerator,
chunk_box: &BlockBox,
) {
- for block in &self.descriptor.template.blocks {
+ for block in self.descriptor.template.blocks.iter() {
let palette = &self.descriptor.template.palette[block.state as usize];
if matches!(
palette.name.as_str(),
@@ -117,10 +117,10 @@ impl EndCityTemplatePiece {
continue;
};
chunk.set_block_state(position.x, position.y, position.z, state);
- Self::place_block_entity(chunk, palette, block.nbt.as_ref(), position, random);
+ Self::place_block_entity(chunk, palette, block.nbt.as_deref(), position, random);
}
- for block in &self.descriptor.template.blocks {
+ for block in self.descriptor.template.blocks.iter() {
let palette = &self.descriptor.template.palette[block.state as usize];
if palette.name != "minecraft:structure_block" {
continue;
diff --git a/crates/pumpkin-world/src/generation/structure/structures/igloo.rs b/crates/pumpkin-world/src/generation/structure/structures/igloo.rs
index 9130b462..36399302 100644
--- a/crates/pumpkin-world/src/generation/structure/structures/igloo.rs
+++ b/crates/pumpkin-world/src/generation/structure/structures/igloo.rs
@@ -190,7 +190,7 @@ impl IglooPiece {
&mut context_rng,
);
- for block in &self.template.blocks {
+ for block in self.template.blocks.iter() {
let palette_entry = &self.template.palette[block.state as usize];
let local_pos =
@@ -226,7 +226,7 @@ impl IglooPiece {
continue;
}
- let mut block_entity_nbt = block.nbt.clone();
+ let mut block_entity_nbt = block.nbt.as_deref().cloned();
let placed_entry = palette_entry.clone();
let Some(state) = BlockStateResolver::resolve(&placed_entry, rotation, mirror) else {