Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/app/runtime/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
mod setup;

use crate::errors::BinaryError;
use crate::setup::setup_block_and_item_mapping;
use std::sync::Arc;
use std::time::Instant;
use temper_config::whitelist::create_whitelist;
Expand Down Expand Up @@ -39,6 +40,8 @@ pub fn entry(start_time: Instant, no_tui: bool) -> Result<(), BinaryError> {
#[cfg(feature = "dashboard")]
temper_dashboard::start_dashboard(global_state.clone());

setup_block_and_item_mapping();

game_loop::start_game_loop(global_state.clone(), no_tui)?;

if !no_tui {
Expand Down
6 changes: 6 additions & 0 deletions src/app/runtime/src/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::errors::BinaryError;
use std::time::Instant;
use temper_components::player::offline_player_data::OfflinePlayerData;
use temper_config::server_config::get_global_config;
use temper_core::block_state_id::{init_block_mappings, init_item_to_block_mapping};
use temper_core::dimension::Dimension;
use temper_core::pos::ChunkPos;
use temper_state::GlobalState;
Expand Down Expand Up @@ -72,3 +73,8 @@ pub fn setup_db(state: GlobalState) -> Result<(), BinaryError> {
info!("Database setup complete.");
Ok(())
}

pub fn setup_block_and_item_mapping() {
init_item_to_block_mapping();
init_block_mappings();
}
82 changes: 50 additions & 32 deletions src/core/src/block_state_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ use crate::block_data::BlockData;
use ahash::RandomState;
use bitcode_derive::{Decode, Encode};
use deepsize::DeepSizeOf;
use lazy_static::lazy_static;
use once_cell::sync::Lazy;
use once_cell::sync::OnceCell;
use std::collections::HashMap;
use std::fmt::Display;
use std::process::exit;
Expand All @@ -18,31 +17,36 @@ const BLOCK_ENTRIES: usize = 27914;

const BLOCKSFILE: &str = include_str!("../../../assets/data/blockstates.json");

lazy_static! {
pub static ref ID2BLOCK: Vec<BlockData> = {
let string_keys: HashMap<String, BlockData, RandomState> =
serde_json::from_str(BLOCKSFILE).unwrap();
if string_keys.len() != BLOCK_ENTRIES {
// Edit this number if the block mappings file changes
error!("Block mappings file is not the correct length");
error!("Expected {} entries, found {}", BLOCK_ENTRIES, string_keys.len());
exit(1);
}
let mut id2block = Vec::with_capacity(BLOCK_ENTRIES);
for _ in 0..BLOCK_ENTRIES {
id2block.push(BlockData::default());
}
string_keys
.iter()
.map(|(k, v)| (k.parse::<i32>().unwrap(), v.clone()))
.for_each(|(k, v)| id2block[k as usize] = v);
id2block
};
pub static ref BLOCK2ID: HashMap<BlockData, i32, RandomState> = ID2BLOCK
pub static ID2BLOCK: OnceCell<Vec<BlockData>> = OnceCell::new();
pub static BLOCK2ID: OnceCell<HashMap<BlockData, i32, RandomState>> = OnceCell::new();

pub fn init_block_mappings() {
let string_keys: HashMap<String, BlockData, RandomState> =
serde_json::from_str(BLOCKSFILE).unwrap();
if string_keys.len() != BLOCK_ENTRIES {
error!("Block mappings file is not the correct length");
error!(
"Expected {} entries, found {}",
BLOCK_ENTRIES,
string_keys.len()
);
exit(1);
}
let mut id2block = Vec::with_capacity(BLOCK_ENTRIES);
for _ in 0..BLOCK_ENTRIES {
id2block.push(BlockData::default());
}
string_keys
.iter()
.map(|(k, v)| (k.parse::<i32>().unwrap(), v.clone()))
.for_each(|(k, v)| id2block[k as usize] = v);
let block2id: HashMap<BlockData, i32, RandomState> = id2block
.iter()
.enumerate()
.map(|(k, v)| (v.clone(), k as i32))
.collect();
ID2BLOCK.set(id2block).expect("Failed to set ID2BLOCK");
BLOCK2ID.set(block2id).expect("Failed to set BLOCK2ID");
}

/// An ID for a block, and it's state in the world. Use this over `BlockData` unless you need to
Expand All @@ -62,17 +66,26 @@ impl BlockStateId {

/// Given a BlockData, return a BlockStateId. Does not clone, should be quite fast.
pub fn from_block_data(block_data: &BlockData) -> Self {
let id = BLOCK2ID.get(block_data).copied().unwrap_or_else(|| {
warn!("Block data '{block_data}' not found in block mappings file");
0
});
let id = BLOCK2ID
.get()
.expect("Mappings not initialized")
.get(block_data)
.copied()
.unwrap_or_else(|| {
warn!("Block data '{block_data}' not found in block mappings file");
0
});
BlockStateId(id as u32)
}

/// Given a block state ID, return a BlockData. Will clone, so don't use in hot loops.
/// If the ID is not found, returns None.
pub fn to_block_data(&self) -> Option<BlockData> {
ID2BLOCK.get(self.0 as usize).cloned()
ID2BLOCK
.get()
.expect("Mappings not initialized")
.get(self.0 as usize)
.cloned()
}

pub fn from_varint(var_int: VarInt) -> Self {
Expand Down Expand Up @@ -154,16 +167,21 @@ impl Default for BlockStateId {

const ITEM_TO_BLOCK_MAPPING_FILE: &str =
include_str!("../../../assets/data/item_to_block_mapping.json");
pub static ITEM_TO_BLOCK_MAPPING: Lazy<HashMap<i32, BlockStateId>> = Lazy::new(|| {
pub static ITEM_TO_BLOCK_MAPPING: OnceCell<HashMap<i32, BlockStateId>> = OnceCell::new();

pub fn init_item_to_block_mapping() {
let str_form: HashMap<String, String> = serde_json::from_str(ITEM_TO_BLOCK_MAPPING_FILE)
.expect("Failed to parse item_to_block_mapping.json");
str_form
let res = str_form
.into_iter()
.map(|(k, v)| {
(
i32::from_str(&k).unwrap(),
BlockStateId::new(u32::from_str(&v).unwrap()),
)
})
.collect()
});
.collect();
ITEM_TO_BLOCK_MAPPING
.set(res)
.expect("Failed to set ITEM_TO_BLOCK_MAPPING, it was already set");
}
12 changes: 11 additions & 1 deletion src/game_systems/src/interactions/src/block_interactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,9 @@ pub fn is_interactive(block_state_id: BlockStateId) -> bool {
mod tests {
use super::*;
use std::collections::BTreeMap;
use temper_core::block_state_id::BlockStateId;
use temper_core::block_state_id::{
BlockStateId, init_block_mappings, init_item_to_block_mapping,
};
use temper_macros::block;

#[test]
Expand All @@ -184,6 +186,8 @@ mod tests {

#[test]
fn test_try_interact_opens_door() {
init_item_to_block_mapping();
init_block_mappings();
// A closed oak door (lower half, north-facing, left hinge, unpowered)
let closed_door: BlockStateId = block!("oak_door", { facing: "north", half: "lower", hinge: "left", open: false, powered: false });

Expand All @@ -201,6 +205,8 @@ mod tests {

#[test]
fn test_try_interact_closes_door() {
init_item_to_block_mapping();
init_block_mappings();
// An already-open oak door
let open_door: BlockStateId = block!("oak_door", { facing: "north", half: "lower", hinge: "left", open: true, powered: false });

Expand All @@ -221,6 +227,8 @@ mod tests {

#[test]
fn test_try_interact_not_interactive() {
init_item_to_block_mapping();
init_block_mappings();
let stone: BlockStateId = block!("stone");
assert!(matches!(
try_interact(stone),
Expand All @@ -230,6 +238,8 @@ mod tests {

#[test]
fn test_is_interactive() {
init_item_to_block_mapping();
init_block_mappings();
let door: BlockStateId = block!("oak_door", { facing: "north", half: "lower", hinge: "left", open: false, powered: false });
let stone: BlockStateId = block!("stone");

Expand Down
14 changes: 1 addition & 13 deletions src/game_systems/src/packets/src/place_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,10 @@ use block_placing::PlacedBlocks;
use std::collections::HashMap;
use temper_components::player::rotation::Rotation;
use temper_config::server_config::get_global_config;
use temper_core::block_state_id::BlockStateId;
use temper_core::dimension::Dimension;
use temper_core::mq;
use temper_inventories::hotbar::Hotbar;
use temper_inventories::inventory::Inventory;
use temper_macros::match_block;
use temper_messages::world_change::WorldChange;
use temper_text::{Color, NamedColor, TextComponentBuilder};

Expand Down Expand Up @@ -159,7 +157,7 @@ pub fn handle(
continue 'ev_loop;
}

let block_at_pos = {
let _block_at_pos = {
let chunk = state
.0
.world
Expand All @@ -168,16 +166,6 @@ pub fn handle(
chunk.get_block(offset_pos.chunk_block_pos())
};

if !(match_block!("water", block_at_pos)
|| match_block!("lava", block_at_pos)
|| match_block!("air", block_at_pos))
{
debug!(
"Block placement failed because the block at the target position is not replaceable"
);
continue 'ev_loop;
}

let placed_blocks = block_placing::place_item(
state.0.clone(),
block_placing::BlockPlaceContext {
Expand Down
47 changes: 29 additions & 18 deletions src/world/block-placing/src/blocks/door.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use bevy_math::IVec3;
use std::collections::BTreeMap;
use temper_core::block_data::BlockData;
use temper_core::dimension::Dimension;
use temper_macros::{item, match_block};
use temper_macros::match_block;
use temper_state::GlobalState;
use tracing::error;

Expand All @@ -16,15 +16,22 @@ impl PlacableBlock for PlaceableDoor {
context: BlockPlaceContext,
state: GlobalState,
) -> Result<PlacedBlocks, BlockPlaceError> {
let name = match context.item_used {
item!("oak_door") => "minecraft:oak_door",
item!("birch_door") => "minecraft:birch_door",
item!("spruce_door") => "minecraft:spruce_door",
item!("jungle_door") => "minecraft:jungle_door",
item!("acacia_door") => "minecraft:acacia_door",
item!("dark_oak_door") => "minecraft:dark_oak_door",
_ => return Err(BlockPlaceError::ItemNotMappedToBlock(context.item_used)),
let name = match context.item_used.to_name() {
Some(name) => name,
None => return Err(BlockPlaceError::ItemIdHasNoNameMapping(context.item_used)),
};

let target_block = {
let chunk = state
.world
.get_or_generate_chunk(context.block_position.chunk(), Dimension::Overworld)
.expect("Could not load chunk");
chunk.get_block(context.block_position.chunk_block_pos())
};
if !match_block!("air", target_block) && !match_block!("cave_air", target_block) {
return Err(BlockPlaceError::TargetBlockNotEmpty(context.block_position));
}

let block_above = {
let chunk = state
.world
Expand All @@ -33,10 +40,9 @@ impl PlacableBlock for PlaceableDoor {
chunk.get_block((context.block_position.pos + IVec3::new(0, 1, 0)).into())
};
if !(match_block!("air", block_above) || match_block!("cave_air", block_above)) {
return Ok(PlacedBlocks {
blocks: std::collections::HashMap::new(),
take_item: false,
});
return Err(BlockPlaceError::TargetBlockNotEmpty(
context.block_position + IVec3::new(0, 1, 0).into(),
));
};
let facing = match context.face_clicked {
BlockFace::North => "south",
Expand Down Expand Up @@ -121,12 +127,15 @@ mod test {
use super::*;
use crate::BlockPlaceContext;
use temper_components::player::rotation::Rotation;
use temper_core::block_state_id::{init_block_mappings, init_item_to_block_mapping};
use temper_core::dimension::Dimension;
use temper_core::pos::BlockPos;
use temper_macros::block;
use temper_macros::{block, item};

#[test]
fn test_place_door() {
init_item_to_block_mapping();
init_block_mappings();
let (state, _) = temper_state::create_test_state();
let context = BlockPlaceContext {
block_clicked: Default::default(),
Expand Down Expand Up @@ -174,6 +183,8 @@ mod test {

#[test]
fn test_place_door_with_block_above() {
init_item_to_block_mapping();
init_block_mappings();
let (state, _) = temper_state::create_test_state();
// Place a block above the door position
{
Expand All @@ -197,16 +208,16 @@ mod test {
player_position: Default::default(),
};
let result = PlaceableDoor::place(context, state.0.clone());
assert!(result.is_ok());
let placed_blocks = result.unwrap();
assert!(
placed_blocks.blocks.is_empty(),
"Door should not be placed when there is a block above"
result.is_err(),
"Placing a door with a block above should return an error"
);
}

#[test]
fn test_place_door_on_invalid_face() {
init_item_to_block_mapping();
init_block_mappings();
let (state, _) = temper_state::create_test_state();
let context = BlockPlaceContext {
block_clicked: Default::default(),
Expand Down
Loading