1use super::{
2 SpriteKind,
3 sprite::{self, RelativeNeighborPosition},
4};
5use crate::{
6 comp::{fluid_dynamics::LiquidKind, tool::ToolKind},
7 consts::FRIC_GROUND,
8 lottery::LootSpec,
9 make_case_elim, rtsim,
10 vol::FilledVox,
11};
12use num_derive::FromPrimitive;
13use num_traits::FromPrimitive;
14use serde::{Deserialize, Serialize};
15use std::ops::Deref;
16use strum::{Display, EnumIter, EnumString};
17use vek::*;
18
19make_case_elim!(
20 block_kind,
21 #[derive(
22 Copy,
23 Clone,
24 Debug,
25 Hash,
26 Eq,
27 PartialEq,
28 Serialize,
29 Deserialize,
30 FromPrimitive,
31 EnumString,
32 EnumIter,
33 Display,
34 )]
35 #[repr(u8)]
36 pub enum BlockKind {
37 Air = 0x00, Water = 0x01,
39 Rock = 0x10,
44 WeakRock = 0x11, Lava = 0x12, GlowingRock = 0x13,
47 GlowingWeakRock = 0x14,
48 Grass = 0x20, Snow = 0x21,
51 ArtSnow = 0x22,
53 Earth = 0x30,
55 Sand = 0x31,
56 Wood = 0x40,
58 Leaves = 0x41,
59 GlowingMushroom = 0x42,
60 Ice = 0x43,
61 ArtLeaves = 0x44,
62 Misc = 0xFE,
67 }
68);
69
70impl BlockKind {
71 #[inline]
72 pub const fn is_air(&self) -> bool { matches!(self, BlockKind::Air) }
73
74 #[inline]
78 pub const fn is_fluid(&self) -> bool { *self as u8 & 0xF0 == 0x00 }
79
80 #[inline]
81 pub const fn is_liquid(&self) -> bool { self.is_fluid() && !self.is_air() }
82
83 #[inline]
84 pub const fn liquid_kind(&self) -> Option<LiquidKind> {
85 Some(match self {
86 BlockKind::Water => LiquidKind::Water,
87 BlockKind::Lava => LiquidKind::Lava,
88 _ => return None,
89 })
90 }
91
92 #[inline]
95 pub const fn is_filled(&self) -> bool { !self.is_fluid() }
96
97 #[inline]
100 pub const fn has_color(&self) -> bool { self.is_filled() }
101
102 #[inline]
107 pub const fn is_terrain(&self) -> bool {
108 matches!(
109 self,
110 BlockKind::Rock
111 | BlockKind::WeakRock
112 | BlockKind::GlowingRock
113 | BlockKind::GlowingWeakRock
114 | BlockKind::Grass
115 | BlockKind::Earth
116 | BlockKind::Sand
117 )
118 }
119}
120
121#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
141pub struct Block {
142 kind: BlockKind,
143 data: [u8; 3],
144}
145
146impl FilledVox for Block {
147 fn default_non_filled() -> Self { Block::air(SpriteKind::Empty) }
148
149 fn is_filled(&self) -> bool { self.kind.is_filled() }
150}
151
152impl Deref for Block {
153 type Target = BlockKind;
154
155 fn deref(&self) -> &Self::Target { &self.kind }
156}
157
158impl Block {
159 pub const MAX_HEIGHT: f32 = 3.0;
160
161 #[inline]
164 pub const fn from_raw(kind: BlockKind, data: [u8; 3]) -> Self { Self { kind, data } }
165
166 #[inline]
168 #[track_caller]
169 pub const fn new(kind: BlockKind, color: Rgb<u8>) -> Self {
170 if kind.is_filled() {
171 Self::from_raw(kind, [color.r, color.g, color.b])
172 } else {
173 let data = (SpriteKind::Empty as u32).to_be_bytes();
175 Self::from_raw(kind, [data[1], data[2], data[3]])
176 }
177 }
178
179 #[inline]
182 pub fn unfilled(kind: BlockKind, sprite: SpriteKind) -> Self {
183 #[cfg(debug_assertions)]
184 assert!(!kind.is_filled());
185
186 Self::from_raw(kind, sprite.to_initial_bytes())
187 }
188
189 #[inline]
190 pub fn air(sprite: SpriteKind) -> Self { Self::unfilled(BlockKind::Air, sprite) }
191
192 #[inline]
193 pub const fn empty() -> Self {
194 let data = (SpriteKind::Empty as u32).to_be_bytes();
196 Self::from_raw(BlockKind::Air, [data[1], data[2], data[3]])
197 }
198
199 #[inline]
200 pub fn water(sprite: SpriteKind) -> Self { Self::unfilled(BlockKind::Water, sprite) }
201
202 #[inline(always)]
205 pub const fn get_sprite(&self) -> Option<SpriteKind> {
206 if !self.kind.is_filled() {
207 SpriteKind::from_block(*self)
208 } else {
209 None
210 }
211 }
212
213 #[inline(always)]
214 pub(super) const fn sprite_category_byte(&self) -> u8 { self.data[0] }
215
216 #[inline(always)]
217 pub const fn sprite_category(&self) -> Option<sprite::Category> {
218 if self.kind.is_filled() {
219 None
220 } else {
221 sprite::Category::from_block(*self)
222 }
223 }
224
225 #[inline]
227 pub fn with_attr<A: sprite::Attribute>(
228 mut self,
229 attr: A,
230 ) -> Result<Self, sprite::AttributeError<core::convert::Infallible>> {
231 self.set_attr(attr)?;
232 Ok(self)
233 }
234
235 #[inline]
237 pub fn set_attr<A: sprite::Attribute>(
238 &mut self,
239 attr: A,
240 ) -> Result<(), sprite::AttributeError<core::convert::Infallible>> {
241 match self.sprite_category() {
242 Some(category) => category.write_attr(self, attr),
243 None => Err(sprite::AttributeError::NotPresent),
244 }
245 }
246
247 #[inline]
249 pub fn get_attr<A: sprite::Attribute>(&self) -> Result<A, sprite::AttributeError<A::Error>> {
250 match self.sprite_category() {
251 Some(category) => category.read_attr(*self),
252 None => Err(sprite::AttributeError::NotPresent),
253 }
254 }
255
256 pub fn sprite_z_rot(&self) -> Option<f32> {
257 self.get_attr::<sprite::Ori>()
258 .ok()
259 .map(|ori| std::f32::consts::PI * 0.25 * ori.0 as f32)
260 }
261
262 pub fn sprite_mirror_vec(&self) -> Vec3<f32> {
263 Vec3::new(
264 self.get_attr::<sprite::MirrorX>().map(|m| m.0),
265 self.get_attr::<sprite::MirrorY>().map(|m| m.0),
266 self.get_attr::<sprite::MirrorZ>().map(|m| m.0),
267 )
268 .map(|b| match b.unwrap_or(false) {
269 true => -1.0,
270 false => 1.0,
271 })
272 }
273
274 #[inline(always)]
275 pub(super) const fn data(&self) -> [u8; 3] { self.data }
276
277 #[inline(always)]
278 pub(super) const fn with_data(mut self, data: [u8; 3]) -> Self {
279 self.data = data;
280 self
281 }
282
283 #[inline(always)]
284 pub(super) const fn to_be_u32(self) -> u32 {
285 u32::from_be_bytes([self.kind as u8, self.data[0], self.data[1], self.data[2]])
286 }
287
288 #[inline]
289 pub fn get_color(&self) -> Option<Rgb<u8>> {
290 if self.has_color() {
291 Some(self.data.into())
292 } else {
293 None
294 }
295 }
296
297 #[inline]
301 pub fn get_rtsim_resource(&self) -> Option<rtsim::ChunkResource> {
302 match self.get_sprite()? {
303 SpriteKind::Stones => Some(rtsim::ChunkResource::Stone),
304 SpriteKind::Twigs
305 | SpriteKind::Wood
306 | SpriteKind::Bamboo
307 | SpriteKind::Hardwood
308 | SpriteKind::Ironwood
309 | SpriteKind::Frostwood
310 | SpriteKind::Eldwood => Some(rtsim::ChunkResource::Wood),
311 SpriteKind::Amethyst
312 | SpriteKind::Ruby
313 | SpriteKind::Sapphire
314 | SpriteKind::Emerald
315 | SpriteKind::Topaz
316 | SpriteKind::Diamond
317 | SpriteKind::CrystalHigh
318 | SpriteKind::CrystalLow => Some(rtsim::ChunkResource::Gem),
319 SpriteKind::Bloodstone
320 | SpriteKind::Coal
321 | SpriteKind::Cobalt
322 | SpriteKind::Copper
323 | SpriteKind::Iron
324 | SpriteKind::Tin
325 | SpriteKind::Silver
326 | SpriteKind::Gold => Some(rtsim::ChunkResource::Ore),
327
328 SpriteKind::LongGrass
329 | SpriteKind::MediumGrass
330 | SpriteKind::ShortGrass
331 | SpriteKind::LargeGrass
332 | SpriteKind::GrassBlue
333 | SpriteKind::SavannaGrass
334 | SpriteKind::TallSavannaGrass
335 | SpriteKind::RedSavannaGrass
336 | SpriteKind::JungleRedGrass
337 | SpriteKind::Fern => Some(rtsim::ChunkResource::Grass),
338 SpriteKind::BlueFlower
339 | SpriteKind::PinkFlower
340 | SpriteKind::PurpleFlower
341 | SpriteKind::RedFlower
342 | SpriteKind::WhiteFlower
343 | SpriteKind::YellowFlower
344 | SpriteKind::Sunflower
345 | SpriteKind::Moonbell
346 | SpriteKind::Pyrebloom => Some(rtsim::ChunkResource::Flower),
347 SpriteKind::Reed
348 | SpriteKind::Flax
349 | SpriteKind::WildFlax
350 | SpriteKind::Cotton
351 | SpriteKind::Corn
352 | SpriteKind::WheatYellow
353 | SpriteKind::WheatGreen => Some(rtsim::ChunkResource::Plant),
354 SpriteKind::Apple
355 | SpriteKind::Pumpkin
356 | SpriteKind::Beehive | SpriteKind::Coconut => Some(rtsim::ChunkResource::Fruit),
358 SpriteKind::Cabbage
359 | SpriteKind::Carrot
360 | SpriteKind::Tomato
361 | SpriteKind::Radish
362 | SpriteKind::Turnip => Some(rtsim::ChunkResource::Vegetable),
363 SpriteKind::Mushroom
364 | SpriteKind::CaveMushroom
365 | SpriteKind::CeilingMushroom
366 | SpriteKind::RockyMushroom
367 | SpriteKind::LushMushroom
368 | SpriteKind::GlowMushroom => Some(rtsim::ChunkResource::Mushroom),
369
370 SpriteKind::Chest
371 | SpriteKind::ChestBuried
372 | SpriteKind::PotionMinor
373 | SpriteKind::DungeonChest0
374 | SpriteKind::DungeonChest1
375 | SpriteKind::DungeonChest2
376 | SpriteKind::DungeonChest3
377 | SpriteKind::DungeonChest4
378 | SpriteKind::DungeonChest5
379 | SpriteKind::CoralChest
380 | SpriteKind::HaniwaUrn
381 | SpriteKind::TerracottaChest
382 | SpriteKind::SahaginChest
383 | SpriteKind::Crate => Some(rtsim::ChunkResource::Loot),
384 _ => None,
385 }
386 }
387
388 #[inline]
389 pub fn get_glow(&self) -> Option<u8> {
390 let glow_level = match self.kind() {
391 BlockKind::Lava => 24,
392 BlockKind::GlowingRock | BlockKind::GlowingWeakRock => 10,
393 BlockKind::GlowingMushroom => 20,
394 _ => match self.get_sprite()? {
395 SpriteKind::StreetLamp | SpriteKind::StreetLampTall | SpriteKind::BonfireMLit => 24,
396 SpriteKind::Ember | SpriteKind::FireBlock => 20,
397 SpriteKind::WallLamp
398 | SpriteKind::WallLampSmall
399 | SpriteKind::WallLampWizard
400 | SpriteKind::WallLampMesa
401 | SpriteKind::WallSconce
402 | SpriteKind::FireBowlGround
403 | SpriteKind::MesaLantern
404 | SpriteKind::LampTerracotta
405 | SpriteKind::ChristmasOrnament
406 | SpriteKind::CliffDecorBlock
407 | SpriteKind::Orb
408 | SpriteKind::Candle => 16,
409 SpriteKind::DiamondLight => 30,
410 SpriteKind::Velorite
411 | SpriteKind::VeloriteFrag
412 | SpriteKind::GrassBlueShort
413 | SpriteKind::GrassBlueMedium
414 | SpriteKind::GrassBlueLong
415 | SpriteKind::CavernLillypadBlue
416 | SpriteKind::MycelBlue
417 | SpriteKind::Mold
418 | SpriteKind::CeilingMushroom => 6,
419 SpriteKind::CaveMushroom
420 | SpriteKind::GlowMushroom
421 | SpriteKind::CookingPot
422 | SpriteKind::CrystalHigh
423 | SpriteKind::LanternFlower
424 | SpriteKind::CeilingLanternFlower
425 | SpriteKind::LanternPlant
426 | SpriteKind::CeilingLanternPlant
427 | SpriteKind::CrystalLow => 10,
428 SpriteKind::SewerMushroom => 16,
429 SpriteKind::Amethyst
430 | SpriteKind::Ruby
431 | SpriteKind::Sapphire
432 | SpriteKind::Diamond
433 | SpriteKind::Emerald
434 | SpriteKind::Topaz => 3,
435 SpriteKind::Lantern
436 | SpriteKind::LanternpostWoodLantern
437 | SpriteKind::LanternAirshipWallBlackS
438 | SpriteKind::LanternAirshipWallBrownS
439 | SpriteKind::LanternAirshipWallChestnutS
440 | SpriteKind::LanternAirshipWallRedS
441 | SpriteKind::LanternAirshipGroundBlackS
442 | SpriteKind::LanternAirshipGroundBrownS
443 | SpriteKind::LanternAirshipGroundChestnutS
444 | SpriteKind::LanternAirshipGroundRedS
445 | SpriteKind::LampMetalShinglesCyan
446 | SpriteKind::LampMetalShinglesRed => 24,
447 SpriteKind::TerracottaStatue => 8,
448 SpriteKind::SeashellLantern | SpriteKind::GlowIceCrystal => 16,
449 SpriteKind::SeaDecorEmblem => 12,
450 SpriteKind::SeaDecorBlock
451 | SpriteKind::HaniwaKeyDoor
452 | SpriteKind::VampireKeyDoor => 10,
453 _ => return None,
454 },
455 };
456
457 if self
458 .get_attr::<sprite::LightEnabled>()
459 .map_or(true, |l| l.0)
460 {
461 Some(glow_level)
462 } else {
463 None
464 }
465 }
466
467 #[inline]
469 pub fn get_max_sunlight(&self) -> (u8, f32) {
470 match self.kind() {
471 BlockKind::Water => (0, 0.4),
472 BlockKind::Leaves => (9, 255.0),
473 BlockKind::ArtLeaves => (9, 255.0),
474 BlockKind::Wood => (6, 2.0),
475 BlockKind::Snow => (6, 2.0),
476 BlockKind::ArtSnow => (6, 2.0),
477 BlockKind::Ice => (4, 2.0),
478 _ if self.is_opaque() => (0, 255.0),
479 _ => (0, 0.0),
480 }
481 }
482
483 #[inline]
485 pub fn is_solid(&self) -> bool {
486 self.get_sprite()
487 .map(|s| s.solid_height().is_some())
488 .unwrap_or(!matches!(self.kind, BlockKind::Lava))
489 }
490
491 pub fn valid_collision_dir(
492 &self,
493 entity_aabb: Aabb<f32>,
494 block_aabb: Aabb<f32>,
495 move_dir: Vec3<f32>,
496 ) -> bool {
497 self.get_sprite().is_none_or(|sprite| {
498 sprite.valid_collision_dir(entity_aabb, block_aabb, move_dir, self)
499 })
500 }
501
502 #[inline]
506 pub fn explode_power(&self) -> Option<f32> {
507 match self.kind() {
510 BlockKind::Leaves => Some(0.25),
511 BlockKind::ArtLeaves => Some(0.25),
512 BlockKind::Grass => Some(0.5),
513 BlockKind::WeakRock => Some(0.75),
514 BlockKind::Snow => Some(0.1),
515 BlockKind::Ice => Some(0.5),
516 BlockKind::Wood => Some(4.5),
517 BlockKind::Lava => None,
518 _ => self.get_sprite().and_then(|sprite| match sprite {
519 sprite if sprite.is_container() => None,
520 SpriteKind::Keyhole
521 | SpriteKind::KeyDoor
522 | SpriteKind::BoneKeyhole
523 | SpriteKind::BoneKeyDoor
524 | SpriteKind::OneWayWall
525 | SpriteKind::KeyholeBars
526 | SpriteKind::DoorBars => None,
527 SpriteKind::Anvil
528 | SpriteKind::Cauldron
529 | SpriteKind::CookingPot
530 | SpriteKind::CraftingBench
531 | SpriteKind::Forge
532 | SpriteKind::Loom
533 | SpriteKind::SpinningWheel
534 | SpriteKind::DismantlingBench
535 | SpriteKind::RepairBench
536 | SpriteKind::TanningRack
537 | SpriteKind::Chest
538 | SpriteKind::DungeonChest0
539 | SpriteKind::DungeonChest1
540 | SpriteKind::DungeonChest2
541 | SpriteKind::DungeonChest3
542 | SpriteKind::DungeonChest4
543 | SpriteKind::DungeonChest5
544 | SpriteKind::CoralChest
545 | SpriteKind::HaniwaUrn
546 | SpriteKind::HaniwaKeyDoor
547 | SpriteKind::HaniwaKeyhole
548 | SpriteKind::VampireKeyDoor
549 | SpriteKind::VampireKeyhole
550 | SpriteKind::MyrmidonKeyDoor
551 | SpriteKind::MyrmidonKeyhole
552 | SpriteKind::MinotaurKeyhole
553 | SpriteKind::HaniwaTrap
554 | SpriteKind::HaniwaTrapTriggered
555 | SpriteKind::ChestBuried
556 | SpriteKind::TerracottaChest
557 | SpriteKind::SahaginChest
558 | SpriteKind::SeaDecorBlock
559 | SpriteKind::SeaDecorChain
560 | SpriteKind::SeaDecorWindowHor
561 | SpriteKind::SeaDecorWindowVer
562 | SpriteKind::WitchWindow
563 | SpriteKind::Rope
564 | SpriteKind::MetalChain
565 | SpriteKind::IronSpike
566 | SpriteKind::HotSurface
567 | SpriteKind::FireBlock
568 | SpriteKind::GlassBarrier
569 | SpriteKind::GlassKeyhole
570 | SpriteKind::SahaginKeyhole
571 | SpriteKind::SahaginKeyDoor
572 | SpriteKind::TerracottaKeyDoor
573 | SpriteKind::TerracottaKeyhole
574 | SpriteKind::TerracottaStatue
575 | SpriteKind::TerracottaBlock => None,
576 SpriteKind::EnsnaringVines
577 | SpriteKind::EnsnaringWeb
578 | SpriteKind::SeaUrchin
579 | SpriteKind::IceSpike
580 | SpriteKind::DiamondLight => Some(0.1),
581 _ => Some(0.25),
582 }),
583 }
584 }
585
586 #[inline]
587 pub fn collectible_id(&self) -> Option<Option<LootSpec<&'static str>>> {
588 self.get_sprite()
589 .map(|s| s.collectible_id())
590 .unwrap_or(None)
591 }
592
593 #[inline]
594 pub fn is_collectible(&self) -> bool {
595 self.collectible_id().is_some() && self.mine_tool().is_none()
596 }
597
598 #[inline]
599 pub fn is_mountable(&self) -> bool { self.mount_offset().is_some() }
600
601 pub fn mount_offset(&self) -> Option<(Vec3<f32>, Vec3<f32>)> {
603 self.get_sprite().and_then(|sprite| sprite.mount_offset())
604 }
605
606 pub fn is_controller(&self) -> bool {
607 self.get_sprite()
608 .is_some_and(|sprite| sprite.is_controller())
609 }
610
611 #[inline]
612 pub fn is_bonkable(&self) -> bool {
613 match self.get_sprite() {
614 Some(
615 SpriteKind::Apple | SpriteKind::Beehive | SpriteKind::Coconut | SpriteKind::Bomb,
616 ) => self.is_solid(),
617 _ => false,
618 }
619 }
620
621 #[inline]
622 pub fn is_owned(&self) -> bool {
623 self.get_attr::<sprite::Owned>()
624 .is_ok_and(|sprite::Owned(b)| b)
625 }
626
627 #[inline]
630 pub fn mine_tool(&self) -> Option<ToolKind> {
631 match self.kind() {
632 BlockKind::WeakRock | BlockKind::Ice | BlockKind::GlowingWeakRock => {
633 Some(ToolKind::Pick)
634 },
635 _ => self.get_sprite().and_then(|s| s.mine_tool()),
636 }
637 }
638
639 #[inline]
640 pub fn is_opaque(&self) -> bool {
641 match self.get_sprite() {
642 Some(
643 SpriteKind::Keyhole
644 | SpriteKind::KeyDoor
645 | SpriteKind::KeyholeBars
646 | SpriteKind::DoorBars,
647 ) => true,
648 Some(_) => false,
649 None => self.kind().is_filled(),
650 }
651 }
652
653 #[inline]
654 pub fn solid_height(&self) -> f32 {
655 self.get_sprite()
656 .map(|s| s.solid_height().unwrap_or(0.0))
657 .unwrap_or(1.0)
658 }
659
660 #[inline]
663 pub fn get_friction(&self) -> f32 {
664 match self.kind() {
665 BlockKind::Ice => FRIC_GROUND * 0.1,
666 _ => FRIC_GROUND,
667 }
668 }
669
670 #[inline]
676 pub fn get_traction(&self) -> f32 {
677 match self.kind() {
678 BlockKind::Snow | BlockKind::ArtSnow => 0.8,
679 _ => 1.0,
680 }
681 }
682
683 pub fn with_toggle_light(self, enable: bool) -> Option<Self> {
685 self.with_attr(sprite::LightEnabled(enable)).ok()
686 }
687
688 #[inline]
689 pub fn kind(&self) -> BlockKind { self.kind }
690
691 #[inline]
693 #[must_use]
694 pub fn with_data_of(mut self, other: Block) -> Self {
695 if self.is_filled() == other.is_filled() {
696 self = self.with_data(other.data());
697 }
698 self
699 }
700
701 #[inline]
703 #[must_use]
704 pub fn with_sprite(mut self, sprite: SpriteKind) -> Self {
705 if !self.is_filled() {
706 self = Self::unfilled(self.kind, sprite);
707 }
708 self
709 }
710
711 #[inline]
713 #[must_use]
714 pub fn with_ori(self, ori: u8) -> Option<Self> { self.with_attr(sprite::Ori(ori)).ok() }
715
716 #[inline]
718 #[must_use]
719 pub fn with_adjacent_type(self, adj: RelativeNeighborPosition) -> Option<Self> {
720 self.with_attr(sprite::AdjacentType(adj as u8)).ok()
721 }
722
723 #[inline]
725 #[must_use]
726 pub fn into_vacant(self) -> Self {
727 if self.is_fluid() {
728 Block::unfilled(self.kind(), SpriteKind::Empty)
729 } else {
730 Block::air(SpriteKind::Empty)
733 }
734 }
735
736 #[inline]
738 #[must_use]
739 pub fn from_u32(x: u32) -> Option<Self> {
740 let [bk, r, g, b] = x.to_le_bytes();
741 let block = Self {
742 kind: BlockKind::from_u8(bk)?,
743 data: [r, g, b],
744 };
745
746 (block.kind.is_filled() || SpriteKind::from_block(block).is_some()).then_some(block)
747 }
748
749 #[inline]
750 pub fn to_u32(self) -> u32 {
751 u32::from_le_bytes([self.kind as u8, self.data[0], self.data[1], self.data[2]])
752 }
753}
754
755const _: () = assert!(core::mem::size_of::<BlockKind>() == 1);
756const _: () = assert!(core::mem::size_of::<Block>() == 4);