1use std::collections::{BTreeMap, HashMap, HashSet};
45use std::fmt;
46use std::hash::Hash;
47use std::marker::PhantomData;
48
49use bevy::prelude::{App, Plugin, Resource};
50use serde::{Deserialize, Serialize};
51
52#[cfg(feature = "items")]
53use crate::items::{DefaultItem, DropTable, DropTableEntry, ItemType};
54use crate::voxel::{DefaultVoxel, VoxelType};
55
56#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
62pub struct ContentId(String);
63
64impl ContentId {
65 pub fn new(id: impl Into<String>) -> Self {
67 Self(id.into())
68 }
69
70 pub fn as_str(&self) -> &str {
72 &self.0
73 }
74}
75
76impl From<&str> for ContentId {
77 fn from(value: &str) -> Self {
78 Self::new(value)
79 }
80}
81
82impl From<String> for ContentId {
83 fn from(value: String) -> Self {
84 Self::new(value)
85 }
86}
87
88impl AsRef<str> for ContentId {
89 fn as_ref(&self) -> &str {
90 self.as_str()
91 }
92}
93
94impl fmt::Display for ContentId {
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 f.write_str(self.as_str())
97 }
98}
99
100#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
105pub enum ContentValue {
106 Bool(bool),
108 Integer(i64),
110 Float(f64),
112 Text(String),
114 TextList(Vec<String>),
116 NumberList(Vec<f64>),
118 Color([f32; 4]),
120}
121
122impl ContentValue {
123 pub fn strings(values: impl IntoIterator<Item = impl Into<String>>) -> Self {
125 Self::TextList(values.into_iter().map(Into::into).collect())
126 }
127
128 pub fn as_bool(&self) -> Option<bool> {
130 match self {
131 Self::Bool(value) => Some(*value),
132 _ => None,
133 }
134 }
135
136 pub fn as_i64(&self) -> Option<i64> {
138 match self {
139 Self::Integer(value) => Some(*value),
140 _ => None,
141 }
142 }
143
144 pub fn as_f64(&self) -> Option<f64> {
146 match self {
147 Self::Float(value) => Some(*value),
148 _ => None,
149 }
150 }
151
152 pub fn as_number(&self) -> Option<f64> {
154 match self {
155 Self::Integer(value) => Some(*value as f64),
156 Self::Float(value) => Some(*value),
157 _ => None,
158 }
159 }
160
161 pub fn as_str(&self) -> Option<&str> {
163 match self {
164 Self::Text(value) => Some(value.as_str()),
165 _ => None,
166 }
167 }
168
169 pub fn as_text_list(&self) -> Option<&[String]> {
171 match self {
172 Self::TextList(value) => Some(value.as_slice()),
173 _ => None,
174 }
175 }
176
177 pub fn as_number_list(&self) -> Option<&[f64]> {
179 match self {
180 Self::NumberList(value) => Some(value.as_slice()),
181 _ => None,
182 }
183 }
184
185 pub fn as_color(&self) -> Option<[f32; 4]> {
187 match self {
188 Self::Color(value) => Some(*value),
189 _ => None,
190 }
191 }
192}
193
194impl From<bool> for ContentValue {
195 fn from(value: bool) -> Self {
196 Self::Bool(value)
197 }
198}
199
200impl From<i64> for ContentValue {
201 fn from(value: i64) -> Self {
202 Self::Integer(value)
203 }
204}
205
206impl From<i32> for ContentValue {
207 fn from(value: i32) -> Self {
208 Self::Integer(value.into())
209 }
210}
211
212impl From<u32> for ContentValue {
213 fn from(value: u32) -> Self {
214 Self::Integer(value.into())
215 }
216}
217
218impl From<f32> for ContentValue {
219 fn from(value: f32) -> Self {
220 Self::Float(value.into())
221 }
222}
223
224impl From<f64> for ContentValue {
225 fn from(value: f64) -> Self {
226 Self::Float(value)
227 }
228}
229
230impl From<&str> for ContentValue {
231 fn from(value: &str) -> Self {
232 Self::Text(value.to_owned())
233 }
234}
235
236impl From<String> for ContentValue {
237 fn from(value: String) -> Self {
238 Self::Text(value)
239 }
240}
241
242impl From<[f32; 4]> for ContentValue {
243 fn from(value: [f32; 4]) -> Self {
244 Self::Color(value)
245 }
246}
247
248#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
255pub struct BlockEngineProperties {
256 pub emits_mesh: bool,
258 pub collidable: bool,
260 pub opacity: f32,
262 pub color: [f32; 4],
264 pub texture_layers: [u32; 6],
266}
267
268impl BlockEngineProperties {
269 pub fn new(
271 emits_mesh: bool,
272 collidable: bool,
273 opacity: f32,
274 color: [f32; 4],
275 texture_layers: [u32; 6],
276 ) -> Self {
277 Self {
278 emits_mesh,
279 collidable,
280 opacity,
281 color,
282 texture_layers,
283 }
284 }
285
286 pub fn from_voxel<V: VoxelType>(voxel: V) -> Self {
288 Self {
289 emits_mesh: voxel.is_solid(),
290 collidable: voxel.is_solid(),
291 opacity: voxel.alpha(),
292 color: voxel.color(),
293 texture_layers: [
294 voxel.texture_layer(0),
295 voxel.texture_layer(1),
296 voxel.texture_layer(2),
297 voxel.texture_layer(3),
298 voxel.texture_layer(4),
299 voxel.texture_layer(5),
300 ],
301 }
302 }
303
304 pub fn empty() -> Self {
306 Self::new(false, false, 0.0, [0.0, 0.0, 0.0, 0.0], [0; 6])
307 }
308}
309
310#[derive(Debug, Clone, PartialEq)]
312pub struct BlockDefinition<V: VoxelType> {
313 id: ContentId,
314 voxel: V,
315 display_name: String,
316 engine: BlockEngineProperties,
317 attributes: HashMap<String, ContentValue>,
318 tags: HashSet<String>,
319}
320
321#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
327pub struct BlockContentSnapshot {
328 pub id: ContentId,
330 pub display_name: String,
332 pub voxel_byte: u8,
334 pub engine: BlockEngineProperties,
336 pub attributes: BTreeMap<String, ContentValue>,
338 pub tags: Vec<String>,
340}
341
342impl<V: VoxelType> BlockDefinition<V> {
343 pub fn new(id: impl Into<ContentId>, voxel: V) -> Self {
345 Self {
346 id: id.into(),
347 voxel,
348 display_name: voxel.name().to_owned(),
349 engine: BlockEngineProperties::from_voxel(voxel),
350 attributes: HashMap::new(),
351 tags: HashSet::new(),
352 }
353 }
354
355 pub fn id(&self) -> &ContentId {
357 &self.id
358 }
359
360 pub fn voxel(&self) -> V {
362 self.voxel
363 }
364
365 pub fn display_name(&self) -> &str {
367 &self.display_name
368 }
369
370 pub fn named(mut self, name: impl Into<String>) -> Self {
372 self.display_name = name.into();
373 self
374 }
375
376 pub fn engine(&self) -> BlockEngineProperties {
378 self.engine
379 }
380
381 pub fn engine_properties(mut self, engine: BlockEngineProperties) -> Self {
383 self.engine = engine;
384 self
385 }
386
387 pub fn attribute(mut self, key: impl Into<String>, value: impl Into<ContentValue>) -> Self {
389 self.attributes.insert(key.into(), value.into());
390 self
391 }
392
393 pub fn tag(mut self, tag: impl Into<String>) -> Self {
395 self.tags.insert(tag.into());
396 self
397 }
398
399 pub fn get_attribute(&self, key: &str) -> Option<&ContentValue> {
401 self.attributes.get(key)
402 }
403
404 pub fn bool_attribute(&self, key: &str) -> Option<bool> {
406 self.get_attribute(key).and_then(ContentValue::as_bool)
407 }
408
409 pub fn integer_attribute(&self, key: &str) -> Option<i64> {
411 self.get_attribute(key).and_then(ContentValue::as_i64)
412 }
413
414 pub fn number_attribute(&self, key: &str) -> Option<f64> {
418 self.get_attribute(key).and_then(ContentValue::as_number)
419 }
420
421 pub fn text_attribute(&self, key: &str) -> Option<&str> {
423 self.get_attribute(key).and_then(ContentValue::as_str)
424 }
425
426 pub fn text_list_attribute(&self, key: &str) -> Option<&[String]> {
428 self.get_attribute(key).and_then(ContentValue::as_text_list)
429 }
430
431 pub fn number_list_attribute(&self, key: &str) -> Option<&[f64]> {
433 self.get_attribute(key)
434 .and_then(ContentValue::as_number_list)
435 }
436
437 pub fn color_attribute(&self, key: &str) -> Option<[f32; 4]> {
439 self.get_attribute(key).and_then(ContentValue::as_color)
440 }
441
442 pub fn attributes(&self) -> &HashMap<String, ContentValue> {
444 &self.attributes
445 }
446
447 pub fn has_tag(&self, tag: &str) -> bool {
449 self.tags.contains(tag)
450 }
451
452 pub fn tags(&self) -> &HashSet<String> {
454 &self.tags
455 }
456
457 pub fn snapshot(&self) -> BlockContentSnapshot {
459 BlockContentSnapshot {
460 id: self.id.clone(),
461 display_name: self.display_name.clone(),
462 voxel_byte: self.voxel.to_byte(),
463 engine: self.engine,
464 attributes: ordered_attributes(&self.attributes),
465 tags: ordered_tags(&self.tags),
466 }
467 }
468}
469
470#[derive(Debug, Clone, PartialEq)]
472pub enum ContentRegistryError<V: VoxelType> {
473 DuplicateId { id: ContentId },
475 DuplicateVoxel { voxel: V, existing_id: ContentId },
477 MissingId { id: ContentId },
479}
480
481impl<V: VoxelType + fmt::Debug> fmt::Display for ContentRegistryError<V> {
482 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
483 match self {
484 Self::DuplicateId { id } => {
485 write!(f, "content id `{id}` is already registered")
486 }
487 Self::DuplicateVoxel { voxel, existing_id } => {
488 write!(
489 f,
490 "voxel value `{voxel:?}` is already registered as `{existing_id}`"
491 )
492 }
493 Self::MissingId { id } => {
494 write!(f, "content id `{id}` is not registered")
495 }
496 }
497 }
498}
499
500impl<V: VoxelType + fmt::Debug> std::error::Error for ContentRegistryError<V> {}
501
502#[derive(Debug, Clone, Resource)]
508pub struct BlockRegistry<V: VoxelType> {
509 blocks_by_id: HashMap<ContentId, BlockDefinition<V>>,
510 ids_by_voxel: HashMap<V, ContentId>,
511}
512
513impl<V: VoxelType> Default for BlockRegistry<V> {
514 fn default() -> Self {
515 Self {
516 blocks_by_id: HashMap::new(),
517 ids_by_voxel: HashMap::new(),
518 }
519 }
520}
521
522impl<V: VoxelType> BlockRegistry<V> {
523 pub fn register(
528 &mut self,
529 definition: BlockDefinition<V>,
530 ) -> Result<(), ContentRegistryError<V>> {
531 if self.blocks_by_id.contains_key(definition.id()) {
532 return Err(ContentRegistryError::DuplicateId {
533 id: definition.id().clone(),
534 });
535 }
536
537 if let Some(existing_id) = self.ids_by_voxel.get(&definition.voxel()) {
538 return Err(ContentRegistryError::DuplicateVoxel {
539 voxel: definition.voxel(),
540 existing_id: existing_id.clone(),
541 });
542 }
543
544 self.ids_by_voxel
545 .insert(definition.voxel(), definition.id().clone());
546 self.blocks_by_id
547 .insert(definition.id().clone(), definition);
548 Ok(())
549 }
550
551 pub fn insert_or_replace(&mut self, definition: BlockDefinition<V>) {
554 if let Some(old) = self.blocks_by_id.remove(definition.id()) {
555 self.ids_by_voxel.remove(&old.voxel());
556 }
557 if let Some(old_id) = self.ids_by_voxel.remove(&definition.voxel()) {
558 self.blocks_by_id.remove(&old_id);
559 }
560
561 self.ids_by_voxel
562 .insert(definition.voxel(), definition.id().clone());
563 self.blocks_by_id
564 .insert(definition.id().clone(), definition);
565 }
566
567 pub fn get(&self, id: impl AsRef<str>) -> Option<&BlockDefinition<V>> {
569 let id = ContentId::new(id.as_ref());
570 self.blocks_by_id.get(&id)
571 }
572
573 pub fn require(
575 &self,
576 id: impl AsRef<str>,
577 ) -> Result<&BlockDefinition<V>, ContentRegistryError<V>> {
578 let id = ContentId::new(id.as_ref());
579 self.blocks_by_id
580 .get(&id)
581 .ok_or(ContentRegistryError::MissingId { id })
582 }
583
584 pub fn get_by_voxel(&self, voxel: V) -> Option<&BlockDefinition<V>> {
586 self.ids_by_voxel
587 .get(&voxel)
588 .and_then(|id| self.blocks_by_id.get(id))
589 }
590
591 pub fn contains_id(&self, id: impl AsRef<str>) -> bool {
593 self.get(id).is_some()
594 }
595
596 pub fn len(&self) -> usize {
598 self.blocks_by_id.len()
599 }
600
601 pub fn is_empty(&self) -> bool {
603 self.blocks_by_id.is_empty()
604 }
605
606 pub fn iter(&self) -> impl Iterator<Item = &BlockDefinition<V>> {
608 self.blocks_by_id.values()
609 }
610
611 pub fn snapshot(&self) -> Vec<BlockContentSnapshot> {
613 let mut blocks: Vec<_> = self.iter().map(BlockDefinition::snapshot).collect();
614 blocks.sort_by(|left, right| left.id.as_str().cmp(right.id.as_str()));
615 blocks
616 }
617}
618
619#[cfg(feature = "items")]
627#[derive(Debug, Clone, PartialEq)]
628pub struct ItemDefinition<I: ItemType> {
629 id: ContentId,
630 item: I,
631 display_name: String,
632 color: [f32; 4],
633 attributes: HashMap<String, ContentValue>,
634 tags: HashSet<String>,
635}
636
637#[cfg(feature = "items")]
639#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
640pub struct ItemContentSnapshot {
641 pub id: ContentId,
643 pub display_name: String,
645 pub item_byte: u8,
647 pub color: [f32; 4],
649 pub attributes: BTreeMap<String, ContentValue>,
651 pub tags: Vec<String>,
653}
654
655#[cfg(feature = "items")]
656impl<I: ItemType> ItemDefinition<I> {
657 pub fn new(id: impl Into<ContentId>, item: I) -> Self {
659 Self {
660 id: id.into(),
661 item,
662 display_name: item.name().to_owned(),
663 color: item.color(),
664 attributes: HashMap::new(),
665 tags: HashSet::new(),
666 }
667 }
668
669 pub fn id(&self) -> &ContentId {
671 &self.id
672 }
673
674 pub fn item(&self) -> I {
676 self.item
677 }
678
679 pub fn display_name(&self) -> &str {
681 &self.display_name
682 }
683
684 pub fn named(mut self, name: impl Into<String>) -> Self {
686 self.display_name = name.into();
687 self
688 }
689
690 pub fn color(&self) -> [f32; 4] {
692 self.color
693 }
694
695 pub fn color_override(mut self, color: [f32; 4]) -> Self {
697 self.color = color;
698 self
699 }
700
701 pub fn attribute(mut self, key: impl Into<String>, value: impl Into<ContentValue>) -> Self {
703 self.attributes.insert(key.into(), value.into());
704 self
705 }
706
707 pub fn tag(mut self, tag: impl Into<String>) -> Self {
709 self.tags.insert(tag.into());
710 self
711 }
712
713 pub fn get_attribute(&self, key: &str) -> Option<&ContentValue> {
715 self.attributes.get(key)
716 }
717
718 pub fn bool_attribute(&self, key: &str) -> Option<bool> {
720 self.get_attribute(key).and_then(ContentValue::as_bool)
721 }
722
723 pub fn integer_attribute(&self, key: &str) -> Option<i64> {
725 self.get_attribute(key).and_then(ContentValue::as_i64)
726 }
727
728 pub fn number_attribute(&self, key: &str) -> Option<f64> {
732 self.get_attribute(key).and_then(ContentValue::as_number)
733 }
734
735 pub fn text_attribute(&self, key: &str) -> Option<&str> {
737 self.get_attribute(key).and_then(ContentValue::as_str)
738 }
739
740 pub fn text_list_attribute(&self, key: &str) -> Option<&[String]> {
742 self.get_attribute(key).and_then(ContentValue::as_text_list)
743 }
744
745 pub fn number_list_attribute(&self, key: &str) -> Option<&[f64]> {
747 self.get_attribute(key)
748 .and_then(ContentValue::as_number_list)
749 }
750
751 pub fn color_attribute(&self, key: &str) -> Option<[f32; 4]> {
753 self.get_attribute(key).and_then(ContentValue::as_color)
754 }
755
756 pub fn attributes(&self) -> &HashMap<String, ContentValue> {
758 &self.attributes
759 }
760
761 pub fn has_tag(&self, tag: &str) -> bool {
763 self.tags.contains(tag)
764 }
765
766 pub fn tags(&self) -> &HashSet<String> {
768 &self.tags
769 }
770
771 pub fn snapshot(&self) -> ItemContentSnapshot {
773 ItemContentSnapshot {
774 id: self.id.clone(),
775 display_name: self.display_name.clone(),
776 item_byte: self.item.to_byte(),
777 color: self.color,
778 attributes: ordered_attributes(&self.attributes),
779 tags: ordered_tags(&self.tags),
780 }
781 }
782}
783
784#[cfg(feature = "items")]
786#[derive(Debug, Clone, PartialEq)]
787pub enum ItemRegistryError<I: ItemType> {
788 DuplicateId { id: ContentId },
790 DuplicateItem { item: I, existing_id: ContentId },
792 MissingId { id: ContentId },
794}
795
796#[cfg(feature = "items")]
797impl<I: ItemType + fmt::Debug> fmt::Display for ItemRegistryError<I> {
798 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
799 match self {
800 Self::DuplicateId { id } => {
801 write!(f, "content id `{id}` is already registered")
802 }
803 Self::DuplicateItem { item, existing_id } => {
804 write!(
805 f,
806 "item value `{item:?}` is already registered as `{existing_id}`"
807 )
808 }
809 Self::MissingId { id } => {
810 write!(f, "content id `{id}` is not registered")
811 }
812 }
813 }
814}
815
816#[cfg(feature = "items")]
817impl<I: ItemType + fmt::Debug> std::error::Error for ItemRegistryError<I> {}
818
819#[cfg(feature = "items")]
821#[derive(Debug, Clone, Resource)]
822pub struct ItemRegistry<I: ItemType> {
823 items_by_id: HashMap<ContentId, ItemDefinition<I>>,
824 ids_by_item: HashMap<I, ContentId>,
825}
826
827#[cfg(feature = "items")]
828impl<I: ItemType> Default for ItemRegistry<I> {
829 fn default() -> Self {
830 Self {
831 items_by_id: HashMap::new(),
832 ids_by_item: HashMap::new(),
833 }
834 }
835}
836
837#[cfg(feature = "items")]
838impl<I: ItemType> ItemRegistry<I> {
839 pub fn register(&mut self, definition: ItemDefinition<I>) -> Result<(), ItemRegistryError<I>> {
841 if self.items_by_id.contains_key(definition.id()) {
842 return Err(ItemRegistryError::DuplicateId {
843 id: definition.id().clone(),
844 });
845 }
846
847 if let Some(existing_id) = self.ids_by_item.get(&definition.item()) {
848 return Err(ItemRegistryError::DuplicateItem {
849 item: definition.item(),
850 existing_id: existing_id.clone(),
851 });
852 }
853
854 self.ids_by_item
855 .insert(definition.item(), definition.id().clone());
856 self.items_by_id.insert(definition.id().clone(), definition);
857 Ok(())
858 }
859
860 pub fn insert_or_replace(&mut self, definition: ItemDefinition<I>) {
863 if let Some(old) = self.items_by_id.remove(definition.id()) {
864 self.ids_by_item.remove(&old.item());
865 }
866 if let Some(old_id) = self.ids_by_item.remove(&definition.item()) {
867 self.items_by_id.remove(&old_id);
868 }
869
870 self.ids_by_item
871 .insert(definition.item(), definition.id().clone());
872 self.items_by_id.insert(definition.id().clone(), definition);
873 }
874
875 pub fn get(&self, id: impl AsRef<str>) -> Option<&ItemDefinition<I>> {
877 let id = ContentId::new(id.as_ref());
878 self.items_by_id.get(&id)
879 }
880
881 pub fn require(&self, id: impl AsRef<str>) -> Result<&ItemDefinition<I>, ItemRegistryError<I>> {
883 let id = ContentId::new(id.as_ref());
884 self.items_by_id
885 .get(&id)
886 .ok_or(ItemRegistryError::MissingId { id })
887 }
888
889 pub fn get_by_item(&self, item: I) -> Option<&ItemDefinition<I>> {
891 self.ids_by_item
892 .get(&item)
893 .and_then(|id| self.items_by_id.get(id))
894 }
895
896 pub fn contains_id(&self, id: impl AsRef<str>) -> bool {
898 self.get(id).is_some()
899 }
900
901 pub fn len(&self) -> usize {
903 self.items_by_id.len()
904 }
905
906 pub fn is_empty(&self) -> bool {
908 self.items_by_id.is_empty()
909 }
910
911 pub fn iter(&self) -> impl Iterator<Item = &ItemDefinition<I>> {
913 self.items_by_id.values()
914 }
915
916 pub fn snapshot(&self) -> Vec<ItemContentSnapshot> {
918 let mut items: Vec<_> = self.iter().map(ItemDefinition::snapshot).collect();
919 items.sort_by(|left, right| left.id.as_str().cmp(right.id.as_str()));
920 items
921 }
922}
923
924#[cfg(feature = "items")]
930pub struct ItemContentPlugin<I: ItemType = DefaultItem> {
931 _marker: PhantomData<I>,
932}
933
934#[cfg(feature = "items")]
935impl<I: ItemType> ItemContentPlugin<I> {
936 pub fn new() -> Self {
938 Self {
939 _marker: PhantomData,
940 }
941 }
942}
943
944#[cfg(feature = "items")]
945impl<I: ItemType> Default for ItemContentPlugin<I> {
946 fn default() -> Self {
947 Self::new()
948 }
949}
950
951#[cfg(feature = "items")]
952impl<I: ItemType> Plugin for ItemContentPlugin<I> {
953 fn build(&self, app: &mut App) {
954 app.init_resource::<ItemRegistry<I>>();
955 }
956}
957
958#[cfg(feature = "items")]
962#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
963pub struct DropCount {
964 pub min: u32,
966 pub max: u32,
968}
969
970#[cfg(feature = "items")]
971impl DropCount {
972 pub fn fixed(count: u32) -> Self {
974 Self {
975 min: count,
976 max: count,
977 }
978 }
979
980 pub fn range(min: u32, max: u32) -> Self {
985 Self {
986 min: min.min(max),
987 max: min.max(max),
988 }
989 }
990}
991
992#[cfg(feature = "items")]
994#[derive(Debug, Clone, PartialEq)]
995pub struct BlockDropDefinition<I: ItemType> {
996 item: I,
997 count: DropCount,
998 chance: f32,
999 attributes: HashMap<String, ContentValue>,
1000}
1001
1002#[cfg(feature = "items")]
1004#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1005pub struct BlockDropContentSnapshot {
1006 pub block_id: ContentId,
1008 pub item_byte: u8,
1010 pub min_count: u32,
1012 pub max_count: u32,
1014 pub chance: f32,
1016 pub attributes: BTreeMap<String, ContentValue>,
1018}
1019
1020#[cfg(feature = "items")]
1021impl<I: ItemType> BlockDropDefinition<I> {
1022 pub fn fixed(item: I, count: u32) -> Self {
1024 Self::new(item, DropCount::fixed(count))
1025 }
1026
1027 pub fn new(item: I, count: DropCount) -> Self {
1029 Self {
1030 item,
1031 count,
1032 chance: 1.0,
1033 attributes: HashMap::new(),
1034 }
1035 }
1036
1037 pub fn item(&self) -> I {
1039 self.item
1040 }
1041
1042 pub fn count(&self) -> DropCount {
1044 self.count
1045 }
1046
1047 pub fn chance(&self) -> f32 {
1049 self.chance
1050 }
1051
1052 pub fn with_chance(mut self, chance: f32) -> Self {
1054 self.chance = chance.clamp(0.0, 1.0);
1055 self
1056 }
1057
1058 pub fn attribute(mut self, key: impl Into<String>, value: impl Into<ContentValue>) -> Self {
1060 self.attributes.insert(key.into(), value.into());
1061 self
1062 }
1063
1064 pub fn get_attribute(&self, key: &str) -> Option<&ContentValue> {
1066 self.attributes.get(key)
1067 }
1068
1069 pub fn bool_attribute(&self, key: &str) -> Option<bool> {
1071 self.get_attribute(key).and_then(ContentValue::as_bool)
1072 }
1073
1074 pub fn integer_attribute(&self, key: &str) -> Option<i64> {
1076 self.get_attribute(key).and_then(ContentValue::as_i64)
1077 }
1078
1079 pub fn number_attribute(&self, key: &str) -> Option<f64> {
1083 self.get_attribute(key).and_then(ContentValue::as_number)
1084 }
1085
1086 pub fn text_attribute(&self, key: &str) -> Option<&str> {
1088 self.get_attribute(key).and_then(ContentValue::as_str)
1089 }
1090
1091 pub fn text_list_attribute(&self, key: &str) -> Option<&[String]> {
1093 self.get_attribute(key).and_then(ContentValue::as_text_list)
1094 }
1095
1096 pub fn number_list_attribute(&self, key: &str) -> Option<&[f64]> {
1098 self.get_attribute(key)
1099 .and_then(ContentValue::as_number_list)
1100 }
1101
1102 pub fn color_attribute(&self, key: &str) -> Option<[f32; 4]> {
1104 self.get_attribute(key).and_then(ContentValue::as_color)
1105 }
1106
1107 pub fn attributes(&self) -> &HashMap<String, ContentValue> {
1109 &self.attributes
1110 }
1111
1112 pub fn to_drop_table_entry(&self) -> DropTableEntry<I> {
1115 DropTableEntry::with_chance(self.item, self.count.min, self.count.max, self.chance)
1116 }
1117
1118 fn snapshot(&self, block_id: &ContentId) -> BlockDropContentSnapshot {
1119 BlockDropContentSnapshot {
1120 block_id: block_id.clone(),
1121 item_byte: self.item.to_byte(),
1122 min_count: self.count.min,
1123 max_count: self.count.max,
1124 chance: self.chance,
1125 attributes: ordered_attributes(&self.attributes),
1126 }
1127 }
1128}
1129
1130#[cfg(feature = "items")]
1132#[derive(Debug, Clone, PartialEq)]
1133pub enum BlockDropRegistryError<I: ItemType> {
1134 UnknownBlockId { id: ContentId },
1136 UnknownItem { block_id: ContentId, item: I },
1138}
1139
1140#[cfg(feature = "items")]
1141impl<I: ItemType + fmt::Debug> fmt::Display for BlockDropRegistryError<I> {
1142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1143 match self {
1144 Self::UnknownBlockId { id } => {
1145 write!(f, "drop table references unknown block id `{id}`")
1146 }
1147 Self::UnknownItem { block_id, item } => {
1148 write!(
1149 f,
1150 "drop table for block `{block_id}` references unknown item `{item:?}`"
1151 )
1152 }
1153 }
1154 }
1155}
1156
1157#[cfg(feature = "items")]
1158impl<I: ItemType + fmt::Debug> std::error::Error for BlockDropRegistryError<I> {}
1159
1160#[cfg(feature = "items")]
1162#[derive(Debug, Clone, Resource)]
1163pub struct BlockDropRegistry<I: ItemType> {
1164 drops_by_block_id: HashMap<ContentId, Vec<BlockDropDefinition<I>>>,
1165}
1166
1167#[cfg(feature = "items")]
1168impl<I: ItemType> Default for BlockDropRegistry<I> {
1169 fn default() -> Self {
1170 Self {
1171 drops_by_block_id: HashMap::new(),
1172 }
1173 }
1174}
1175
1176#[cfg(feature = "items")]
1177impl<I: ItemType> BlockDropRegistry<I> {
1178 pub fn register_drop(&mut self, block_id: impl Into<ContentId>, drop: BlockDropDefinition<I>) {
1180 self.drops_by_block_id
1181 .entry(block_id.into())
1182 .or_default()
1183 .push(drop);
1184 }
1185
1186 pub fn get(&self, block_id: impl AsRef<str>) -> &[BlockDropDefinition<I>] {
1188 let id = ContentId::new(block_id.as_ref());
1189 self.drops_by_block_id
1190 .get(&id)
1191 .map(Vec::as_slice)
1192 .unwrap_or(&[])
1193 }
1194
1195 pub fn contains_block_id(&self, block_id: impl AsRef<str>) -> bool {
1197 let id = ContentId::new(block_id.as_ref());
1198 self.drops_by_block_id.contains_key(&id)
1199 }
1200
1201 pub fn len_for(&self, block_id: impl AsRef<str>) -> usize {
1203 self.get(block_id).len()
1204 }
1205
1206 pub fn iter(&self) -> impl Iterator<Item = (&ContentId, &[BlockDropDefinition<I>])> {
1208 self.drops_by_block_id
1209 .iter()
1210 .map(|(id, drops)| (id, drops.as_slice()))
1211 }
1212
1213 pub fn snapshot(&self) -> Vec<BlockDropContentSnapshot> {
1215 let mut drops: Vec<_> = self
1216 .iter()
1217 .flat_map(|(block_id, drops)| drops.iter().map(|drop| drop.snapshot(block_id)))
1218 .collect();
1219 drops.sort_by(|left, right| {
1220 left.block_id
1221 .as_str()
1222 .cmp(right.block_id.as_str())
1223 .then(left.item_byte.cmp(&right.item_byte))
1224 .then(left.min_count.cmp(&right.min_count))
1225 .then(left.max_count.cmp(&right.max_count))
1226 });
1227 drops
1228 }
1229
1230 pub fn get_for_voxel<V: VoxelType>(
1233 &self,
1234 voxel: V,
1235 blocks: &BlockRegistry<V>,
1236 ) -> &[BlockDropDefinition<I>] {
1237 let Some(block) = blocks.get_by_voxel(voxel) else {
1238 return &[];
1239 };
1240 self.get(block.id().as_str())
1241 }
1242
1243 pub fn validate_blocks<V: VoxelType>(
1245 &self,
1246 blocks: &BlockRegistry<V>,
1247 ) -> Result<(), BlockDropRegistryError<I>> {
1248 for block_id in self.drops_by_block_id.keys() {
1249 if !blocks.contains_id(block_id.as_str()) {
1250 return Err(BlockDropRegistryError::UnknownBlockId {
1251 id: block_id.clone(),
1252 });
1253 }
1254 }
1255 Ok(())
1256 }
1257
1258 pub fn validate_items(&self, items: &ItemRegistry<I>) -> Result<(), BlockDropRegistryError<I>> {
1260 for (block_id, drops) in &self.drops_by_block_id {
1261 for drop in drops {
1262 if items.get_by_item(drop.item()).is_none() {
1263 return Err(BlockDropRegistryError::UnknownItem {
1264 block_id: block_id.clone(),
1265 item: drop.item(),
1266 });
1267 }
1268 }
1269 }
1270 Ok(())
1271 }
1272
1273 pub fn to_drop_table<V: VoxelType>(
1280 &self,
1281 blocks: &BlockRegistry<V>,
1282 ) -> Result<DropTable<I>, BlockDropRegistryError<I>> {
1283 let mut table = DropTable::new();
1284 self.apply_to_drop_table(blocks, &mut table)?;
1285 Ok(table)
1286 }
1287
1288 pub fn apply_to_drop_table<V: VoxelType>(
1295 &self,
1296 blocks: &BlockRegistry<V>,
1297 table: &mut DropTable<I>,
1298 ) -> Result<(), BlockDropRegistryError<I>> {
1299 for (block_id, drops) in &self.drops_by_block_id {
1300 let Some(block) = blocks.get(block_id.as_str()) else {
1301 return Err(BlockDropRegistryError::UnknownBlockId {
1302 id: block_id.clone(),
1303 });
1304 };
1305
1306 table.replace_entries(
1307 block.voxel().to_byte(),
1308 drops.iter().map(BlockDropDefinition::to_drop_table_entry),
1309 );
1310 }
1311 Ok(())
1312 }
1313
1314 pub fn len(&self) -> usize {
1316 self.drops_by_block_id.len()
1317 }
1318
1319 pub fn is_empty(&self) -> bool {
1321 self.drops_by_block_id.is_empty()
1322 }
1323}
1324
1325#[cfg(feature = "items")]
1327pub struct BlockDropContentPlugin<I: ItemType = DefaultItem> {
1328 _marker: PhantomData<I>,
1329}
1330
1331#[cfg(feature = "items")]
1332impl<I: ItemType> BlockDropContentPlugin<I> {
1333 pub fn new() -> Self {
1335 Self {
1336 _marker: PhantomData,
1337 }
1338 }
1339}
1340
1341#[cfg(feature = "items")]
1342impl<I: ItemType> Default for BlockDropContentPlugin<I> {
1343 fn default() -> Self {
1344 Self::new()
1345 }
1346}
1347
1348#[cfg(feature = "items")]
1349impl<I: ItemType> Plugin for BlockDropContentPlugin<I> {
1350 fn build(&self, app: &mut App) {
1351 app.init_resource::<BlockDropRegistry<I>>();
1352 }
1353}
1354
1355pub struct VoxelContentPlugin<V: VoxelType = DefaultVoxel> {
1360 _marker: PhantomData<V>,
1361}
1362
1363impl<V: VoxelType> VoxelContentPlugin<V> {
1364 pub fn new() -> Self {
1366 Self {
1367 _marker: PhantomData,
1368 }
1369 }
1370}
1371
1372impl<V: VoxelType> Default for VoxelContentPlugin<V> {
1373 fn default() -> Self {
1374 Self::new()
1375 }
1376}
1377
1378impl<V: VoxelType> Plugin for VoxelContentPlugin<V> {
1379 fn build(&self, app: &mut App) {
1380 app.init_resource::<BlockRegistry<V>>();
1381 }
1382}
1383
1384fn ordered_attributes(
1385 attributes: &HashMap<String, ContentValue>,
1386) -> BTreeMap<String, ContentValue> {
1387 attributes
1388 .iter()
1389 .map(|(key, value)| (key.clone(), value.clone()))
1390 .collect()
1391}
1392
1393fn ordered_tags(tags: &HashSet<String>) -> Vec<String> {
1394 let mut tags: Vec<_> = tags.iter().cloned().collect();
1395 tags.sort();
1396 tags
1397}
1398
1399#[cfg(test)]
1400mod tests {
1401 use bevy::prelude::{App, MinimalPlugins};
1402
1403 use super::*;
1404 #[cfg(feature = "items")]
1405 use crate::items::DefaultItem;
1406 use crate::voxel::DefaultTerrainVoxel;
1407
1408 #[test]
1409 fn block_definition_keeps_author_defined_attributes_and_tags() {
1410 let definition = BlockDefinition::new("regolith", DefaultTerrainVoxel::Sand)
1411 .named("Regolith")
1412 .tag("terrain")
1413 .attribute("hardness", 0.8)
1414 .attribute("dusty", true)
1415 .attribute("drops", ContentValue::strings(["regolith"]));
1416
1417 assert_eq!(definition.id().as_str(), "regolith");
1418 assert_eq!(definition.voxel(), DefaultTerrainVoxel::Sand);
1419 assert_eq!(definition.display_name(), "Regolith");
1420 assert!(definition.has_tag("terrain"));
1421 assert_eq!(definition.number_attribute("hardness"), Some(0.8));
1422 assert_eq!(definition.bool_attribute("dusty"), Some(true));
1423 assert_eq!(
1424 definition.text_list_attribute("drops"),
1425 Some(&["regolith".to_owned()][..])
1426 );
1427 }
1428
1429 #[test]
1430 fn content_value_number_accepts_integers_and_floats() {
1431 assert_eq!(ContentValue::from(5).as_number(), Some(5.0));
1432 assert_eq!(ContentValue::from(0.75).as_number(), Some(0.75));
1433 assert_eq!(ContentValue::from("not_a_number").as_number(), None);
1434 }
1435
1436 #[test]
1437 fn registry_rejects_duplicate_ids_and_duplicate_voxels() {
1438 let mut registry = BlockRegistry::<DefaultTerrainVoxel>::default();
1439 registry
1440 .register(BlockDefinition::new("stone", DefaultTerrainVoxel::Stone))
1441 .expect("first block should register");
1442
1443 let duplicate_id =
1444 registry.register(BlockDefinition::new("stone", DefaultTerrainVoxel::Dirt));
1445 assert!(matches!(
1446 duplicate_id,
1447 Err(ContentRegistryError::DuplicateId { .. })
1448 ));
1449
1450 let duplicate_voxel = registry.register(BlockDefinition::new(
1451 "another_stone",
1452 DefaultTerrainVoxel::Stone,
1453 ));
1454 assert!(matches!(
1455 duplicate_voxel,
1456 Err(ContentRegistryError::DuplicateVoxel { .. })
1457 ));
1458 }
1459
1460 #[test]
1461 fn registry_can_lookup_by_id_and_voxel() {
1462 let mut registry = BlockRegistry::<DefaultTerrainVoxel>::default();
1463 registry
1464 .register(BlockDefinition::new("wood", DefaultTerrainVoxel::Wood).tag("organic"))
1465 .expect("block should register");
1466
1467 assert_eq!(registry.len(), 1);
1468 assert!(registry.contains_id("wood"));
1469 assert_eq!(
1470 registry.require("wood").expect("wood should exist").voxel(),
1471 DefaultTerrainVoxel::Wood
1472 );
1473 assert!(matches!(
1474 registry.require("missing"),
1475 Err(ContentRegistryError::MissingId { .. })
1476 ));
1477 assert!(
1478 registry
1479 .get_by_voxel(DefaultTerrainVoxel::Wood)
1480 .expect("wood voxel should resolve")
1481 .has_tag("organic")
1482 );
1483 }
1484
1485 #[test]
1486 fn block_registry_snapshot_is_serializable_and_deterministic() {
1487 let mut registry = BlockRegistry::<DefaultTerrainVoxel>::default();
1488 registry
1489 .register(
1490 BlockDefinition::new("wood", DefaultTerrainVoxel::Wood)
1491 .tag("organic")
1492 .tag("solid")
1493 .attribute("hardness", 1.5)
1494 .attribute("flammable", true),
1495 )
1496 .expect("block should register");
1497
1498 let snapshot = registry.snapshot();
1499 assert_eq!(snapshot.len(), 1);
1500 assert_eq!(snapshot[0].id.as_str(), "wood");
1501 assert_eq!(snapshot[0].voxel_byte, DefaultTerrainVoxel::Wood.to_byte());
1502 assert_eq!(
1503 snapshot[0].tags,
1504 vec!["organic".to_owned(), "solid".to_owned()]
1505 );
1506 assert_eq!(
1507 snapshot[0]
1508 .attributes
1509 .get("hardness")
1510 .and_then(ContentValue::as_number),
1511 Some(1.5)
1512 );
1513
1514 let json = serde_json::to_string(&snapshot).expect("snapshot should serialize");
1515 assert!(json.contains("\"id\":\"wood\""));
1516 assert!(json.contains("\"voxel_byte\""));
1517 }
1518
1519 #[test]
1520 fn content_plugin_initializes_empty_registry_without_defaults() {
1521 let mut app = App::new();
1522 app.add_plugins(MinimalPlugins);
1523 app.add_plugins(VoxelContentPlugin::<DefaultTerrainVoxel>::new());
1524
1525 assert!(
1526 app.world()
1527 .resource::<BlockRegistry<DefaultTerrainVoxel>>()
1528 .is_empty(),
1529 "content plugin must not register game-specific default blocks"
1530 );
1531 }
1532
1533 #[cfg(feature = "items")]
1534 #[test]
1535 fn item_definition_keeps_author_defined_attributes_and_tags() {
1536 let definition = ItemDefinition::new("dream_glass_shard", DefaultItem::Crystal)
1537 .named("Dream Glass Shard")
1538 .color_override([0.45, 0.75, 1.0, 1.0])
1539 .tag("ritual_material")
1540 .attribute("mana_conductivity", 12.0);
1541
1542 assert_eq!(definition.id().as_str(), "dream_glass_shard");
1543 assert_eq!(definition.item(), DefaultItem::Crystal);
1544 assert_eq!(definition.display_name(), "Dream Glass Shard");
1545 assert_eq!(definition.color(), [0.45, 0.75, 1.0, 1.0]);
1546 assert!(definition.has_tag("ritual_material"));
1547 assert_eq!(definition.number_attribute("mana_conductivity"), Some(12.0));
1548 }
1549
1550 #[cfg(feature = "items")]
1551 #[test]
1552 fn item_registry_rejects_duplicate_ids_and_duplicate_items() {
1553 let mut registry = ItemRegistry::<DefaultItem>::default();
1554 registry
1555 .register(ItemDefinition::new("sand_item", DefaultItem::Sand))
1556 .expect("first item should register");
1557
1558 let duplicate_id =
1559 registry.register(ItemDefinition::new("sand_item", DefaultItem::Crystal));
1560 assert!(matches!(
1561 duplicate_id,
1562 Err(ItemRegistryError::DuplicateId { .. })
1563 ));
1564
1565 let duplicate_item =
1566 registry.register(ItemDefinition::new("another_sand", DefaultItem::Sand));
1567 assert!(matches!(
1568 duplicate_item,
1569 Err(ItemRegistryError::DuplicateItem { .. })
1570 ));
1571
1572 assert!(registry.require("sand_item").is_ok());
1573 assert!(matches!(
1574 registry.require("missing"),
1575 Err(ItemRegistryError::MissingId { .. })
1576 ));
1577 }
1578
1579 #[cfg(feature = "items")]
1580 #[test]
1581 fn item_registry_snapshot_is_serializable_and_deterministic() {
1582 let mut registry = ItemRegistry::<DefaultItem>::default();
1583 registry
1584 .register(
1585 ItemDefinition::new("dream_glass_shard", DefaultItem::Crystal)
1586 .tag("ritual_material")
1587 .attribute("mana_conductivity", 12.0),
1588 )
1589 .expect("item should register");
1590
1591 let snapshot = registry.snapshot();
1592 assert_eq!(snapshot.len(), 1);
1593 assert_eq!(snapshot[0].id.as_str(), "dream_glass_shard");
1594 assert_eq!(snapshot[0].item_byte, DefaultItem::Crystal.to_byte());
1595 assert_eq!(snapshot[0].tags, vec!["ritual_material".to_owned()]);
1596
1597 let json = serde_json::to_string(&snapshot).expect("snapshot should serialize");
1598 assert!(json.contains("\"item_byte\""));
1599 }
1600
1601 #[cfg(feature = "items")]
1602 #[test]
1603 fn block_drop_registry_resolves_drops_by_block_id_and_voxel() {
1604 let mut blocks = BlockRegistry::<DefaultTerrainVoxel>::default();
1605 blocks
1606 .register(BlockDefinition::new(
1607 "moon_regolith",
1608 DefaultTerrainVoxel::Sand,
1609 ))
1610 .expect("block should register");
1611
1612 let mut drops = BlockDropRegistry::<DefaultItem>::default();
1613 drops.register_drop(
1614 "moon_regolith",
1615 BlockDropDefinition::new(DefaultItem::Sand, DropCount::range(3, 1)).with_chance(1.4),
1616 );
1617
1618 let by_id = drops.get("moon_regolith");
1619 assert_eq!(by_id.len(), 1);
1620 assert_eq!(by_id[0].item(), DefaultItem::Sand);
1621 assert_eq!(by_id[0].count(), DropCount { min: 1, max: 3 });
1622 assert_eq!(by_id[0].chance(), 1.0);
1623 assert!(drops.contains_block_id("moon_regolith"));
1624 assert_eq!(drops.len_for("moon_regolith"), 1);
1625
1626 let by_voxel = drops.get_for_voxel(DefaultTerrainVoxel::Sand, &blocks);
1627 assert_eq!(by_voxel.len(), 1);
1628 assert_eq!(by_voxel[0].item(), DefaultItem::Sand);
1629 assert!(
1630 drops
1631 .get_for_voxel(DefaultTerrainVoxel::Stone, &blocks)
1632 .is_empty()
1633 );
1634 }
1635
1636 #[cfg(feature = "items")]
1637 #[test]
1638 fn block_drop_registry_validates_block_and_item_references() {
1639 let mut blocks = BlockRegistry::<DefaultTerrainVoxel>::default();
1640 blocks
1641 .register(BlockDefinition::new(
1642 "moon_regolith",
1643 DefaultTerrainVoxel::Sand,
1644 ))
1645 .expect("block should register");
1646
1647 let mut items = ItemRegistry::<DefaultItem>::default();
1648 items
1649 .register(ItemDefinition::new("moon_regolith", DefaultItem::Sand))
1650 .expect("item should register");
1651
1652 let mut drops = BlockDropRegistry::<DefaultItem>::default();
1653 drops.register_drop(
1654 "moon_regolith",
1655 BlockDropDefinition::fixed(DefaultItem::Sand, 1),
1656 );
1657
1658 assert!(drops.validate_blocks(&blocks).is_ok());
1659 assert!(drops.validate_items(&items).is_ok());
1660
1661 drops.register_drop(
1662 "missing_block",
1663 BlockDropDefinition::fixed(DefaultItem::Sand, 1),
1664 );
1665 assert!(matches!(
1666 drops.validate_blocks(&blocks),
1667 Err(BlockDropRegistryError::UnknownBlockId { .. })
1668 ));
1669
1670 drops.register_drop(
1671 "moon_regolith",
1672 BlockDropDefinition::fixed(DefaultItem::Crystal, 1),
1673 );
1674 assert!(matches!(
1675 drops.validate_items(&items),
1676 Err(BlockDropRegistryError::UnknownItem { .. })
1677 ));
1678 }
1679
1680 #[cfg(feature = "items")]
1681 #[test]
1682 fn block_drop_registry_builds_runtime_drop_table() {
1683 let mut blocks = BlockRegistry::<DefaultTerrainVoxel>::default();
1684 blocks
1685 .register(BlockDefinition::new(
1686 "moon_regolith",
1687 DefaultTerrainVoxel::Sand,
1688 ))
1689 .expect("block should register");
1690
1691 let mut drops = BlockDropRegistry::<DefaultItem>::default();
1692 drops.register_drop(
1693 "moon_regolith",
1694 BlockDropDefinition::new(DefaultItem::Sand, DropCount::range(1, 3)),
1695 );
1696 drops.register_drop(
1697 "moon_regolith",
1698 BlockDropDefinition::fixed(DefaultItem::Crystal, 1).with_chance(1.0),
1699 );
1700
1701 let table = drops
1702 .to_drop_table(&blocks)
1703 .expect("content drops should resolve through blocks");
1704 let runtime_drops = table.get_drops(DefaultTerrainVoxel::Sand.to_byte(), 42);
1705
1706 assert_eq!(runtime_drops.len(), 2);
1707 assert_eq!(runtime_drops[0].0, DefaultItem::Sand);
1708 assert!((1..=3).contains(&runtime_drops[0].1));
1709 assert_eq!(runtime_drops[1], (DefaultItem::Crystal, 1));
1710 }
1711
1712 #[cfg(feature = "items")]
1713 #[test]
1714 fn block_drop_registry_applies_to_existing_drop_table_idempotently() {
1715 let mut blocks = BlockRegistry::<DefaultTerrainVoxel>::default();
1716 blocks
1717 .register(BlockDefinition::new(
1718 "moon_regolith",
1719 DefaultTerrainVoxel::Sand,
1720 ))
1721 .expect("block should register");
1722
1723 let mut drops = BlockDropRegistry::<DefaultItem>::default();
1724 drops.register_drop(
1725 "moon_regolith",
1726 BlockDropDefinition::fixed(DefaultItem::Sand, 1),
1727 );
1728
1729 let mut table = DropTable::<DefaultItem>::new();
1730 table.register(1, DefaultItem::Dirt, 1, 1);
1731
1732 drops
1733 .apply_to_drop_table(&blocks, &mut table)
1734 .expect("first apply should resolve");
1735 drops
1736 .apply_to_drop_table(&blocks, &mut table)
1737 .expect("second apply should replace rather than duplicate");
1738
1739 let runtime_drops = table.get_drops(DefaultTerrainVoxel::Sand.to_byte(), 0);
1740 assert_eq!(runtime_drops, vec![(DefaultItem::Sand, 1)]);
1741 assert_eq!(
1742 table.get_drops(1, 0),
1743 vec![(DefaultItem::Dirt, 1)],
1744 "unrelated hand-written runtime drops should remain untouched"
1745 );
1746 }
1747
1748 #[cfg(feature = "items")]
1749 #[test]
1750 fn block_drop_registry_to_drop_table_reports_missing_blocks() {
1751 let blocks = BlockRegistry::<DefaultTerrainVoxel>::default();
1752 let mut drops = BlockDropRegistry::<DefaultItem>::default();
1753 drops.register_drop(
1754 "missing_block",
1755 BlockDropDefinition::fixed(DefaultItem::Sand, 1),
1756 );
1757
1758 assert!(matches!(
1759 drops.to_drop_table(&blocks),
1760 Err(BlockDropRegistryError::UnknownBlockId { .. })
1761 ));
1762 }
1763
1764 #[cfg(feature = "items")]
1765 #[test]
1766 fn block_drop_registry_snapshot_is_serializable_and_deterministic() {
1767 let mut drops = BlockDropRegistry::<DefaultItem>::default();
1768 drops.register_drop(
1769 "moon_regolith",
1770 BlockDropDefinition::new(DefaultItem::Sand, DropCount::range(3, 1))
1771 .with_chance(0.5)
1772 .attribute("source", "surface_layer"),
1773 );
1774
1775 let snapshot = drops.snapshot();
1776 assert_eq!(snapshot.len(), 1);
1777 assert_eq!(snapshot[0].block_id.as_str(), "moon_regolith");
1778 assert_eq!(snapshot[0].item_byte, DefaultItem::Sand.to_byte());
1779 assert_eq!(snapshot[0].min_count, 1);
1780 assert_eq!(snapshot[0].max_count, 3);
1781 assert_eq!(snapshot[0].chance, 0.5);
1782
1783 let json = serde_json::to_string(&snapshot).expect("snapshot should serialize");
1784 assert!(json.contains("\"block_id\":\"moon_regolith\""));
1785 assert!(json.contains("\"chance\":0.5"));
1786 }
1787
1788 #[cfg(feature = "items")]
1789 #[test]
1790 fn item_and_drop_plugins_initialize_empty_registries_without_defaults() {
1791 let mut app = App::new();
1792 app.add_plugins(MinimalPlugins);
1793 app.add_plugins(ItemContentPlugin::<DefaultItem>::new());
1794 app.add_plugins(BlockDropContentPlugin::<DefaultItem>::new());
1795
1796 assert!(
1797 app.world()
1798 .resource::<ItemRegistry<DefaultItem>>()
1799 .is_empty(),
1800 "item content plugin must not register game-specific default items"
1801 );
1802 assert!(
1803 app.world()
1804 .resource::<BlockDropRegistry<DefaultItem>>()
1805 .is_empty(),
1806 "block-drop content plugin must not register game-specific default drops"
1807 );
1808 }
1809}