1use super::{BlockKind, SpriteCfg, StructureSprite};
2use crate::{
3 assets::{self, AssetCache, AssetExt, AssetHandle, BoxedError, DotVox, Ron, SharedString},
4 make_case_elim,
5 vol::{BaseVol, ReadVol, SizedVol, WriteVol},
6 volumes::dyna::{Dyna, DynaError},
7};
8use common_i18n::Content;
9use dot_vox::DotVoxData;
10use hashbrown::HashMap;
11use serde::Deserialize;
12use std::{num::NonZeroU8, sync::Arc};
13use vek::*;
14
15make_case_elim!(
16 structure_block,
17 #[derive(Clone, Debug, Deserialize)]
18 #[repr(u8)]
19 pub enum StructureBlock {
20 None = 0,
21 Grass = 1,
22 TemperateLeaves = 2,
23 PineLeaves = 3,
24 Acacia = 4,
25 Mangrove = 5,
26 PalmLeavesInner = 6,
27 PalmLeavesOuter = 7,
28 Water = 8,
29 GreenSludge = 9,
30 Fruit = 10,
31 Coconut = 11,
32 MaybeChest = 12,
33 Hollow = 13,
34 Liana = 14,
35 Normal(color: Rgb<u8>) = 15,
36 Log = 16,
37 Filled(kind: BlockKind, color: Rgb<u8>) = 17,
38 Sprite(sprite: StructureSprite) = 18,
39 Chestnut = 19,
40 Baobab = 20,
41 BirchWood = 21,
42 FrostpineLeaves = 22,
43 EntitySpawner(entitykind: String, spawn_chance: f32) = 24,
46 Keyhole(consumes: String) = 25,
48 BoneKeyhole(consumes: String) = 26,
49 GlassKeyhole(consumes: String) = 27,
50 Sign(content: Content, ori: u8) = 28,
51 KeyholeBars(consumes: String) = 29,
52 HaniwaKeyhole(consumes: String) = 30,
53 TerracottaKeyhole(consumes: String) = 31,
54 SahaginKeyhole(consumes: String) = 32,
55 VampireKeyhole(consumes: String) = 33,
56 MyrmidonKeyhole(consumes: String) = 34,
57 MinotaurKeyhole(consumes: String) = 35,
58 MapleLeaves = 36,
59 CherryLeaves = 37,
60 AutumnLeaves = 38,
61 RedwoodWood = 39,
62 SpriteWithCfg(sprite: StructureSprite, sprite_cfg: SpriteCfg) = 40,
63 Choice(block_table: Vec<(f32, StructureBlock)>) = 41,
64 }
65);
66
67#[expect(clippy::derivable_impls)]
69impl Default for StructureBlock {
70 fn default() -> Self { StructureBlock::None }
71}
72
73#[derive(Debug)]
74pub enum StructureError {
75 OutOfBounds,
76}
77
78#[derive(Clone, Debug)]
79pub struct Structure {
80 center: Vec3<i32>,
81 base: Arc<BaseStructure<StructureBlock>>,
82 custom_indices: [Option<StructureBlock>; 256],
83}
84
85#[derive(Debug)]
86pub(crate) struct BaseStructure<B> {
87 pub(crate) vol: Dyna<Option<NonZeroU8>, ()>,
88 pub(crate) palette: [B; 256],
89}
90
91pub struct StructuresGroup(Vec<Structure>);
92
93impl std::ops::Deref for StructuresGroup {
94 type Target = [Structure];
95
96 fn deref(&self) -> &[Structure] { &self.0 }
97}
98
99impl assets::Asset for StructuresGroup {
100 fn load(cache: &AssetCache, specifier: &SharedString) -> Result<Self, BoxedError> {
101 let specs = cache.load::<Ron<Vec<StructureSpec>>>(specifier)?.read();
102
103 Ok(StructuresGroup(
104 specs
105 .0
106 .iter()
107 .map(|sp| {
108 let base = cache
109 .load::<Arc<BaseStructure<StructureBlock>>>(&sp.specifier)?
110 .cloned();
111 Ok(Structure {
112 center: Vec3::from(sp.center),
113 base,
114 custom_indices: {
115 let mut indices = std::array::from_fn(|_| None);
116 for (&idx, custom) in default_custom_indices()
117 .iter()
118 .chain(sp.custom_indices.iter())
119 {
120 indices[idx as usize] = Some(custom.clone());
121 }
122 indices
123 },
124 })
125 })
126 .collect::<Result<_, BoxedError>>()?,
127 ))
128 }
129}
130
131const STRUCTURE_MANIFESTS_DIR: &str = "world.manifests";
132impl Structure {
133 pub fn load_group(specifier: &str) -> AssetHandle<StructuresGroup> {
134 StructuresGroup::load_expect(&format!("{STRUCTURE_MANIFESTS_DIR}.{specifier}"))
135 }
136
137 #[must_use]
138 pub fn with_center(mut self, center: Vec3<i32>) -> Self {
139 self.center = center;
140 self
141 }
142
143 pub fn get_bounds(&self) -> Aabb<i32> {
144 Aabb {
145 min: -self.center,
146 max: self.base.vol.size().map(|e| e as i32) - self.center,
147 }
148 }
149}
150
151impl BaseVol for Structure {
152 type Error = StructureError;
153 type Vox = StructureBlock;
154}
155
156impl ReadVol for Structure {
157 #[inline(always)]
158 fn get(&self, pos: Vec3<i32>) -> Result<&Self::Vox, StructureError> {
159 match self.base.vol.get(pos + self.center) {
160 Ok(None) => Ok(&StructureBlock::None),
161 Ok(Some(index)) => match &self.custom_indices[index.get() as usize] {
162 Some(sb) => Ok(sb),
163 None => Ok(&self.base.palette[index.get() as usize]),
164 },
165 Err(DynaError::OutOfBounds) => Err(StructureError::OutOfBounds),
166 }
167 }
168}
169
170pub(crate) fn load_base_structure<B: Default>(
171 dot_vox_data: &DotVoxData,
172 mut to_block: impl FnMut(Rgb<u8>) -> B,
173) -> BaseStructure<B> {
174 let mut palette = std::array::from_fn(|_| B::default());
175 if let Some(model) = dot_vox_data.models.first() {
176 for (i, col) in dot_vox_data
177 .palette
178 .iter()
179 .map(|col| Rgb::new(col.r, col.g, col.b))
180 .enumerate()
181 {
182 palette[(i + 1).min(255)] = to_block(col);
183 }
184
185 let mut vol = Dyna::filled(
186 Vec3::new(model.size.x, model.size.y, model.size.z),
187 None,
188 (),
189 );
190
191 for voxel in &model.voxels {
192 let _ = vol.set(
193 Vec3::new(voxel.x, voxel.y, voxel.z).map(i32::from),
194 Some(NonZeroU8::new(voxel.i + 1).unwrap()),
195 );
196 }
197
198 BaseStructure { vol, palette }
199 } else {
200 BaseStructure {
201 vol: Dyna::filled(Vec3::zero(), None, ()),
202 palette,
203 }
204 }
205}
206
207impl assets::Asset for BaseStructure<StructureBlock> {
208 fn load(cache: &AssetCache, specifier: &SharedString) -> Result<Self, BoxedError> {
209 let dot_vox_data = cache.load::<DotVox>(specifier)?.read();
210 let dot_vox_data = &dot_vox_data.0;
211
212 Ok(load_base_structure(dot_vox_data, |col| {
213 StructureBlock::Filled(BlockKind::Misc, col)
214 }))
215 }
216}
217
218#[derive(Clone, Deserialize)]
219struct StructureSpec {
220 specifier: String,
221 center: [i32; 3],
222 #[serde(default)]
223 custom_indices: HashMap<u8, StructureBlock>,
224}
225
226fn default_custom_indices() -> HashMap<u8, StructureBlock> {
227 let blocks: [_; 16] = [
228 Some(StructureBlock::TemperateLeaves),
229 Some(StructureBlock::PineLeaves),
230 None,
231 Some(StructureBlock::Water),
232 Some(StructureBlock::Acacia),
233 Some(StructureBlock::Mangrove),
234 Some(StructureBlock::GreenSludge),
235 Some(StructureBlock::Fruit),
236 Some(StructureBlock::Grass),
237 Some(StructureBlock::Liana),
238 Some(StructureBlock::MaybeChest),
239 Some(StructureBlock::Coconut),
240 None,
241 Some(StructureBlock::PalmLeavesOuter),
242 Some(StructureBlock::PalmLeavesInner),
243 Some(StructureBlock::Hollow),
244 ];
245
246 blocks
247 .iter()
248 .enumerate()
249 .filter_map(|(i, sb)| sb.as_ref().map(|sb| (i as u8 + 1, sb.clone())))
250 .collect()
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
256 use crate::{
257 assets,
258 generation::tests::validate_entity_config,
259 lottery::{LootSpec, tests::validate_loot_spec},
260 terrain::Block,
261 };
262
263 pub fn validate_sprite_and_cfg(sprite: StructureSprite, sprite_cfg: &SpriteCfg) {
264 let sprite = sprite
265 .apply_to_block(Block::empty())
266 .unwrap()
267 .get_sprite()
268 .expect("This should have the sprite");
269
270 let SpriteCfg {
271 unlock: _,
273 content: _,
275 loot_table,
276 } = sprite_cfg;
277
278 if let Some(loot_table) = loot_table.clone() {
279 if !sprite.is_defined_as_container() {
280 panic!(
281 r"
282Manifest contains a structure block with custom loot table for a sprite
283that isn't defined as container, you probably don't want that.
284
285If you want, add this sprite to `is_defined_as_container` list.
286Sprite in question: {sprite:?}
287"
288 );
289 }
290
291 validate_loot_spec(&LootSpec::LootTable(loot_table))
292 }
293 }
294
295 pub fn validate_choice_block(_chosen_block: &[(f32, StructureBlock)]) {
296 }
298
299 fn validate_structure_block(sb: &StructureBlock, id: &str) {
300 match sb {
301 StructureBlock::SpriteWithCfg(sprite, sprite_cfg) => {
302 std::panic::catch_unwind(|| validate_sprite_and_cfg(*sprite, sprite_cfg))
303 .unwrap_or_else(|_| {
304 panic!("failed to load structure_block in: {id}\n{sb:?}");
305 })
306 },
307 StructureBlock::EntitySpawner(entity_kind, _spawn_chance) => {
308 let config = &entity_kind;
309 std::panic::catch_unwind(|| validate_entity_config(config)).unwrap_or_else(|_| {
310 panic!("failed to load structure_block in: {id}\n{sb:?}");
311 })
312 },
313 StructureBlock::Choice(choice_block) => {
314 std::panic::catch_unwind(|| validate_choice_block(choice_block)).unwrap_or_else(
315 |_| {
316 panic!("failed to load structure_block in: {id}\n{sb:?}");
317 },
318 )
319 },
320 StructureBlock::None
322 | StructureBlock::Grass
323 | StructureBlock::TemperateLeaves
324 | StructureBlock::PineLeaves
325 | StructureBlock::Acacia
326 | StructureBlock::Mangrove
327 | StructureBlock::PalmLeavesInner
328 | StructureBlock::PalmLeavesOuter
329 | StructureBlock::Water
330 | StructureBlock::GreenSludge
331 | StructureBlock::Fruit
332 | StructureBlock::Coconut
333 | StructureBlock::MaybeChest
334 | StructureBlock::Hollow
335 | StructureBlock::Liana
336 | StructureBlock::Normal { .. }
337 | StructureBlock::Log
338 | StructureBlock::Filled { .. }
339 | StructureBlock::Sprite { .. }
340 | StructureBlock::Chestnut
341 | StructureBlock::Baobab
342 | StructureBlock::BirchWood
343 | StructureBlock::FrostpineLeaves
344 | StructureBlock::MapleLeaves
345 | StructureBlock::CherryLeaves
346 | StructureBlock::RedwoodWood
347 | StructureBlock::AutumnLeaves => {},
348 StructureBlock::Keyhole { .. }
350 | StructureBlock::MyrmidonKeyhole { .. }
351 | StructureBlock::MinotaurKeyhole { .. }
352 | StructureBlock::SahaginKeyhole { .. }
353 | StructureBlock::VampireKeyhole { .. }
354 | StructureBlock::BoneKeyhole { .. }
355 | StructureBlock::GlassKeyhole { .. }
356 | StructureBlock::KeyholeBars { .. }
357 | StructureBlock::HaniwaKeyhole { .. }
358 | StructureBlock::TerracottaKeyhole { .. } => {},
359 StructureBlock::Sign { .. } => {},
361 }
362 }
363
364 #[test]
365 fn test_structure_manifests() {
366 let specs =
367 assets::load_rec_dir::<Ron<Vec<StructureSpec>>>(STRUCTURE_MANIFESTS_DIR).unwrap();
368 for id in specs.read().ids() {
369 if id != "world.manifests.spots" {
371 let group = Ron::<Vec<StructureSpec>>::load(id).unwrap_or_else(|e| {
372 panic!("failed to load: {id}\n{e:?}");
373 });
374 let group = group.read();
375 for StructureSpec {
376 specifier,
377 center: _center,
378 custom_indices,
379 } in &group.0
380 {
381 BaseStructure::<StructureBlock>::load(specifier).unwrap_or_else(|e| {
382 panic!("failed to load specifier for: {id}\n{e:?}");
383 });
384
385 for sb in custom_indices.values() {
386 validate_structure_block(sb, id);
387 }
388 }
389 }
390 }
391 }
392}