chore: move to crates folder
This commit is contained in:
1 parent
5d10c0d8a8
commit
cb3660bcd2
3393 files changed
+1270
-741
No files matched your search
@@ -0,0 +1,643 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command, literal};
|
||||
use crate::command::argument_types::core::string::StringArgumentType;
|
||||
use crate::command::argument_types::entity::EntityArgumentType;
|
||||
use crate::command::argument_types::resource_key::{ADVANCEMENT_REGISTRY, ResourceKeyArgument};
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::context::command_source::CommandSource;
|
||||
use crate::command::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use crate::command::suggestion::provider::{SuggestionProvider, SuggestionProviderResult};
|
||||
use crate::command::suggestion::suggestions::SuggestionsBuilder;
|
||||
use crate::entity::EntityBase;
|
||||
use crate::entity::player::Player;
|
||||
use crate::entity::player::advancement::PlayerAdvancement;
|
||||
use futures::future::join_all;
|
||||
use pumpkin_data::advancement_data::AdvancementNode;
|
||||
use pumpkin_data::{ADVANCEMENT_TREE, Advancement, translation};
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::sync::Arc;
|
||||
|
||||
const NAME: &str = "advancement";
|
||||
const DESCRIPTION: &str = "manage advancement of players";
|
||||
const PERMISSION: &str = "minecraft:command.advancement";
|
||||
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
const ARG_ADVANCEMENT: &str = "advancement";
|
||||
const ARG_CRITERION: &str = "criterion";
|
||||
|
||||
#[allow(unused)]
|
||||
const ERROR_CRITERION_NOT_FOUND: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ADVANCEMENT_CRITERIONNOTFOUND,
|
||||
translation::java::COMMANDS_ADVANCEMENT_CRITERIONNOTFOUND,
|
||||
);
|
||||
const ERROR_GRANT_ONE_TO_ONE: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ADVANCEMENT_GRANT_ONE_TO_ONE_FAILURE,
|
||||
translation::java::COMMANDS_ADVANCEMENT_GRANT_ONE_TO_ONE_FAILURE,
|
||||
);
|
||||
const ERROR_REVOKE_ONE_TO_ONE: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ADVANCEMENT_REVOKE_ONE_TO_ONE_FAILURE,
|
||||
translation::java::COMMANDS_ADVANCEMENT_REVOKE_ONE_TO_ONE_FAILURE,
|
||||
);
|
||||
const ERROR_GRANT_ONE_TO_MANY: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ADVANCEMENT_GRANT_ONE_TO_MANY_FAILURE,
|
||||
translation::java::COMMANDS_ADVANCEMENT_GRANT_ONE_TO_MANY_FAILURE,
|
||||
);
|
||||
const ERROR_REVOKE_ONE_TO_MANY: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ADVANCEMENT_REVOKE_ONE_TO_MANY_FAILURE,
|
||||
translation::java::COMMANDS_ADVANCEMENT_REVOKE_ONE_TO_MANY_FAILURE,
|
||||
);
|
||||
const ERROR_GRANT_MANY_TO_ONE: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ADVANCEMENT_GRANT_MANY_TO_ONE_FAILURE,
|
||||
translation::java::COMMANDS_ADVANCEMENT_GRANT_MANY_TO_ONE_FAILURE,
|
||||
);
|
||||
const ERROR_REVOKE_MANY_TO_ONE: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ADVANCEMENT_REVOKE_MANY_TO_ONE_FAILURE,
|
||||
translation::java::COMMANDS_ADVANCEMENT_REVOKE_MANY_TO_ONE_FAILURE,
|
||||
);
|
||||
const ERROR_GRANT_MANY_TO_MANY: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ADVANCEMENT_GRANT_MANY_TO_MANY_FAILURE,
|
||||
translation::java::COMMANDS_ADVANCEMENT_GRANT_MANY_TO_MANY_FAILURE,
|
||||
);
|
||||
const ERROR_REVOKE_MANY_TO_MANY: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ADVANCEMENT_REVOKE_MANY_TO_MANY_FAILURE,
|
||||
translation::java::COMMANDS_ADVANCEMENT_REVOKE_MANY_TO_MANY_FAILURE,
|
||||
);
|
||||
|
||||
const ERROR_GRANT_CRITERION_TO_ONE_FAILURE: CommandErrorType<3> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ADVANCEMENT_GRANT_CRITERION_TO_ONE_FAILURE,
|
||||
translation::java::COMMANDS_ADVANCEMENT_GRANT_CRITERION_TO_ONE_FAILURE,
|
||||
);
|
||||
|
||||
const ERROR_REVOKE_CRITERION_TO_ONE_FAILURE: CommandErrorType<3> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ADVANCEMENT_REVOKE_CRITERION_TO_ONE_FAILURE,
|
||||
translation::java::COMMANDS_ADVANCEMENT_REVOKE_CRITERION_TO_ONE_FAILURE,
|
||||
);
|
||||
|
||||
const ERROR_GRANT_CRITERION_TO_MANY_FAILURE: CommandErrorType<3> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ADVANCEMENT_GRANT_CRITERION_TO_MANY_FAILURE,
|
||||
translation::java::COMMANDS_ADVANCEMENT_GRANT_CRITERION_TO_MANY_FAILURE,
|
||||
);
|
||||
|
||||
const ERROR_REVOKE_CRITERION_TO_MANY_FAILURE: CommandErrorType<3> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ADVANCEMENT_REVOKE_CRITERION_TO_MANY_FAILURE,
|
||||
translation::java::COMMANDS_ADVANCEMENT_REVOKE_CRITERION_TO_MANY_FAILURE,
|
||||
);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum Action {
|
||||
Grant,
|
||||
Revoke,
|
||||
}
|
||||
|
||||
impl Action {
|
||||
/// inner function that directly take the locked [`PlayerAdvancement`]
|
||||
fn perform_single_inner(
|
||||
self,
|
||||
guard: &mut PlayerAdvancement,
|
||||
advancement: &'static Advancement,
|
||||
) -> bool {
|
||||
let progress = guard.progress.get_mut_or_start_progress(advancement);
|
||||
match self {
|
||||
Self::Grant => {
|
||||
if progress.is_done() {
|
||||
return false;
|
||||
}
|
||||
let criteria: Vec<Arc<str>> = progress.get_remaining_criteria().collect();
|
||||
for criterion in criteria {
|
||||
guard.award(advancement, &criterion);
|
||||
}
|
||||
true
|
||||
}
|
||||
Self::Revoke => {
|
||||
if !progress.is_done() {
|
||||
return false;
|
||||
}
|
||||
let criteria: Vec<Arc<str>> = progress.get_completed_criteria().collect();
|
||||
for criterion in criteria {
|
||||
guard.revoke(advancement, &criterion);
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs the action (grant or revoke) on multiple advancements for a single player.
|
||||
///
|
||||
/// This method applies the current action to each advancement in the provided slice for the
|
||||
/// specified player. It locks the player's advancements and processes each advancement
|
||||
/// sequentially, collecting the count of successful operations.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `player` - The player whose advancements will be modified
|
||||
/// * `advancements` - A slice of advancements to apply the action to
|
||||
/// * `show_advancement` - A flag to control advancement notification display (currently unused)
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Returns the number of advancements successfully modified. An advancement is counted as
|
||||
/// successful if [`perform_single_inner`] returns `true`
|
||||
async fn perform(
|
||||
&self,
|
||||
player: &Arc<Player>,
|
||||
advancements: &[&'static Advancement],
|
||||
show_advancement: bool,
|
||||
) -> i32 {
|
||||
let mut guard = player.advancements.lock().await;
|
||||
if !show_advancement {
|
||||
guard.flush_dirty(player, true);
|
||||
}
|
||||
let count = advancements
|
||||
.iter()
|
||||
.filter(|advancement| self.perform_single_inner(&mut guard, advancement))
|
||||
.count() as i32;
|
||||
if !show_advancement {
|
||||
guard.flush_dirty(player, false);
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
async fn perform_criterion(
|
||||
&self,
|
||||
player: &Arc<Player>,
|
||||
advancement: &'static Advancement,
|
||||
criterion: &str,
|
||||
) -> bool {
|
||||
let mut guard = player.advancements.lock().await;
|
||||
match self {
|
||||
Self::Grant => guard.award(advancement, criterion),
|
||||
Self::Revoke => guard.revoke(advancement, criterion),
|
||||
}
|
||||
}
|
||||
|
||||
/// return the corresponding key of the action
|
||||
const fn get_key(&self) -> &str {
|
||||
match self {
|
||||
Self::Grant => "commands.advancement.grant",
|
||||
Self::Revoke => "commands.advancement.revoke",
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
#[allow(unused)]
|
||||
enum Mode {
|
||||
Only,
|
||||
Through,
|
||||
From,
|
||||
Until,
|
||||
Everything,
|
||||
}
|
||||
|
||||
impl Mode {
|
||||
const fn parents(self) -> bool {
|
||||
match self {
|
||||
Self::Only | Self::From => false,
|
||||
Self::Through | Self::Until | Self::Everything => true,
|
||||
}
|
||||
}
|
||||
|
||||
const fn children(self) -> bool {
|
||||
match self {
|
||||
Self::Only | Self::Until => false,
|
||||
Self::Through | Self::From | Self::Everything => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves a collection of advancements based on the target advancement and traversal mode.
|
||||
///
|
||||
/// This function builds a list of advancements by traversing the advancement tree according to
|
||||
/// the specified mode. The traversal can include parent advancements, child advancements, or both,
|
||||
/// depending on the mode selected.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `target` - The advancement to use as the starting point for traversal
|
||||
/// * `mode` - The traversal mode that determines which advancements to include:
|
||||
/// - `Mode::Only` - Returns only the target advancement
|
||||
/// - `Mode::From` - Returns the target and all its descendants
|
||||
/// - `Mode::Until` - Returns the target and all its ancestors
|
||||
/// - `Mode::Through` - Returns the target and both ancestors and descendants
|
||||
/// - `Mode::Everything` - Returns the target and all ancestors and descendants (never used)
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// A vector of references to advancements matching the specified mode. If the target advancement
|
||||
/// is not found in the tree, a vector containing only the target is returned.
|
||||
fn get_advancements(target: &Advancement, mode: Mode) -> Vec<&Advancement> {
|
||||
let tree = &ADVANCEMENT_TREE;
|
||||
let target_node = tree.get_node_from_id(&target.id);
|
||||
target_node.map_or_else(
|
||||
|| vec![target],
|
||||
|target_node| {
|
||||
let mut advancements = Vec::new();
|
||||
if mode.parents() {
|
||||
let mut parent = target_node.parent;
|
||||
while let Some(parent_id) = parent {
|
||||
let current_node = &tree.nodes_vector[parent_id];
|
||||
advancements.push(current_node.value);
|
||||
parent = current_node.parent;
|
||||
}
|
||||
}
|
||||
advancements.push(target);
|
||||
if mode.children() {
|
||||
add_children(target_node, &mut advancements);
|
||||
}
|
||||
advancements
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn add_children(parent: &AdvancementNode, output: &mut Vec<&Advancement>) {
|
||||
for child in &parent.children {
|
||||
let node = &ADVANCEMENT_TREE.nodes_vector[*child];
|
||||
output.push(node.value);
|
||||
add_children(node, output);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
async fn perform_and_show(
|
||||
context: Arc<CommandSource>,
|
||||
players: &[Arc<Player>],
|
||||
action: Action,
|
||||
advancements: &[&'static Advancement],
|
||||
) -> Result<i32, CommandSyntaxError> {
|
||||
perform(context, players, action, advancements, true).await
|
||||
}
|
||||
|
||||
/// Performs a batch action (grant or revoke) on multiple advancements for multiple players.
|
||||
///
|
||||
/// This function iterates through each player and applies the specified action to all provided
|
||||
/// advancements. It automatically handles error messaging based on the number of players and
|
||||
/// advancements involved, as well as the number of successful operations.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `context` - The command source context used to send feedback messages to the command executor
|
||||
/// * `targets` - Slice of players who will be affected by the action
|
||||
/// * `action` - The action to perform on each advancement (Grant or Revoke)
|
||||
/// * `advancements` - Slice of advancements to apply the action to
|
||||
/// * `show_advancement` - Whether to show advancement notifications to players (currently unused)
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Returns `Ok(i)` with the total count of successful operations if at least one advancement
|
||||
/// was successfully modified for at least one player.
|
||||
///
|
||||
/// Returns `Err` with an appropriate localized error message if no operations succeeded. The
|
||||
/// error message varies based on:
|
||||
/// - Whether one or many players were targeted
|
||||
/// - Whether one or many advancements were involved
|
||||
/// - The type of action (Grant or Revoke)
|
||||
async fn perform(
|
||||
context: Arc<CommandSource>,
|
||||
targets: &[Arc<Player>],
|
||||
action: Action,
|
||||
advancements: &[&'static Advancement],
|
||||
show_advancement: bool,
|
||||
) -> Result<i32, CommandSyntaxError> {
|
||||
let mut i = 0;
|
||||
for player in targets {
|
||||
i += action.perform(player, advancements, show_advancement).await;
|
||||
}
|
||||
if i == 0 {
|
||||
return if let [first_advancement] = advancements[..] {
|
||||
if let [first_player] = targets {
|
||||
Err(match action {
|
||||
Action::Grant => &ERROR_GRANT_ONE_TO_ONE,
|
||||
Action::Revoke => &ERROR_REVOKE_ONE_TO_ONE,
|
||||
}
|
||||
.create_without_context_args_slice(&[
|
||||
first_advancement.name(),
|
||||
first_player.get_display_name().await,
|
||||
]))
|
||||
} else {
|
||||
Err(match action {
|
||||
Action::Grant => &ERROR_GRANT_ONE_TO_MANY,
|
||||
Action::Revoke => &ERROR_REVOKE_ONE_TO_MANY,
|
||||
}
|
||||
.create_without_context_args_slice(&[
|
||||
first_advancement.name(),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
]))
|
||||
}
|
||||
} else if let [first_player] = targets {
|
||||
Err(match action {
|
||||
Action::Grant => &ERROR_GRANT_MANY_TO_ONE,
|
||||
Action::Revoke => &ERROR_REVOKE_MANY_TO_ONE,
|
||||
}
|
||||
.create_without_context_args_slice(&[
|
||||
TextComponent::text(advancements.len().to_string()),
|
||||
first_player.get_display_name().await,
|
||||
]))
|
||||
} else {
|
||||
Err(match action {
|
||||
Action::Grant => &ERROR_GRANT_MANY_TO_MANY,
|
||||
Action::Revoke => &ERROR_REVOKE_MANY_TO_MANY,
|
||||
}
|
||||
.create_without_context_args_slice(&[
|
||||
TextComponent::text(advancements.len().to_string()),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
]))
|
||||
};
|
||||
}
|
||||
let translate = if let [first_advancement] = advancements[..] {
|
||||
if let [first_player] = targets {
|
||||
TextComponent::translate(
|
||||
format!("{}.one.to.one.success", action.get_key()),
|
||||
[
|
||||
first_advancement.name(),
|
||||
first_player.get_display_name().await,
|
||||
],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate(
|
||||
format!("{}.one.to.many.success", action.get_key()),
|
||||
[
|
||||
first_advancement.name(),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
)
|
||||
}
|
||||
} else if let [first] = targets {
|
||||
TextComponent::translate(
|
||||
format!("{}.many.to.one.success", action.get_key()),
|
||||
[
|
||||
TextComponent::text(advancements.len().to_string()),
|
||||
first.get_display_name().await,
|
||||
],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate(
|
||||
format!("{}.many.to.many.success", action.get_key()),
|
||||
[
|
||||
TextComponent::text(advancements.len().to_string()),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
)
|
||||
};
|
||||
context.send_feedback(translate, true).await;
|
||||
Ok(i)
|
||||
}
|
||||
|
||||
/// Performs an action (grant or revoke) on a specific advancement criterion for multiple players.
|
||||
///
|
||||
/// This function attempts to apply the specified action to a criterion of an advancement for each
|
||||
/// of the given players. It handles error reporting based on the number of successful operations
|
||||
/// and provides feedback to the command source.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `context` - The command source context for sending feedback
|
||||
/// * `targets` - The players to apply the action to
|
||||
/// * `action` - The action to perform (Grant or Revoke)
|
||||
/// * `advancement` - The advancement containing the criterion
|
||||
/// * `criterion` - The specific criterion name to operate on
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Returns `Ok(count)` with the number of successful operations if at least one succeeded.
|
||||
/// Returns `Err` with an appropriate error message if:
|
||||
/// - The criterion doesn't exist in the advancement
|
||||
/// - No operations succeeded
|
||||
pub async fn perform_criterion(
|
||||
context: Arc<CommandSource>,
|
||||
targets: &[Arc<Player>],
|
||||
action: Action,
|
||||
advancement: &'static Advancement,
|
||||
criterion: &str,
|
||||
) -> Result<i32, CommandSyntaxError> {
|
||||
if advancement.criteria.contains(&criterion) {
|
||||
let count = join_all(
|
||||
targets
|
||||
.iter()
|
||||
.map(|player| action.perform_criterion(player, advancement, criterion)),
|
||||
)
|
||||
.await
|
||||
.into_iter()
|
||||
.filter(|&success| success)
|
||||
.count() as i32;
|
||||
if count == 0 {
|
||||
if let [first_player] = targets {
|
||||
Err(match action {
|
||||
Action::Grant => &ERROR_GRANT_CRITERION_TO_ONE_FAILURE,
|
||||
Action::Revoke => &ERROR_REVOKE_CRITERION_TO_ONE_FAILURE,
|
||||
}
|
||||
.create_without_context_args_slice(&[
|
||||
TextComponent::text(criterion.to_owned()),
|
||||
advancement.name(),
|
||||
first_player.get_display_name().await,
|
||||
]))
|
||||
} else {
|
||||
Err(match action {
|
||||
Action::Grant => &ERROR_GRANT_CRITERION_TO_MANY_FAILURE,
|
||||
Action::Revoke => &ERROR_REVOKE_CRITERION_TO_MANY_FAILURE,
|
||||
}
|
||||
.create_without_context_args_slice(&[
|
||||
TextComponent::text(criterion.to_owned()),
|
||||
advancement.name(),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
]))
|
||||
}
|
||||
} else {
|
||||
let translate = if let [first_player] = targets {
|
||||
TextComponent::translate(
|
||||
format!("{}.criterion.to.one.success", action.get_key()),
|
||||
[
|
||||
TextComponent::text(criterion.to_owned()),
|
||||
advancement.name(),
|
||||
first_player.get_display_name().await,
|
||||
],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate(
|
||||
format!("{}.criterion.to.many.success", action.get_key()),
|
||||
[
|
||||
TextComponent::text(criterion.to_owned()),
|
||||
advancement.name(),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
)
|
||||
};
|
||||
context.send_feedback(translate, true).await;
|
||||
Ok(count)
|
||||
}
|
||||
} else {
|
||||
Err(ERROR_CRITERION_NOT_FOUND.create_without_context(
|
||||
advancement.name(),
|
||||
TextComponent::text(criterion.to_owned()),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// use for when a criterion is specified to on grant/revoke this criterion
|
||||
struct OnlyAdvancementCriterionExecutor {
|
||||
action: Action,
|
||||
}
|
||||
|
||||
impl CommandExecutor for OnlyAdvancementCriterionExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
let action = self.action;
|
||||
Box::pin(async move {
|
||||
perform_criterion(
|
||||
context.source.clone(),
|
||||
&EntityArgumentType::get_players(context, ARG_TARGETS).await?,
|
||||
action,
|
||||
ResourceKeyArgument::get_advancement(context, ARG_ADVANCEMENT)?,
|
||||
StringArgumentType::get(context, ARG_CRITERION)?,
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// use to grant/revoke advancement depending on the selected `mode`
|
||||
struct AdvancementExecutor {
|
||||
action: Action,
|
||||
mode: Mode,
|
||||
}
|
||||
|
||||
impl CommandExecutor for AdvancementExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
let action = self.action;
|
||||
let mode = self.mode;
|
||||
Box::pin(async move {
|
||||
perform_and_show(
|
||||
context.source.clone(),
|
||||
&EntityArgumentType::get_players(context, ARG_TARGETS).await?,
|
||||
action,
|
||||
&get_advancements(
|
||||
ResourceKeyArgument::get_advancement(context, ARG_ADVANCEMENT)?,
|
||||
mode,
|
||||
),
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// suggest the corresponding criterion of the specified advancement
|
||||
struct CriterionSuggestionProvider;
|
||||
|
||||
impl SuggestionProvider for CriterionSuggestionProvider {
|
||||
fn suggest<'a>(
|
||||
&'a self,
|
||||
context: &'a CommandContext,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> SuggestionProviderResult<'a> {
|
||||
let suggestion = ResourceKeyArgument::get_advancement(context, ARG_ADVANCEMENT)
|
||||
.ok()
|
||||
.map(|adv| adv.criteria)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(ToString::to_string);
|
||||
Box::pin(async move { builder.filter_and_suggest_iter(suggestion).build() })
|
||||
}
|
||||
}
|
||||
|
||||
/// executor to grant/revoke every advancement to specified players
|
||||
struct EveryAdvancementExecutor {
|
||||
action: Action,
|
||||
}
|
||||
|
||||
impl CommandExecutor for EveryAdvancementExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
let action = self.action;
|
||||
Box::pin(async move {
|
||||
perform(
|
||||
context.source.clone(),
|
||||
&EntityArgumentType::get_players(context, ARG_TARGETS).await?,
|
||||
action,
|
||||
&Advancement::get_advancements_list(),
|
||||
false,
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// register the advancement command
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
));
|
||||
|
||||
macro_rules! build_action {
|
||||
($name:expr, $action:expr) => {
|
||||
literal($name).then(
|
||||
argument(ARG_TARGETS, EntityArgumentType::Players)
|
||||
.then(
|
||||
literal("only").then(
|
||||
argument(
|
||||
ARG_ADVANCEMENT,
|
||||
ResourceKeyArgument(ADVANCEMENT_REGISTRY.clone()),
|
||||
)
|
||||
.executes(AdvancementExecutor {
|
||||
action: $action,
|
||||
mode: Mode::Only,
|
||||
})
|
||||
.then(
|
||||
argument(ARG_CRITERION, StringArgumentType::GreedyPhrase)
|
||||
.suggests(CriterionSuggestionProvider)
|
||||
.executes(OnlyAdvancementCriterionExecutor { action: $action }),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("from").then(
|
||||
argument(
|
||||
ARG_ADVANCEMENT,
|
||||
ResourceKeyArgument(ADVANCEMENT_REGISTRY.clone()),
|
||||
)
|
||||
.executes(AdvancementExecutor {
|
||||
action: $action,
|
||||
mode: Mode::From,
|
||||
}),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("until").then(
|
||||
argument(
|
||||
ARG_ADVANCEMENT,
|
||||
ResourceKeyArgument(ADVANCEMENT_REGISTRY.clone()),
|
||||
)
|
||||
.executes(AdvancementExecutor {
|
||||
action: $action,
|
||||
mode: Mode::Until,
|
||||
}),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("through").then(
|
||||
argument(
|
||||
ARG_ADVANCEMENT,
|
||||
ResourceKeyArgument(ADVANCEMENT_REGISTRY.clone()),
|
||||
)
|
||||
.executes(AdvancementExecutor {
|
||||
action: $action,
|
||||
mode: Mode::Through,
|
||||
}),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("everything")
|
||||
.executes(EveryAdvancementExecutor { action: $action }),
|
||||
),
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
dispatcher.register(
|
||||
command(NAME, DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.then(build_action!("grant", Action::Grant))
|
||||
.then(build_action!("revoke", Action::Revoke)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,530 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command, literal};
|
||||
use crate::command::argument_types::attribute::AttributeArgumentType;
|
||||
use crate::command::argument_types::core::double::DoubleArgumentType;
|
||||
use crate::command::argument_types::core::string::StringArgumentType;
|
||||
use crate::command::argument_types::entity::EntityArgumentType;
|
||||
use crate::command::argument_types::uuid::UuidArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use crate::entity::attributes::ModifierOperation;
|
||||
use pumpkin_data::attributes::Attributes;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const DESCRIPTION: &str = "Queries or modifies attributes of an entity.";
|
||||
const PERMISSION: &str = "minecraft:command.attribute";
|
||||
|
||||
const ARG_TARGET: &str = "target";
|
||||
const ARG_ATTRIBUTE: &str = "attribute";
|
||||
const ARG_SCALE: &str = "scale";
|
||||
const ARG_VALUE: &str = "value";
|
||||
const ARG_UUID: &str = "uuid";
|
||||
const ARG_NAME: &str = "name";
|
||||
|
||||
const FAILED_ENTITY_ERROR: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ATTRIBUTE_FAILED_ENTITY,
|
||||
translation::java::COMMANDS_ATTRIBUTE_FAILED_ENTITY,
|
||||
);
|
||||
|
||||
const NO_ATTRIBUTE_ERROR: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ATTRIBUTE_FAILED_NO_ATTRIBUTE,
|
||||
translation::java::COMMANDS_ATTRIBUTE_FAILED_NO_ATTRIBUTE,
|
||||
);
|
||||
|
||||
const MODIFIER_ALREADY_PRESENT_ERROR: CommandErrorType<3> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ATTRIBUTE_FAILED_MODIFIER_ALREADY_PRESENT,
|
||||
translation::java::COMMANDS_ATTRIBUTE_FAILED_MODIFIER_ALREADY_PRESENT,
|
||||
);
|
||||
|
||||
const NO_MODIFIER_ERROR: CommandErrorType<3> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_ATTRIBUTE_FAILED_NO_MODIFIER,
|
||||
translation::java::COMMANDS_ATTRIBUTE_FAILED_NO_MODIFIER,
|
||||
);
|
||||
|
||||
fn attribute_translation_key(attribute: &Attributes) -> String {
|
||||
let path = attribute
|
||||
.name
|
||||
.strip_prefix("minecraft:")
|
||||
.unwrap_or(attribute.name);
|
||||
format!("attribute.name.{path}")
|
||||
}
|
||||
|
||||
struct GetExecutor {
|
||||
is_base: bool,
|
||||
has_scale: bool,
|
||||
}
|
||||
|
||||
impl CommandExecutor for GetExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
let scale = if self.has_scale {
|
||||
DoubleArgumentType::get(context, ARG_SCALE)?
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
|
||||
let has_attr = living
|
||||
.attributes
|
||||
.read()
|
||||
.unwrap()
|
||||
.contains_key(&attribute.id);
|
||||
if !has_attr {
|
||||
return Err(NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
));
|
||||
}
|
||||
|
||||
if self.is_base {
|
||||
let base_value = living.get_attribute_base(&attribute);
|
||||
let scaled_value = base_value * scale;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_GET_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_GET_SUCCESS,
|
||||
[
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(base_value.to_string()),
|
||||
],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(scaled_value as i32)
|
||||
} else {
|
||||
let value = living.get_attribute_value(&attribute);
|
||||
let scaled_value = value * scale;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_VALUE_GET_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_VALUE_GET_SUCCESS,
|
||||
[
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(value.to_string()),
|
||||
],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(scaled_value as i32)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct BaseSetExecutor;
|
||||
|
||||
impl CommandExecutor for BaseSetExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
let value = DoubleArgumentType::get(context, ARG_VALUE)?;
|
||||
|
||||
let has_attr = living
|
||||
.attributes
|
||||
.read()
|
||||
.unwrap()
|
||||
.contains_key(&attribute.id);
|
||||
if !has_attr {
|
||||
return Err(NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
));
|
||||
}
|
||||
|
||||
living.set_attribute_base(&attribute, value);
|
||||
crate::entity::attributes::send_attribute_updates_for_living(
|
||||
living,
|
||||
vec![attribute.clone()],
|
||||
)
|
||||
.await;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_SET_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_SET_SUCCESS,
|
||||
[
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(value.to_string()),
|
||||
],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(value as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct BaseResetExecutor;
|
||||
|
||||
impl CommandExecutor for BaseResetExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
|
||||
let has_attr = living
|
||||
.attributes
|
||||
.read()
|
||||
.unwrap()
|
||||
.contains_key(&attribute.id);
|
||||
if !has_attr {
|
||||
return Err(NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
));
|
||||
}
|
||||
|
||||
let default_val = attribute.default_value;
|
||||
living.set_attribute_base(&attribute, default_val);
|
||||
crate::entity::attributes::send_attribute_updates_for_living(
|
||||
living,
|
||||
vec![attribute.clone()],
|
||||
)
|
||||
.await;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_RESET_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_RESET_SUCCESS,
|
||||
[
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(default_val.to_string()),
|
||||
],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(default_val as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ModifierAddExecutor {
|
||||
operation: ModifierOperation,
|
||||
}
|
||||
|
||||
impl CommandExecutor for ModifierAddExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
let uuid = UuidArgumentType::get(context, ARG_UUID)?;
|
||||
let _name = StringArgumentType::get(context, ARG_NAME)?;
|
||||
let value = DoubleArgumentType::get(context, ARG_VALUE)?;
|
||||
|
||||
let modifier_id = uuid.to_string();
|
||||
|
||||
let res = {
|
||||
let mut map = living.attributes.write().unwrap();
|
||||
let inst = map.get_mut(&attribute.id).ok_or_else(|| {
|
||||
NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
)
|
||||
})?;
|
||||
|
||||
if inst.modifiers.iter().any(|m| m.id == modifier_id) {
|
||||
Err(MODIFIER_ALREADY_PRESENT_ERROR.create_without_context(
|
||||
TextComponent::text(modifier_id.clone()),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
))
|
||||
} else {
|
||||
inst.modifiers.push(crate::entity::attributes::Modifier {
|
||||
id: modifier_id.clone(),
|
||||
amount: value,
|
||||
operation: self.operation,
|
||||
});
|
||||
inst.dirty.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
res?;
|
||||
|
||||
crate::entity::attributes::send_attribute_updates_for_living(
|
||||
living,
|
||||
vec![attribute.clone()],
|
||||
)
|
||||
.await;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_ADD_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_ADD_SUCCESS,
|
||||
[
|
||||
TextComponent::text(modifier_id),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ModifierRemoveExecutor;
|
||||
|
||||
impl CommandExecutor for ModifierRemoveExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
let uuid = UuidArgumentType::get(context, ARG_UUID)?;
|
||||
|
||||
let modifier_id = uuid.to_string();
|
||||
|
||||
let res = {
|
||||
let mut map = living.attributes.write().unwrap();
|
||||
let inst = map.get_mut(&attribute.id).ok_or_else(|| {
|
||||
NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
)
|
||||
})?;
|
||||
|
||||
let index = inst
|
||||
.modifiers
|
||||
.iter()
|
||||
.position(|m| m.id == modifier_id)
|
||||
.ok_or_else(|| {
|
||||
NO_MODIFIER_ERROR.create_without_context(
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(modifier_id.clone()),
|
||||
)
|
||||
})?;
|
||||
|
||||
inst.modifiers.remove(index);
|
||||
inst.dirty.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
Ok(())
|
||||
};
|
||||
res?;
|
||||
|
||||
crate::entity::attributes::send_attribute_updates_for_living(
|
||||
living,
|
||||
vec![attribute.clone()],
|
||||
)
|
||||
.await;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_REMOVE_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_REMOVE_SUCCESS,
|
||||
[
|
||||
TextComponent::text(modifier_id),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ModifierGetExecutor;
|
||||
|
||||
impl CommandExecutor for ModifierGetExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
||||
let living = target
|
||||
.get_living_entity()
|
||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||
|
||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||
let uuid = UuidArgumentType::get(context, ARG_UUID)?;
|
||||
|
||||
let modifier_id = uuid.to_string();
|
||||
|
||||
let val = {
|
||||
let map = living.attributes.read().unwrap();
|
||||
let inst = map.get(&attribute.id).ok_or_else(|| {
|
||||
NO_ATTRIBUTE_ERROR.create_without_context(
|
||||
target.get_name(),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
)
|
||||
})?;
|
||||
|
||||
let modifier = inst
|
||||
.modifiers
|
||||
.iter()
|
||||
.find(|m| m.id == modifier_id)
|
||||
.ok_or_else(|| {
|
||||
NO_MODIFIER_ERROR.create_without_context(
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(modifier_id.clone()),
|
||||
)
|
||||
})?;
|
||||
|
||||
modifier.amount
|
||||
};
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_VALUE_GET_SUCCESS,
|
||||
translation::java::COMMANDS_ATTRIBUTE_MODIFIER_VALUE_GET_SUCCESS,
|
||||
[
|
||||
TextComponent::text(modifier_id),
|
||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||
target.get_name(),
|
||||
TextComponent::text(val.to_string()),
|
||||
],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(val as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("attribute", DESCRIPTION).requires(PERMISSION).then(
|
||||
argument(ARG_TARGET, EntityArgumentType::Entity).then(
|
||||
argument(ARG_ATTRIBUTE, AttributeArgumentType)
|
||||
.then(
|
||||
literal("get")
|
||||
.executes(GetExecutor {
|
||||
is_base: false,
|
||||
has_scale: false,
|
||||
})
|
||||
.then(argument(ARG_SCALE, DoubleArgumentType::any()).executes(
|
||||
GetExecutor {
|
||||
is_base: false,
|
||||
has_scale: true,
|
||||
},
|
||||
)),
|
||||
)
|
||||
.then(
|
||||
literal("base")
|
||||
.then(
|
||||
literal("get")
|
||||
.executes(GetExecutor {
|
||||
is_base: true,
|
||||
has_scale: false,
|
||||
})
|
||||
.then(argument(ARG_SCALE, DoubleArgumentType::any()).executes(
|
||||
GetExecutor {
|
||||
is_base: true,
|
||||
has_scale: true,
|
||||
},
|
||||
)),
|
||||
)
|
||||
.then(
|
||||
literal("set").then(
|
||||
argument(ARG_VALUE, DoubleArgumentType::any())
|
||||
.executes(BaseSetExecutor),
|
||||
),
|
||||
)
|
||||
.then(literal("reset").executes(BaseResetExecutor)),
|
||||
)
|
||||
.then(
|
||||
literal("modifier")
|
||||
.then(
|
||||
literal("add").then(
|
||||
argument(ARG_UUID, UuidArgumentType).then(
|
||||
argument(ARG_NAME, StringArgumentType::SingleWord).then(
|
||||
argument(ARG_VALUE, DoubleArgumentType::any())
|
||||
.then(literal("add").executes(
|
||||
ModifierAddExecutor {
|
||||
operation: ModifierOperation::Add,
|
||||
},
|
||||
))
|
||||
.then(literal("multiply").executes(
|
||||
ModifierAddExecutor {
|
||||
operation: ModifierOperation::MultiplyTotal,
|
||||
},
|
||||
))
|
||||
.then(literal("multiply_base").executes(
|
||||
ModifierAddExecutor {
|
||||
operation: ModifierOperation::MultiplyBase,
|
||||
},
|
||||
)),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("remove").then(
|
||||
argument(ARG_UUID, UuidArgumentType)
|
||||
.executes(ModifierRemoveExecutor),
|
||||
),
|
||||
)
|
||||
.then(literal("value").then(literal("get").then(
|
||||
argument(ARG_UUID, UuidArgumentType).executes(ModifierGetExecutor),
|
||||
))),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
use crate::command::CommandResult;
|
||||
use crate::{
|
||||
command::{
|
||||
CommandError, CommandExecutor, CommandSender,
|
||||
args::{
|
||||
Arg, ConsumedArgs,
|
||||
gameprofile::{GameProfileSuggestionMode, GameProfilesArgumentConsumer},
|
||||
message::MsgArgConsumer,
|
||||
},
|
||||
tree::{CommandTree, builder::argument},
|
||||
},
|
||||
data::{SaveJSONConfiguration, banlist_serializer::BannedPlayerEntry},
|
||||
net::{DisconnectReason, GameProfile},
|
||||
};
|
||||
use CommandError::InvalidConsumption;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const NAMES: [&str; 1] = ["ban"];
|
||||
const DESCRIPTION: &str = "bans a player";
|
||||
|
||||
const ARG_TARGET: &str = "player";
|
||||
const ARG_REASON: &str = "reason";
|
||||
|
||||
struct NoReasonExecutor;
|
||||
|
||||
impl CommandExecutor for NoReasonExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
|
||||
ban_players(sender, server, targets.as_slice(), None).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ReasonExecutor;
|
||||
|
||||
impl CommandExecutor for ReasonExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
|
||||
let Some(Arg::Msg(reason)) = args.get(ARG_REASON) else {
|
||||
return Err(InvalidConsumption(Some(ARG_REASON.into())));
|
||||
};
|
||||
|
||||
ban_players(sender, server, targets.as_slice(), Some(reason)).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the number of players successfully banned.
|
||||
async fn ban_players(
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
targets: &[GameProfile],
|
||||
reason: Option<&String>,
|
||||
) -> Result<i32, CommandError> {
|
||||
let mut count: usize = 0;
|
||||
for target in targets {
|
||||
if ban_profile(sender, server, target, reason.cloned()).await {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BAN_FAILED,
|
||||
translation::bedrock::COMMANDS_BAN_FAILED,
|
||||
[],
|
||||
)))
|
||||
} else {
|
||||
Ok(count as i32)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if the player was successfully banned.
|
||||
async fn ban_profile(
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
profile: &GameProfile,
|
||||
reason: Option<String>,
|
||||
) -> bool {
|
||||
let mut banned_players = server.data.banned_player_list.write().await;
|
||||
|
||||
let reason = reason.unwrap_or_else(|| "Banned by an operator.".to_string());
|
||||
|
||||
if let Some(entry) = banned_players
|
||||
.banned_players
|
||||
.iter_mut()
|
||||
.find(|entry| entry.uuid == profile.id)
|
||||
{
|
||||
if entry.name != profile.name {
|
||||
entry.name.clone_from(&profile.name);
|
||||
banned_players.save();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
banned_players.banned_players.push(BannedPlayerEntry::new(
|
||||
profile,
|
||||
sender.to_string(),
|
||||
None,
|
||||
reason.clone(),
|
||||
));
|
||||
|
||||
banned_players.save();
|
||||
drop(banned_players);
|
||||
|
||||
// Send messages
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BAN_SUCCESS,
|
||||
translation::bedrock::COMMANDS_BAN_SUCCESS,
|
||||
[
|
||||
TextComponent::text(profile.name.clone()),
|
||||
TextComponent::text(reason),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
|
||||
if let Some(player) = server.get_player_by_uuid(profile.id) {
|
||||
player
|
||||
.kick(
|
||||
DisconnectReason::Kicked,
|
||||
TextComponent::translate_cross(
|
||||
translation::java::MULTIPLAYER_DISCONNECT_BANNED,
|
||||
translation::bedrock::DISCONNECTIONSCREEN_TITLE_BANNEDBYHOST,
|
||||
[],
|
||||
),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(
|
||||
ARG_TARGET,
|
||||
GameProfilesArgumentConsumer::new(GameProfileSuggestionMode::OnlinePlayers, true),
|
||||
)
|
||||
.execute(NoReasonExecutor)
|
||||
.then(argument(ARG_REASON, MsgArgConsumer).execute(ReasonExecutor)),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
use std::{net::IpAddr, str::FromStr};
|
||||
|
||||
use crate::{
|
||||
command::{
|
||||
CommandError, CommandExecutor, CommandResult, CommandSender,
|
||||
args::{Arg, ConsumedArgs, message::MsgArgConsumer, simple::SimpleArgConsumer},
|
||||
tree::{CommandTree, builder::argument},
|
||||
},
|
||||
data::{SaveJSONConfiguration, banlist_serializer::BannedIpEntry},
|
||||
net::DisconnectReason,
|
||||
server::Server,
|
||||
};
|
||||
use CommandError::InvalidConsumption;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const NAMES: [&str; 1] = ["ban-ip"];
|
||||
const DESCRIPTION: &str = "bans a player-ip";
|
||||
|
||||
const ARG_TARGET: &str = "ip";
|
||||
const ARG_REASON: &str = "reason";
|
||||
|
||||
fn parse_ip(target: &str, server: &Server) -> Option<IpAddr> {
|
||||
Some(match IpAddr::from_str(target) {
|
||||
Ok(ip) => ip,
|
||||
Err(_) => server.get_player_by_name(target)?.client.address().ip(),
|
||||
})
|
||||
}
|
||||
|
||||
struct NoReasonExecutor;
|
||||
|
||||
impl CommandExecutor for NoReasonExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Simple(target)) = args.get(&ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
|
||||
ban_ip(sender, server, target, None).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ReasonExecutor;
|
||||
|
||||
impl CommandExecutor for ReasonExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Simple(target)) = args.get(&ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
|
||||
let Some(Arg::Msg(reason)) = args.get(ARG_REASON) else {
|
||||
return Err(InvalidConsumption(Some(ARG_REASON.into())));
|
||||
};
|
||||
|
||||
ban_ip(sender, server, target, Some(reason.clone())).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn ban_ip(
|
||||
sender: &CommandSender,
|
||||
server: &Server,
|
||||
target: &str,
|
||||
reason: Option<String>,
|
||||
) -> Result<i32, CommandError> {
|
||||
let reason = reason.unwrap_or_else(|| "Banned by an operator.".to_string());
|
||||
|
||||
let Some(target_ip) = parse_ip(target, server) else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANIP_INVALID,
|
||||
translation::bedrock::COMMANDS_BANIP_INVALID,
|
||||
[],
|
||||
)));
|
||||
};
|
||||
|
||||
let mut banned_ips = server.data.banned_ip_list.write().await;
|
||||
|
||||
if banned_ips.get_entry(&target_ip).is_some() {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANIP_FAILED,
|
||||
translation::java::COMMANDS_BANIP_FAILED,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
banned_ips.banned_ips.push(BannedIpEntry::new(
|
||||
target_ip,
|
||||
sender.to_string(),
|
||||
None,
|
||||
reason.clone(),
|
||||
));
|
||||
|
||||
banned_ips.save();
|
||||
drop(banned_ips);
|
||||
|
||||
// Send messages
|
||||
let affected = server.get_players_by_ip(target_ip);
|
||||
let names = affected
|
||||
.iter()
|
||||
.map(|p| p.gameprofile.name.clone())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANIP_SUCCESS,
|
||||
translation::bedrock::COMMANDS_BANIP_SUCCESS,
|
||||
[
|
||||
TextComponent::text(target_ip.to_string()),
|
||||
TextComponent::text(reason),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANIP_INFO,
|
||||
translation::java::COMMANDS_BANIP_INFO,
|
||||
[
|
||||
TextComponent::text(affected.len().to_string()),
|
||||
TextComponent::text(names),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
|
||||
let count = affected.len();
|
||||
for target in affected {
|
||||
target
|
||||
.kick(
|
||||
DisconnectReason::Kicked,
|
||||
TextComponent::translate_cross(
|
||||
translation::java::MULTIPLAYER_DISCONNECT_IP_BANNED,
|
||||
translation::java::MULTIPLAYER_DISCONNECT_IP_BANNED,
|
||||
[],
|
||||
),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(count as i32)
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(ARG_TARGET, SimpleArgConsumer)
|
||||
.execute(NoReasonExecutor)
|
||||
.then(argument(ARG_REASON, MsgArgConsumer).execute(ReasonExecutor)),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, command, literal};
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const DESCRIPTION: &str = "Prints the banlist of players, IPs, or both at once.";
|
||||
|
||||
const PERMISSION: &str = "minecraft:command.banlist";
|
||||
|
||||
struct BanListEntry {
|
||||
name: String,
|
||||
source: String,
|
||||
reason: String,
|
||||
}
|
||||
|
||||
struct BanListCommandExecutor {
|
||||
players: bool,
|
||||
ips: bool,
|
||||
}
|
||||
|
||||
impl CommandExecutor for BanListCommandExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let mut entries = Vec::new();
|
||||
|
||||
let data = &context.server().data;
|
||||
|
||||
if self.players {
|
||||
let lock = data.banned_player_list.read().await;
|
||||
for entry in &lock.banned_players {
|
||||
entries.push(BanListEntry {
|
||||
name: entry.name.clone(),
|
||||
source: entry.source.clone(),
|
||||
reason: entry.reason.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if self.ips {
|
||||
let lock = data.banned_ip_list.read().await;
|
||||
for entry in &lock.banned_ips {
|
||||
entries.push(BanListEntry {
|
||||
name: entry.ip.to_string(),
|
||||
source: entry.source.clone(),
|
||||
reason: entry.reason.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let entries_len = entries.len() as i32;
|
||||
let source = &context.source;
|
||||
|
||||
if entries.is_empty() {
|
||||
source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANLIST_NONE,
|
||||
translation::java::COMMANDS_BANLIST_NONE,
|
||||
[],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
} else {
|
||||
let bedrock_list_key = if self.ips && !self.players {
|
||||
translation::bedrock::COMMANDS_BANLIST_IPS
|
||||
} else {
|
||||
translation::bedrock::COMMANDS_BANLIST_PLAYERS
|
||||
};
|
||||
|
||||
source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANLIST_LIST,
|
||||
bedrock_list_key,
|
||||
[TextComponent::text(entries.len().to_string())],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
|
||||
for entry in entries {
|
||||
source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BANLIST_ENTRY,
|
||||
translation::java::COMMANDS_BANLIST_ENTRY,
|
||||
[
|
||||
TextComponent::text(entry.name),
|
||||
TextComponent::text(entry.source),
|
||||
TextComponent::text(entry.reason),
|
||||
],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(entries_len)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Three),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("banlist", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.then(literal("ips").executes(BanListCommandExecutor {
|
||||
players: false,
|
||||
ips: true,
|
||||
}))
|
||||
.then(literal("players").executes(BanListCommandExecutor {
|
||||
players: true,
|
||||
ips: false,
|
||||
}))
|
||||
.executes(BanListCommandExecutor {
|
||||
players: true,
|
||||
ips: true,
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,677 @@
|
||||
use crate::command::args::bool::BoolArgConsumer;
|
||||
use crate::command::args::bossbar_color::BossbarColorArgumentConsumer;
|
||||
use crate::command::args::bossbar_style::BossbarStyleArgumentConsumer;
|
||||
use crate::command::args::bounded_num::BoundedNumArgumentConsumer;
|
||||
use crate::command::args::players::PlayersArgumentConsumer;
|
||||
use crate::command::args::resource_location::ResourceLocationArgumentConsumer;
|
||||
|
||||
use crate::command::args::{ConsumedArgs, FindArg, FindArgDefaultName};
|
||||
|
||||
use crate::command::args::textcomponent::TextComponentArgConsumer;
|
||||
use crate::command::dispatcher::CommandError;
|
||||
use crate::command::tree::CommandTree;
|
||||
use crate::command::tree::builder::{argument, argument_default_name, literal};
|
||||
use crate::command::{CommandExecutor, CommandResult, CommandSender};
|
||||
use crate::world::bossbar::Bossbar;
|
||||
use crate::world::custom_bossbar::BossbarUpdateError;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_util::text::hover::HoverEvent;
|
||||
use uuid::Uuid;
|
||||
|
||||
const NAMES: [&str; 1] = ["bossbar"];
|
||||
const DESCRIPTION: &str = "Display bossbar";
|
||||
|
||||
const ARG_NAME: &str = "name";
|
||||
|
||||
const ARG_VISIBLE: &str = "visible";
|
||||
|
||||
const fn autocomplete_consumer() -> ResourceLocationArgumentConsumer {
|
||||
// TODO: Add autocompletion when implemented properly
|
||||
ResourceLocationArgumentConsumer
|
||||
}
|
||||
|
||||
enum CommandValueGet {
|
||||
Max,
|
||||
Players,
|
||||
Value,
|
||||
Visible,
|
||||
}
|
||||
|
||||
enum CommandValueSet {
|
||||
Color,
|
||||
Max,
|
||||
Name,
|
||||
Players(bool),
|
||||
Style,
|
||||
Value,
|
||||
Visible,
|
||||
}
|
||||
|
||||
struct AddExecutor;
|
||||
|
||||
impl CommandExecutor for AddExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let mut namespace = autocomplete_consumer()
|
||||
.find_arg_default_name(args)?
|
||||
.to_string();
|
||||
if !namespace.contains(':') {
|
||||
namespace = format!("minecraft:{namespace}");
|
||||
}
|
||||
|
||||
let text_component = TextComponentArgConsumer::find_arg(args, ARG_NAME)?;
|
||||
|
||||
if server.bossbars.lock().await.has_bossbar(&namespace) {
|
||||
return Result::Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_CREATE_FAILED,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_ADD_FAILURE_EXISTS,
|
||||
[TextComponent::text(namespace.clone())],
|
||||
)));
|
||||
}
|
||||
|
||||
let bossbar = Bossbar::new(text_component);
|
||||
let mut bossbars = server.bossbars.lock().await;
|
||||
|
||||
bossbars.create_bossbar(namespace.clone(), bossbar.clone());
|
||||
let new_size = bossbars.get_bossbars_len();
|
||||
drop(bossbars);
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_CREATE_SUCCESS,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_ADD_SUCCESS,
|
||||
[bossbar_prefix(bossbar.title.clone(), namespace.clone())],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(new_size as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct GetExecutor(CommandValueGet);
|
||||
|
||||
impl CommandExecutor for GetExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let namespace = autocomplete_consumer()
|
||||
.find_arg_default_name(args)?
|
||||
.to_string();
|
||||
|
||||
let Some(bossbar) = server.bossbars.lock().await.get_bossbar(&namespace) else {
|
||||
return Err(handle_bossbar_error(
|
||||
BossbarUpdateError::InvalidResourceLocation(namespace.clone()),
|
||||
));
|
||||
};
|
||||
|
||||
match self.0 {
|
||||
CommandValueGet::Max => {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_GET_MAX,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_MAX,
|
||||
[
|
||||
bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.clone(),
|
||||
),
|
||||
TextComponent::text(bossbar.max.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
Ok(bossbar.max)
|
||||
}
|
||||
CommandValueGet::Players => Ok(bossbar.players.len() as i32),
|
||||
CommandValueGet::Value => {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_GET_VALUE,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_VALUE,
|
||||
[
|
||||
bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.clone(),
|
||||
),
|
||||
TextComponent::text(bossbar.value.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
Ok(bossbar.value)
|
||||
}
|
||||
CommandValueGet::Visible => {
|
||||
let (java_key, bedrock_key) = if bossbar.visible {
|
||||
(
|
||||
translation::java::COMMANDS_BOSSBAR_SET_VISIBLE_SUCCESS_VISIBLE,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_VISIBLE_TRUE,
|
||||
)
|
||||
} else {
|
||||
(
|
||||
translation::java::COMMANDS_BOSSBAR_SET_VISIBLE_SUCCESS_HIDDEN,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_GET_VISIBLE_FALSE,
|
||||
)
|
||||
};
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
java_key,
|
||||
bedrock_key,
|
||||
[bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.clone(),
|
||||
)],
|
||||
))
|
||||
.await;
|
||||
Ok(bossbar.visible as i32)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ListExecutor;
|
||||
|
||||
impl CommandExecutor for ListExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let bossbars = server.bossbars.lock().await.get_all_bossbars();
|
||||
|
||||
if bossbars.is_empty() {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_LIST_BARS_NONE,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_LIST_NONE,
|
||||
[],
|
||||
))
|
||||
.await;
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let mut bossbars_text = TextComponent::empty();
|
||||
for (i, bossbar) in bossbars.iter().enumerate() {
|
||||
if i == 0 {
|
||||
bossbars_text = bossbars_text.add_child(bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
bossbar.namespace.clone(),
|
||||
));
|
||||
} else {
|
||||
bossbars_text = bossbars_text.add_child(TextComponent::text(", ").add_child(
|
||||
bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
bossbar.namespace.clone(),
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_LIST_BARS_SOME,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_LIST,
|
||||
[
|
||||
TextComponent::text(bossbars.len().to_string()),
|
||||
bossbars_text,
|
||||
],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(bossbars.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct RemoveExecutor;
|
||||
|
||||
impl CommandExecutor for RemoveExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let namespace = autocomplete_consumer()
|
||||
.find_arg_default_name(args)?
|
||||
.to_string();
|
||||
|
||||
let Some(bossbar) = server.bossbars.lock().await.get_bossbar(&namespace) else {
|
||||
return Err(handle_bossbar_error(
|
||||
BossbarUpdateError::InvalidResourceLocation(namespace),
|
||||
));
|
||||
};
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_REMOVE_SUCCESS,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_REMOVE,
|
||||
[bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.clone(),
|
||||
)],
|
||||
))
|
||||
.await;
|
||||
|
||||
let error = {
|
||||
match server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.remove_bossbar(server, namespace.clone())
|
||||
.await
|
||||
{
|
||||
Ok(()) => return Ok(server.bossbars.lock().await.get_bossbars_len() as i32),
|
||||
Err(error) => error,
|
||||
}
|
||||
};
|
||||
|
||||
Err(handle_bossbar_error(error))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct SetExecutor(CommandValueSet);
|
||||
|
||||
impl CommandExecutor for SetExecutor {
|
||||
#[expect(clippy::too_many_lines)]
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let namespace = autocomplete_consumer().find_arg_default_name(args)?;
|
||||
|
||||
let Some(bossbar) = server.bossbars.lock().await.get_bossbar(namespace) else {
|
||||
return Err(handle_bossbar_error(
|
||||
BossbarUpdateError::InvalidResourceLocation(namespace.to_string()),
|
||||
));
|
||||
};
|
||||
|
||||
match self.0 {
|
||||
CommandValueSet::Color => {
|
||||
let color = BossbarColorArgumentConsumer.find_arg_default_name(args)?;
|
||||
|
||||
match server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.update_color(server, namespace.to_string(), *color)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {}
|
||||
Err(err) => {
|
||||
return Err(handle_bossbar_error(err));
|
||||
}
|
||||
}
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.bossbar.set.color.success",
|
||||
"commands.bossbar.set.color.success",
|
||||
[bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.to_string(),
|
||||
)],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(0)
|
||||
}
|
||||
CommandValueSet::Max => {
|
||||
let Ok(max_value) = max_value_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"parsing.int.invalid",
|
||||
"parsing.int.invalid",
|
||||
[TextComponent::text(i32::MAX.to_string())],
|
||||
)));
|
||||
};
|
||||
|
||||
match server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.update_health(server, namespace.to_string(), max_value, bossbar.value)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {}
|
||||
Err(err) => {
|
||||
return Err(handle_bossbar_error(err));
|
||||
}
|
||||
}
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.bossbar.set.max.success",
|
||||
"commands.bossbar.set.max.success",
|
||||
[
|
||||
bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.to_string(),
|
||||
),
|
||||
TextComponent::text(max_value.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(max_value)
|
||||
}
|
||||
CommandValueSet::Name => {
|
||||
let text_component = TextComponentArgConsumer::find_arg(args, ARG_NAME)?;
|
||||
match server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.update_name(server, namespace, text_component.clone())
|
||||
.await
|
||||
{
|
||||
Ok(()) => {}
|
||||
Err(err) => {
|
||||
return Err(handle_bossbar_error(err));
|
||||
}
|
||||
}
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.bossbar.set.name.success",
|
||||
"commands.bossbar.set.name.success",
|
||||
[bossbar_prefix(text_component, namespace.to_string())],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(0)
|
||||
}
|
||||
CommandValueSet::Players(has_players) => {
|
||||
if !has_players {
|
||||
match server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.update_players(server, namespace.to_string(), vec![])
|
||||
.await
|
||||
{
|
||||
Ok(()) => {}
|
||||
Err(err) => {
|
||||
return Err(handle_bossbar_error(err));
|
||||
}
|
||||
}
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.bossbar.set.players.success.none",
|
||||
"commands.bossbar.set.players.success.none",
|
||||
[bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.to_string(),
|
||||
)],
|
||||
))
|
||||
.await;
|
||||
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let targets = PlayersArgumentConsumer.find_arg_default_name(args)?;
|
||||
let players: Vec<Uuid> =
|
||||
targets.iter().map(|player| player.gameprofile.id).collect();
|
||||
let count = players.len();
|
||||
|
||||
match server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.update_players(server, namespace.to_string(), players)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {}
|
||||
Err(err) => {
|
||||
return Err(handle_bossbar_error(err));
|
||||
}
|
||||
}
|
||||
|
||||
let player_names = targets
|
||||
.iter()
|
||||
.map(|p| p.gameprofile.name.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.bossbar.set.players.success.some",
|
||||
"commands.bossbar.set.players.success.some",
|
||||
[
|
||||
bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.to_string(),
|
||||
),
|
||||
TextComponent::text(count.to_string()),
|
||||
TextComponent::text(player_names),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(count as i32)
|
||||
}
|
||||
CommandValueSet::Style => {
|
||||
let style = BossbarStyleArgumentConsumer.find_arg_default_name(args)?;
|
||||
match server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.update_division(server, namespace.to_string(), *style)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {}
|
||||
Err(err) => {
|
||||
return Err(handle_bossbar_error(err));
|
||||
}
|
||||
}
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.bossbar.set.style.success",
|
||||
"commands.bossbar.set.style.success",
|
||||
[bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.to_string(),
|
||||
)],
|
||||
))
|
||||
.await;
|
||||
Ok(0)
|
||||
}
|
||||
CommandValueSet::Value => {
|
||||
let Ok(value) = value_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"parsing.int.invalid",
|
||||
"parsing.int.invalid",
|
||||
[TextComponent::text(i32::MAX.to_string())],
|
||||
)));
|
||||
};
|
||||
|
||||
match server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.update_health(server, namespace.to_string(), bossbar.max, value)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {}
|
||||
Err(err) => {
|
||||
return Err(handle_bossbar_error(err));
|
||||
}
|
||||
}
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.bossbar.set.value.success",
|
||||
"commands.bossbar.set.value.success",
|
||||
[
|
||||
bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.to_string(),
|
||||
),
|
||||
TextComponent::text(value.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(value)
|
||||
}
|
||||
CommandValueSet::Visible => {
|
||||
let visibility = BoolArgConsumer::find_arg(args, ARG_VISIBLE)?;
|
||||
|
||||
match server
|
||||
.bossbars
|
||||
.lock()
|
||||
.await
|
||||
.update_visibility(server, namespace.to_string(), visibility)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {}
|
||||
Err(err) => {
|
||||
return Err(handle_bossbar_error(err));
|
||||
}
|
||||
}
|
||||
|
||||
let state = if visibility {
|
||||
"commands.bossbar.set.visible.success.visible"
|
||||
} else {
|
||||
"commands.bossbar.set.visible.success.hidden"
|
||||
};
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
state,
|
||||
state,
|
||||
[bossbar_prefix(
|
||||
bossbar.bossbar_data.title.clone(),
|
||||
namespace.to_string(),
|
||||
)],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(visibility as i32)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const fn max_value_consumer() -> BoundedNumArgumentConsumer<i32> {
|
||||
BoundedNumArgumentConsumer::new().min(1).name("max")
|
||||
}
|
||||
|
||||
const fn value_consumer() -> BoundedNumArgumentConsumer<i32> {
|
||||
BoundedNumArgumentConsumer::new().min(0).name("value")
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION)
|
||||
.then(
|
||||
literal("add").then(
|
||||
argument_default_name(autocomplete_consumer())
|
||||
.then(argument(ARG_NAME, TextComponentArgConsumer).execute(AddExecutor)),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("get").then(
|
||||
argument_default_name(autocomplete_consumer())
|
||||
.then(literal("max").execute(GetExecutor(CommandValueGet::Max)))
|
||||
.then(literal("players").execute(GetExecutor(CommandValueGet::Players)))
|
||||
.then(literal("value").execute(GetExecutor(CommandValueGet::Value)))
|
||||
.then(literal("visible").execute(GetExecutor(CommandValueGet::Visible))),
|
||||
),
|
||||
)
|
||||
.then(literal("list").execute(ListExecutor))
|
||||
.then(
|
||||
literal("remove")
|
||||
.then(argument_default_name(autocomplete_consumer()).execute(RemoveExecutor)),
|
||||
)
|
||||
.then(
|
||||
literal("set").then(
|
||||
argument_default_name(autocomplete_consumer())
|
||||
.then(
|
||||
literal("color").then(
|
||||
argument_default_name(BossbarColorArgumentConsumer)
|
||||
.execute(SetExecutor(CommandValueSet::Color)),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("max").then(
|
||||
argument_default_name(max_value_consumer())
|
||||
.execute(SetExecutor(CommandValueSet::Max)),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("name").then(
|
||||
argument(ARG_NAME, TextComponentArgConsumer)
|
||||
.execute(SetExecutor(CommandValueSet::Name)),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("players")
|
||||
.then(
|
||||
argument_default_name(PlayersArgumentConsumer)
|
||||
.execute(SetExecutor(CommandValueSet::Players(true))),
|
||||
)
|
||||
.execute(SetExecutor(CommandValueSet::Players(false))),
|
||||
)
|
||||
.then(
|
||||
literal("style").then(
|
||||
argument_default_name(BossbarStyleArgumentConsumer)
|
||||
.execute(SetExecutor(CommandValueSet::Style)),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("value").then(
|
||||
argument_default_name(value_consumer())
|
||||
.execute(SetExecutor(CommandValueSet::Value)),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("visible").then(
|
||||
argument(ARG_VISIBLE, BoolArgConsumer)
|
||||
.execute(SetExecutor(CommandValueSet::Visible)),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fn bossbar_prefix(title: TextComponent, namespace: String) -> TextComponent {
|
||||
TextComponent::text("[")
|
||||
.add_child(title)
|
||||
.add_child(TextComponent::text("]"))
|
||||
.hover_event(HoverEvent::show_text(TextComponent::text(namespace)))
|
||||
}
|
||||
|
||||
fn handle_bossbar_error(error: BossbarUpdateError) -> CommandError {
|
||||
match error {
|
||||
BossbarUpdateError::InvalidResourceLocation(location) => {
|
||||
CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_BOSSBAR_UNKNOWN,
|
||||
translation::bedrock::COMMANDS_BOSSBAR_NOTFOUND,
|
||||
[TextComponent::text(location)],
|
||||
))
|
||||
}
|
||||
BossbarUpdateError::NoChanges(value, variation) => {
|
||||
let key = variation.map_or_else(
|
||||
|| format!("commands.bossbar.set.{value}.unchanged"),
|
||||
|var| format!("commands.bossbar.set.{value}.unchanged.{var}"),
|
||||
);
|
||||
|
||||
CommandError::CommandFailed(TextComponent::translate_cross(key.clone(), key, []))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use pumpkin_data::item_stack::ItemStack;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::command::args::bounded_num::BoundedNumArgumentConsumer;
|
||||
use crate::command::args::players::PlayersArgumentConsumer;
|
||||
use crate::command::args::resource::item::{ItemPredicate, ItemPredicateArgumentConsumer};
|
||||
use crate::command::args::{Arg, ConsumedArgs, FindArg, FindArgDefaultName};
|
||||
use crate::command::tree::CommandTree;
|
||||
use crate::command::tree::builder::{argument, require};
|
||||
use crate::command::{CommandError, CommandExecutor, CommandResult, CommandSender};
|
||||
use crate::entity::EntityBase;
|
||||
use crate::entity::player::Player;
|
||||
use CommandError::InvalidConsumption;
|
||||
|
||||
const NAMES: [&str; 1] = ["clear"];
|
||||
const DESCRIPTION: &str = "Clear your inventory or that of target(s)";
|
||||
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
const ARG_ITEM: &str = "item";
|
||||
const ARG_MAX_COUNT: &str = "max_count";
|
||||
|
||||
const MAX_NO_UPPER_LIMIT: i32 = -1;
|
||||
const MAX_NO_CLEAR_BUT_SIMULATE: i32 = 0;
|
||||
|
||||
/// Returns the number of items actually cleared.
|
||||
///
|
||||
/// If `max` provided is equal to [`MAX_NO_CLEAR_BUT_SIMULATE`] (`0`), then no items are cleared,
|
||||
/// but instead returns the items that *could* be cleared.
|
||||
///
|
||||
/// If `max` provided is [`MAX_NO_UPPER_LIMIT`] (`-1`), then there is no limit in clearing.
|
||||
///
|
||||
/// Otherwise, at most `max` items are cleared.
|
||||
async fn clear_player(target: &Player, item: &ItemPredicate, max: i32) -> i32 {
|
||||
let inventory = target.inventory();
|
||||
let mut count: i32 = 0;
|
||||
let mut max: i32 = max;
|
||||
let mut is_done: bool = false;
|
||||
|
||||
iter_test_and_clear(
|
||||
&inventory.main_inventory,
|
||||
&mut count,
|
||||
&mut max,
|
||||
item,
|
||||
&mut is_done,
|
||||
)
|
||||
.await;
|
||||
|
||||
let entity_equipment_lock = inventory.entity_equipment.lock().await;
|
||||
iter_test_and_clear(
|
||||
entity_equipment_lock.equipment.values(),
|
||||
&mut count,
|
||||
&mut max,
|
||||
item,
|
||||
&mut is_done,
|
||||
)
|
||||
.await;
|
||||
drop(entity_equipment_lock);
|
||||
|
||||
count
|
||||
}
|
||||
|
||||
async fn iter_test_and_clear<'i, I>(
|
||||
iter: I,
|
||||
count: &mut i32,
|
||||
max: &mut i32,
|
||||
item: &ItemPredicate,
|
||||
is_done: &mut bool,
|
||||
) where
|
||||
I: IntoIterator<Item = &'i Arc<Mutex<ItemStack>>>,
|
||||
{
|
||||
// Don't need to enter the loop if we are already done.
|
||||
if !*is_done {
|
||||
for slot in iter {
|
||||
test_and_clear(count, max, item, slot, is_done).await;
|
||||
if *is_done {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn test_and_clear(
|
||||
count: &mut i32,
|
||||
max: &mut i32,
|
||||
item: &ItemPredicate,
|
||||
slot: &Arc<Mutex<ItemStack>>,
|
||||
is_done: &mut bool,
|
||||
) {
|
||||
let mut slot_lock = slot.lock().await;
|
||||
if item.test_item_stack(&slot_lock) {
|
||||
let item_count = slot_lock.item_count as i32;
|
||||
if *max == MAX_NO_CLEAR_BUT_SIMULATE {
|
||||
*count += item_count;
|
||||
} else if *max == MAX_NO_UPPER_LIMIT {
|
||||
*count += item_count;
|
||||
*slot_lock = ItemStack::EMPTY.clone();
|
||||
} else {
|
||||
// We need more complex logic for this one.
|
||||
let taken = i32::min(*max, item_count);
|
||||
|
||||
// Take all that we can.
|
||||
*count += taken;
|
||||
if taken == item_count {
|
||||
*slot_lock = ItemStack::EMPTY.clone();
|
||||
*max -= taken;
|
||||
|
||||
// Set `is_done` flag if required.
|
||||
*is_done = *max == 0;
|
||||
} else {
|
||||
// As `slot_lock.item_count` is limited to `u8`, this should be fine.
|
||||
slot_lock.decrement(taken as u8);
|
||||
*max -= taken;
|
||||
|
||||
// Set `is_done` flag if required.
|
||||
*is_done = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn command_result(
|
||||
sender: &CommandSender,
|
||||
item_count: i32,
|
||||
max_count: i32,
|
||||
targets: &[Arc<Player>],
|
||||
) -> Result<i32, CommandError> {
|
||||
match clear_command_text_output(item_count, max_count, targets).await {
|
||||
Ok(success) => {
|
||||
sender.send_message(success).await;
|
||||
Ok(item_count)
|
||||
}
|
||||
Err(failure) => Err(CommandError::CommandFailed(failure)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn clear_command_text_output(
|
||||
item_count: i32,
|
||||
max_count: i32,
|
||||
targets: &[Arc<Player>],
|
||||
) -> Result<TextComponent, TextComponent> {
|
||||
match (targets, item_count == 0, max_count == 0) {
|
||||
([target], true, _) => Err(TextComponent::translate_cross(
|
||||
translation::java::CLEAR_FAILED_SINGLE,
|
||||
translation::bedrock::COMMANDS_CLEAR_FAILURE,
|
||||
[target.get_display_name().await],
|
||||
)),
|
||||
(targets, true, _) => Err(TextComponent::translate_cross(
|
||||
translation::java::CLEAR_FAILED_MULTIPLE,
|
||||
translation::bedrock::COMMANDS_CLEAR_FAILURE,
|
||||
[TextComponent::text(targets.len().to_string())],
|
||||
)),
|
||||
([target], false, false) => Ok(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_CLEAR_SUCCESS_SINGLE,
|
||||
translation::java::COMMANDS_CLEAR_SUCCESS_SINGLE,
|
||||
[
|
||||
TextComponent::text(item_count.to_string()),
|
||||
target.get_display_name().await,
|
||||
],
|
||||
)),
|
||||
(targets, false, false) => Ok(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_CLEAR_SUCCESS_MULTIPLE,
|
||||
translation::java::COMMANDS_CLEAR_SUCCESS_MULTIPLE,
|
||||
[
|
||||
TextComponent::text(item_count.to_string()),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
)),
|
||||
([target], false, true) => Ok(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_CLEAR_TEST_SINGLE,
|
||||
translation::java::COMMANDS_CLEAR_TEST_SINGLE,
|
||||
[
|
||||
TextComponent::text(item_count.to_string()),
|
||||
target.get_display_name().await,
|
||||
],
|
||||
)),
|
||||
(targets, false, true) => Ok(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_CLEAR_TEST_MULTIPLE,
|
||||
translation::java::COMMANDS_CLEAR_TEST_MULTIPLE,
|
||||
[
|
||||
TextComponent::text(item_count.to_string()),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
const fn count_consumer() -> BoundedNumArgumentConsumer<i32> {
|
||||
BoundedNumArgumentConsumer::new().min(0).name(ARG_MAX_COUNT)
|
||||
}
|
||||
|
||||
struct SelfExecutor;
|
||||
|
||||
impl CommandExecutor for SelfExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = sender.as_player().ok_or(CommandError::InvalidRequirement)?;
|
||||
|
||||
let items_cleared =
|
||||
clear_player(&target, &ItemPredicate::Any, MAX_NO_UPPER_LIMIT).await;
|
||||
|
||||
command_result(sender, items_cleared, MAX_NO_UPPER_LIMIT, &[target]).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
|
||||
let mut total_items_cleared = 0;
|
||||
for target in targets {
|
||||
total_items_cleared +=
|
||||
clear_player(target, &ItemPredicate::Any, MAX_NO_UPPER_LIMIT).await;
|
||||
}
|
||||
|
||||
command_result(sender, total_items_cleared, MAX_NO_UPPER_LIMIT, targets).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ItemExecutor;
|
||||
|
||||
impl CommandExecutor for ItemExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
|
||||
let item = ItemPredicateArgumentConsumer::find_arg(args, ARG_ITEM)?;
|
||||
|
||||
let mut total_items_cleared = 0;
|
||||
for target in targets {
|
||||
total_items_cleared += clear_player(target, &item, MAX_NO_UPPER_LIMIT).await;
|
||||
}
|
||||
|
||||
command_result(sender, total_items_cleared, MAX_NO_UPPER_LIMIT, targets).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ItemCountExecutor;
|
||||
|
||||
impl CommandExecutor for ItemCountExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
|
||||
let item = ItemPredicateArgumentConsumer::find_arg(args, ARG_ITEM)?;
|
||||
let Ok(max) = count_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::PARSING_INT_INVALID,
|
||||
translation::java::PARSING_INT_INVALID,
|
||||
[TextComponent::text(i32::MAX.to_string())],
|
||||
)));
|
||||
};
|
||||
|
||||
let mut total_items_cleared = 0;
|
||||
for target in targets {
|
||||
total_items_cleared += clear_player(target, &item, max).await;
|
||||
}
|
||||
|
||||
command_result(sender, total_items_cleared, max, targets).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// #[expect(clippy::redundant_closure_for_method_calls)] // causes lifetime issues
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION)
|
||||
.then(
|
||||
argument(ARG_TARGETS, PlayersArgumentConsumer)
|
||||
.execute(Executor)
|
||||
.then(
|
||||
argument(ARG_ITEM, ItemPredicateArgumentConsumer)
|
||||
.execute(ItemExecutor)
|
||||
.then(
|
||||
argument(ARG_MAX_COUNT, count_consumer().name(ARG_MAX_COUNT))
|
||||
.execute(ItemCountExecutor),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(require(super::super::CommandSender::is_player).execute(SelfExecutor))
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command, literal};
|
||||
use crate::command::argument_types::block::BlockArgumentType;
|
||||
use crate::command::argument_types::coordinates::block_pos::BlockPosArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use pumpkin_data::{Block, BlockStateId, translation};
|
||||
use pumpkin_nbt::compound::NbtCompound;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::math::position::BlockPos;
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_world::world::BlockFlags;
|
||||
|
||||
const DESCRIPTION: &str = "Clones blocks from one region to another.";
|
||||
const PERMISSION: &str = "minecraft:command.clone";
|
||||
|
||||
const ARG_BEGIN: &str = "begin";
|
||||
const ARG_END: &str = "end";
|
||||
const ARG_DEST: &str = "destination";
|
||||
const ARG_FILTER: &str = "filter";
|
||||
|
||||
const OVERLAP_ERROR: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_CLONE_OVERLAP,
|
||||
translation::bedrock::COMMANDS_CLONE_NOOVERLAP,
|
||||
);
|
||||
|
||||
const TOOBIG_ERROR: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_CLONE_TOOBIG,
|
||||
translation::bedrock::COMMANDS_CLONE_TOOMANYBLOCKS,
|
||||
);
|
||||
|
||||
const FAILED_ERROR: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_CLONE_FAILED,
|
||||
translation::bedrock::COMMANDS_CLONE_FAILED,
|
||||
);
|
||||
|
||||
const NOT_LOADED_ERROR: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_POS_UNLOADED,
|
||||
translation::java::ARGUMENT_POS_UNLOADED,
|
||||
);
|
||||
|
||||
const OUT_OF_WORLD_ERROR: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_POS_OUTOFWORLD,
|
||||
translation::java::ARGUMENT_POS_OUTOFWORLD,
|
||||
);
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum MaskMode {
|
||||
Replace,
|
||||
Masked,
|
||||
Filtered,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum CloneMode {
|
||||
Normal,
|
||||
Force,
|
||||
Move,
|
||||
}
|
||||
|
||||
struct CloneExecutor {
|
||||
mask_mode: MaskMode,
|
||||
clone_mode: CloneMode,
|
||||
has_filter: bool,
|
||||
}
|
||||
|
||||
struct ClonedBlock {
|
||||
src_pos: BlockPos,
|
||||
dest_pos: BlockPos,
|
||||
state_id: BlockStateId,
|
||||
block_entity_nbt: Option<NbtCompound>,
|
||||
}
|
||||
|
||||
impl CommandExecutor for CloneExecutor {
|
||||
#[expect(clippy::too_many_lines)]
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let begin = BlockPosArgumentType::get_block_pos(context, ARG_BEGIN)?;
|
||||
let end = BlockPosArgumentType::get_block_pos(context, ARG_END)?;
|
||||
let dest = BlockPosArgumentType::get_block_pos(context, ARG_DEST)?;
|
||||
|
||||
let filter_block = if self.has_filter {
|
||||
Some(BlockArgumentType::get(context, ARG_FILTER)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let min_x = begin.0.x.min(end.0.x);
|
||||
let max_x = begin.0.x.max(end.0.x);
|
||||
let min_y = begin.0.y.min(end.0.y);
|
||||
let max_y = begin.0.y.max(end.0.y);
|
||||
let min_z = begin.0.z.min(end.0.z);
|
||||
let max_z = begin.0.z.max(end.0.z);
|
||||
|
||||
let size_x = max_x - min_x + 1;
|
||||
let size_y = max_y - min_y + 1;
|
||||
let size_z = max_z - min_z + 1;
|
||||
|
||||
let volume = size_x * size_y * size_z;
|
||||
|
||||
if volume > 32768 {
|
||||
return Err(TOOBIG_ERROR.create_without_context_args_slice(&[
|
||||
TextComponent::text("32768"),
|
||||
TextComponent::text(volume.to_string()),
|
||||
]));
|
||||
}
|
||||
|
||||
let dest_min_x = dest.0.x;
|
||||
let dest_min_y = dest.0.y;
|
||||
let dest_min_z = dest.0.z;
|
||||
let dest_max_x = dest_min_x + size_x - 1;
|
||||
let dest_max_y = dest_min_y + size_y - 1;
|
||||
let dest_max_z = dest_min_z + size_z - 1;
|
||||
|
||||
let overlap = !(dest_max_x < min_x
|
||||
|| dest_min_x > max_x
|
||||
|| dest_max_y < min_y
|
||||
|| dest_min_y > max_y
|
||||
|| dest_max_z < min_z
|
||||
|| dest_min_z > max_z);
|
||||
|
||||
if overlap && self.clone_mode != CloneMode::Force {
|
||||
return Err(OVERLAP_ERROR.create_without_context());
|
||||
}
|
||||
|
||||
let world = context.source.world();
|
||||
|
||||
let limit_check_pos_1 = BlockPos::new(min_x, min_y, min_z);
|
||||
let limit_check_pos_2 = BlockPos::new(max_x, max_y, max_z);
|
||||
let limit_check_pos_3 = BlockPos::new(dest_min_x, dest_min_y, dest_min_z);
|
||||
let limit_check_pos_4 = BlockPos::new(dest_max_x, dest_max_y, dest_max_z);
|
||||
|
||||
if !world.is_in_build_limit(limit_check_pos_1)
|
||||
|| !world.is_in_build_limit(limit_check_pos_2)
|
||||
|| !world.is_in_build_limit(limit_check_pos_3)
|
||||
|| !world.is_in_build_limit(limit_check_pos_4)
|
||||
{
|
||||
return Err(OUT_OF_WORLD_ERROR.create_without_context());
|
||||
}
|
||||
|
||||
for cx in (min_x >> 4)..=(max_x >> 4) {
|
||||
for cz in (min_z >> 4)..=(max_z >> 4) {
|
||||
let chunk_pos = Vector2::new(cx, cz);
|
||||
if world.level.read_chunk_sync(&chunk_pos, |_| ()).is_none() {
|
||||
return Err(NOT_LOADED_ERROR.create_without_context());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for cx in (dest_min_x >> 4)..=(dest_max_x >> 4) {
|
||||
for cz in (dest_min_z >> 4)..=(dest_max_z >> 4) {
|
||||
let chunk_pos = Vector2::new(cx, cz);
|
||||
if world.level.read_chunk_sync(&chunk_pos, |_| ()).is_none() {
|
||||
return Err(NOT_LOADED_ERROR.create_without_context());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut blocks_to_clone = Vec::new();
|
||||
|
||||
for x in 0..size_x {
|
||||
for y in 0..size_y {
|
||||
for z in 0..size_z {
|
||||
let src_pos = BlockPos::new(min_x + x, min_y + y, min_z + z);
|
||||
let dest_pos =
|
||||
BlockPos::new(dest_min_x + x, dest_min_y + y, dest_min_z + z);
|
||||
|
||||
let state_id = world.get_block_state_id(&src_pos);
|
||||
|
||||
let should_clone = match self.mask_mode {
|
||||
MaskMode::Replace => true,
|
||||
MaskMode::Masked => !pumpkin_data::block_properties::is_air(state_id),
|
||||
MaskMode::Filtered => {
|
||||
let block = Block::from_state_id(state_id);
|
||||
block.id == filter_block.unwrap().id
|
||||
}
|
||||
};
|
||||
|
||||
if should_clone {
|
||||
let block_entity_nbt =
|
||||
if let Some(be) = world.get_block_entity(&src_pos) {
|
||||
let mut nbt = NbtCompound::new();
|
||||
be.write_internal(&mut nbt).await;
|
||||
Some(nbt)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
blocks_to_clone.push(ClonedBlock {
|
||||
src_pos,
|
||||
dest_pos,
|
||||
state_id,
|
||||
block_entity_nbt,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut count = 0;
|
||||
for block in &blocks_to_clone {
|
||||
world
|
||||
.set_block_state(&block.dest_pos, block.state_id, BlockFlags::NOTIFY_ALL)
|
||||
.await;
|
||||
|
||||
if let Some(nbt) = &block.block_entity_nbt {
|
||||
let mut new_nbt = nbt.clone();
|
||||
new_nbt.put_int("x", block.dest_pos.0.x);
|
||||
new_nbt.put_int("y", block.dest_pos.0.y);
|
||||
new_nbt.put_int("z", block.dest_pos.0.z);
|
||||
|
||||
if let Some(be) = crate::block::entities::block_entity_from_nbt(&new_nbt) {
|
||||
world.add_block_entity(be);
|
||||
}
|
||||
}
|
||||
|
||||
count += 1;
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
return Err(FAILED_ERROR.create_without_context());
|
||||
}
|
||||
|
||||
let is_dest_pos = |pos: &BlockPos| {
|
||||
pos.0.x >= dest_min_x
|
||||
&& pos.0.x <= dest_max_x
|
||||
&& pos.0.y >= dest_min_y
|
||||
&& pos.0.y <= dest_max_y
|
||||
&& pos.0.z >= dest_min_z
|
||||
&& pos.0.z <= dest_max_z
|
||||
};
|
||||
|
||||
if self.clone_mode == CloneMode::Move {
|
||||
for block in &blocks_to_clone {
|
||||
if !is_dest_pos(&block.src_pos) {
|
||||
world
|
||||
.set_block_state(
|
||||
&block.src_pos,
|
||||
BlockStateId::AIR,
|
||||
BlockFlags::NOTIFY_ALL,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_CLONE_SUCCESS,
|
||||
translation::bedrock::COMMANDS_CLONE_SUCCESS,
|
||||
[TextComponent::text(count.to_string())],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(count)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("clone", DESCRIPTION).requires(PERMISSION).then(
|
||||
argument(ARG_BEGIN, BlockPosArgumentType).then(
|
||||
argument(ARG_END, BlockPosArgumentType).then(
|
||||
argument(ARG_DEST, BlockPosArgumentType)
|
||||
.executes(CloneExecutor {
|
||||
mask_mode: MaskMode::Replace,
|
||||
clone_mode: CloneMode::Normal,
|
||||
has_filter: false,
|
||||
})
|
||||
.then(
|
||||
literal("replace")
|
||||
.executes(CloneExecutor {
|
||||
mask_mode: MaskMode::Replace,
|
||||
clone_mode: CloneMode::Normal,
|
||||
has_filter: false,
|
||||
})
|
||||
.then(literal("force").executes(CloneExecutor {
|
||||
mask_mode: MaskMode::Replace,
|
||||
clone_mode: CloneMode::Force,
|
||||
has_filter: false,
|
||||
}))
|
||||
.then(literal("move").executes(CloneExecutor {
|
||||
mask_mode: MaskMode::Replace,
|
||||
clone_mode: CloneMode::Move,
|
||||
has_filter: false,
|
||||
}))
|
||||
.then(literal("normal").executes(CloneExecutor {
|
||||
mask_mode: MaskMode::Replace,
|
||||
clone_mode: CloneMode::Normal,
|
||||
has_filter: false,
|
||||
})),
|
||||
)
|
||||
.then(
|
||||
literal("masked")
|
||||
.executes(CloneExecutor {
|
||||
mask_mode: MaskMode::Masked,
|
||||
clone_mode: CloneMode::Normal,
|
||||
has_filter: false,
|
||||
})
|
||||
.then(literal("force").executes(CloneExecutor {
|
||||
mask_mode: MaskMode::Masked,
|
||||
clone_mode: CloneMode::Force,
|
||||
has_filter: false,
|
||||
}))
|
||||
.then(literal("move").executes(CloneExecutor {
|
||||
mask_mode: MaskMode::Masked,
|
||||
clone_mode: CloneMode::Move,
|
||||
has_filter: false,
|
||||
}))
|
||||
.then(literal("normal").executes(CloneExecutor {
|
||||
mask_mode: MaskMode::Masked,
|
||||
clone_mode: CloneMode::Normal,
|
||||
has_filter: false,
|
||||
})),
|
||||
)
|
||||
.then(
|
||||
literal("filtered").then(
|
||||
argument(ARG_FILTER, BlockArgumentType)
|
||||
.executes(CloneExecutor {
|
||||
mask_mode: MaskMode::Filtered,
|
||||
clone_mode: CloneMode::Normal,
|
||||
has_filter: true,
|
||||
})
|
||||
.then(literal("force").executes(CloneExecutor {
|
||||
mask_mode: MaskMode::Filtered,
|
||||
clone_mode: CloneMode::Force,
|
||||
has_filter: true,
|
||||
}))
|
||||
.then(literal("move").executes(CloneExecutor {
|
||||
mask_mode: MaskMode::Filtered,
|
||||
clone_mode: CloneMode::Move,
|
||||
has_filter: true,
|
||||
}))
|
||||
.then(literal("normal").executes(CloneExecutor {
|
||||
mask_mode: MaskMode::Filtered,
|
||||
clone_mode: CloneMode::Normal,
|
||||
has_filter: true,
|
||||
})),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
use pumpkin_data::{damage::DamageType, translation};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::command::{
|
||||
CommandExecutor, CommandResult, CommandSender,
|
||||
args::{
|
||||
Arg, ConsumedArgs, FindArg, bounded_num::BoundedNumArgumentConsumer,
|
||||
entity::EntityArgumentConsumer, position_3d::Position3DArgumentConsumer,
|
||||
resource::damage_type::DamageTypeArgumentConsumer,
|
||||
},
|
||||
dispatcher::CommandError,
|
||||
tree::{
|
||||
CommandTree,
|
||||
builder::{argument, literal},
|
||||
},
|
||||
};
|
||||
use crate::entity::EntityBase;
|
||||
|
||||
const NAMES: [&str; 1] = ["damage"];
|
||||
const DESCRIPTION: &str = "Deals damage to entities";
|
||||
const ARG_TARGET: &str = "target";
|
||||
const ARG_AMOUNT: &str = "amount";
|
||||
const ARG_DAMAGE_TYPE: &str = "damageType";
|
||||
const ARG_LOCATION: &str = "location";
|
||||
const ARG_ENTITY: &str = "entity";
|
||||
const ARG_CAUSE: &str = "cause";
|
||||
|
||||
const fn amount_consumer() -> BoundedNumArgumentConsumer<f32> {
|
||||
BoundedNumArgumentConsumer::new().name(ARG_AMOUNT).min(0.0)
|
||||
}
|
||||
|
||||
struct LocationExecutor;
|
||||
struct EntityExecutor(bool);
|
||||
|
||||
async fn send_damage_result(
|
||||
sender: &CommandSender,
|
||||
success: bool,
|
||||
amount: f32,
|
||||
target_name: TextComponent,
|
||||
) -> Result<i32, CommandError> {
|
||||
if !success {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DAMAGE_INVULNERABLE,
|
||||
translation::java::COMMANDS_DAMAGE_INVULNERABLE,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DAMAGE_SUCCESS,
|
||||
translation::bedrock::COMMANDS_DAMAGE_SUCCESS,
|
||||
[TextComponent::text(amount.to_string()), target_name],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(1) // not arbitrary, this is what vanilla does
|
||||
}
|
||||
|
||||
impl CommandExecutor for LocationExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentConsumer::find_arg(args, ARG_TARGET)?;
|
||||
|
||||
let Ok(Ok(amount)) = BoundedNumArgumentConsumer::<f32>::find_arg(args, ARG_AMOUNT)
|
||||
else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(
|
||||
"Invalid damage amount",
|
||||
)));
|
||||
};
|
||||
|
||||
let damage_type =
|
||||
args.get(ARG_DAMAGE_TYPE)
|
||||
.map_or(DamageType::GENERIC, |arg| match arg {
|
||||
Arg::DamageType(dt) => *dt,
|
||||
_ => DamageType::GENERIC,
|
||||
});
|
||||
|
||||
let location = Position3DArgumentConsumer::find_arg(args, ARG_LOCATION)?;
|
||||
|
||||
let success = target
|
||||
.damage_with_context(&*target, amount, damage_type, Some(location), None, None)
|
||||
.await;
|
||||
|
||||
send_damage_result(sender, success, amount, target.get_display_name().await).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandExecutor for EntityExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentConsumer::find_arg(args, ARG_TARGET)?;
|
||||
|
||||
let Ok(Ok(amount)) = BoundedNumArgumentConsumer::<f32>::find_arg(args, ARG_AMOUNT)
|
||||
else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(
|
||||
"Invalid damage amount",
|
||||
)));
|
||||
};
|
||||
|
||||
let damage_type =
|
||||
args.get(ARG_DAMAGE_TYPE)
|
||||
.map_or(DamageType::GENERIC, |arg| match arg {
|
||||
Arg::DamageType(dt) => *dt,
|
||||
_ => DamageType::GENERIC,
|
||||
});
|
||||
|
||||
let source = EntityArgumentConsumer::find_arg(args, ARG_ENTITY).ok();
|
||||
let cause = if self.0 {
|
||||
EntityArgumentConsumer::find_arg(args, ARG_CAUSE).ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let success = target
|
||||
.damage_with_context(
|
||||
&*target,
|
||||
amount,
|
||||
damage_type,
|
||||
None,
|
||||
source.as_ref().map(|e| e.as_ref() as &dyn EntityBase),
|
||||
cause.as_ref().map(|e| e.as_ref() as &dyn EntityBase),
|
||||
)
|
||||
.await;
|
||||
|
||||
send_damage_result(sender, success, amount, target.get_display_name().await).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(ARG_TARGET, EntityArgumentConsumer).then(
|
||||
argument(ARG_AMOUNT, amount_consumer())
|
||||
// Basic damage
|
||||
.execute(EntityExecutor(false))
|
||||
// With damage type
|
||||
.then(
|
||||
argument(ARG_DAMAGE_TYPE, DamageTypeArgumentConsumer)
|
||||
.execute(EntityExecutor(false))
|
||||
// At location
|
||||
.then(
|
||||
literal("at").then(
|
||||
argument(ARG_LOCATION, Position3DArgumentConsumer)
|
||||
.execute(LocationExecutor),
|
||||
),
|
||||
)
|
||||
// By entity
|
||||
.then(
|
||||
literal("by").then(
|
||||
argument(ARG_ENTITY, EntityArgumentConsumer)
|
||||
.execute(EntityExecutor(false))
|
||||
// From cause
|
||||
.then(
|
||||
literal("from").then(
|
||||
argument(ARG_CAUSE, EntityArgumentConsumer)
|
||||
.execute(EntityExecutor(true)),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
use crate::command::CommandResult;
|
||||
use crate::command::args::entity::EntityArgumentConsumer;
|
||||
use crate::command::tree::builder::literal;
|
||||
use crate::command::{
|
||||
CommandError, CommandExecutor, CommandSender,
|
||||
args::{Arg, ConsumedArgs},
|
||||
tree::{CommandTree, builder::argument},
|
||||
};
|
||||
use crate::entity::NBTStorage;
|
||||
use CommandError::InvalidConsumption;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_nbt::compound::NbtCompound;
|
||||
use pumpkin_nbt::tag::NbtTag;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_util::text::color::NamedColor;
|
||||
|
||||
const NAMES: [&str; 1] = ["data"];
|
||||
const DESCRIPTION: &str = "Query and modify data of entities and blocks";
|
||||
|
||||
const ARG_ENTITY: &str = "entity";
|
||||
|
||||
struct GetEntityDataExecutor;
|
||||
|
||||
impl CommandExecutor for GetEntityDataExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Entity(entity)) = args.get(&ARG_ENTITY) else {
|
||||
return Err(InvalidConsumption(Some(ARG_ENTITY.into())));
|
||||
};
|
||||
display_data(
|
||||
entity.as_nbt_storage(),
|
||||
entity.get_display_name().await,
|
||||
sender,
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::too_many_lines)]
|
||||
pub fn snbt_colorful_display(tag: &NbtTag, depth: usize) -> Result<TextComponent, String> {
|
||||
let folded = TextComponent::text("<...>").color_named(NamedColor::Gray);
|
||||
match tag {
|
||||
NbtTag::End => Err("Unexpected end tag".into()),
|
||||
NbtTag::Byte(value) => {
|
||||
let byte_format = TextComponent::text("b").color_named(NamedColor::Red);
|
||||
Ok(TextComponent::text(format!("{value}"))
|
||||
.color_named(NamedColor::Gold)
|
||||
.add_child(byte_format))
|
||||
}
|
||||
NbtTag::Short(value) => {
|
||||
let short_format = TextComponent::text("s").color_named(NamedColor::Red);
|
||||
Ok(TextComponent::text(format!("{value}"))
|
||||
.color_named(NamedColor::Gold)
|
||||
.add_child(short_format))
|
||||
}
|
||||
NbtTag::Int(value) => {
|
||||
Ok(TextComponent::text(format!("{value}")).color_named(NamedColor::Gold))
|
||||
}
|
||||
NbtTag::Long(value) => {
|
||||
let long_format = TextComponent::text("L").color_named(NamedColor::Red);
|
||||
Ok(TextComponent::text(format!("{value}"))
|
||||
.color_named(NamedColor::Gold)
|
||||
.add_child(long_format))
|
||||
}
|
||||
NbtTag::Float(value) => {
|
||||
let float_format = TextComponent::text("f").color_named(NamedColor::Red);
|
||||
Ok(TextComponent::text(format!("{value}"))
|
||||
.color_named(NamedColor::Gold)
|
||||
.add_child(float_format))
|
||||
}
|
||||
NbtTag::Double(value) => {
|
||||
let double_format = TextComponent::text("d").color_named(NamedColor::Red);
|
||||
Ok(TextComponent::text(format!("{value}"))
|
||||
.color_named(NamedColor::Gold)
|
||||
.add_child(double_format))
|
||||
}
|
||||
NbtTag::ByteArray(value) => {
|
||||
let byte_array_format = TextComponent::text("B").color_named(NamedColor::Red);
|
||||
let mut content = TextComponent::text("[")
|
||||
.add_child(byte_array_format.clone())
|
||||
.add_child(TextComponent::text("; "));
|
||||
|
||||
for (index, byte) in value.iter().take(128).enumerate() {
|
||||
content = content
|
||||
.add_child(TextComponent::text(format!("{byte}")))
|
||||
.add_child(byte_array_format.clone());
|
||||
if index < value.len() - 1 {
|
||||
content = content.add_child(TextComponent::text(", "));
|
||||
}
|
||||
}
|
||||
|
||||
if value.len() > 128 {
|
||||
content = content.add_child(folded);
|
||||
}
|
||||
|
||||
content = content.add_child(TextComponent::text("]"));
|
||||
Ok(content)
|
||||
}
|
||||
NbtTag::String(value) => {
|
||||
let escaped_value = value
|
||||
.replace('"', "\\\"")
|
||||
.replace('\\', "\\\\")
|
||||
.replace('\n', "\\n")
|
||||
.replace('\t', "\\t")
|
||||
.replace('\r', "\\r")
|
||||
.replace('\x0c', "\\f")
|
||||
.replace('\x08', "\\b");
|
||||
|
||||
Ok(TextComponent::text(format!("\"{escaped_value}\"")).color_named(NamedColor::Green))
|
||||
}
|
||||
NbtTag::List(value) => {
|
||||
if value.is_empty() {
|
||||
Ok(TextComponent::text("[]"))
|
||||
} else if depth >= 64 {
|
||||
Ok(TextComponent::text("[")
|
||||
.add_child(folded)
|
||||
.add_child(TextComponent::text("]")))
|
||||
} else {
|
||||
let mut content = TextComponent::text("[");
|
||||
|
||||
for (index, item) in value.iter().take(128).enumerate() {
|
||||
let item_display = snbt_colorful_display(item, depth + 1)
|
||||
.map_err(|string| format!("Error displaying item.[{index}]: {string}"))?;
|
||||
content = content.add_child(item_display);
|
||||
|
||||
if index < value.len() - 1 {
|
||||
content = content.add_child(TextComponent::text(", "));
|
||||
}
|
||||
}
|
||||
|
||||
if value.len() > 128 {
|
||||
content = content.add_child(folded);
|
||||
}
|
||||
|
||||
content = content.add_child(TextComponent::text("]"));
|
||||
Ok(content)
|
||||
}
|
||||
}
|
||||
NbtTag::Compound(value) => {
|
||||
if value.is_empty() {
|
||||
Ok(TextComponent::text("{}"))
|
||||
} else if depth >= 64 {
|
||||
Ok(TextComponent::text("{")
|
||||
.add_child(folded)
|
||||
.add_child(TextComponent::text("}")))
|
||||
} else {
|
||||
let mut content = TextComponent::text("{");
|
||||
|
||||
for (index, (key, item)) in value.child_tags.iter().take(128).enumerate() {
|
||||
let item_display = snbt_colorful_display(item, depth + 1)
|
||||
.map_err(|string| format!("Error displaying item.{key}: {string}"))?;
|
||||
content = content
|
||||
.add_child(
|
||||
TextComponent::text(key.to_string()).color_named(NamedColor::Aqua),
|
||||
)
|
||||
.add_child(TextComponent::text(": "))
|
||||
.add_child(item_display);
|
||||
|
||||
if index < value.child_tags.len() - 1 {
|
||||
content = content.add_child(TextComponent::text(", "));
|
||||
}
|
||||
}
|
||||
|
||||
if value.child_tags.len() > 128 {
|
||||
content = content.add_child(folded);
|
||||
}
|
||||
|
||||
content = content.add_child(TextComponent::text("}"));
|
||||
Ok(content)
|
||||
}
|
||||
}
|
||||
NbtTag::IntArray(value) => {
|
||||
let int_array_format = TextComponent::text("I").color_named(NamedColor::Red);
|
||||
let mut content = TextComponent::text("[")
|
||||
.add_child(int_array_format)
|
||||
.add_child(TextComponent::text("; "));
|
||||
|
||||
for (index, int) in value.iter().take(128).enumerate() {
|
||||
content = content
|
||||
.add_child(TextComponent::text(format!("{int}")).color_named(NamedColor::Gold));
|
||||
if index < value.len() - 1 {
|
||||
content = content.add_child(TextComponent::text(", "));
|
||||
}
|
||||
}
|
||||
|
||||
if value.len() > 128 {
|
||||
content = content.add_child(folded);
|
||||
}
|
||||
|
||||
content = content.add_child(TextComponent::text("]"));
|
||||
Ok(content)
|
||||
}
|
||||
NbtTag::LongArray(value) => {
|
||||
let long_array_format = TextComponent::text("L").color_named(NamedColor::Red);
|
||||
let mut content = TextComponent::text("[")
|
||||
.add_child(long_array_format.clone())
|
||||
.add_child(TextComponent::text("; "));
|
||||
|
||||
for (index, long) in value.iter().take(128).enumerate() {
|
||||
content = content
|
||||
.add_child(TextComponent::text(format!("{long}")))
|
||||
.add_child(long_array_format.clone());
|
||||
if index < value.len() - 1 {
|
||||
content = content.add_child(TextComponent::text(", "));
|
||||
}
|
||||
}
|
||||
|
||||
if value.len() > 128 {
|
||||
content = content.add_child(folded);
|
||||
}
|
||||
|
||||
content = content.add_child(TextComponent::text("]"));
|
||||
Ok(content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn display_data(
|
||||
storage: &dyn NBTStorage,
|
||||
target_name: TextComponent,
|
||||
sender: &CommandSender,
|
||||
) -> Result<i32, CommandError> {
|
||||
let mut nbt = NbtCompound::new();
|
||||
storage.write_nbt(&mut nbt).await;
|
||||
let tag = NbtTag::Compound(nbt);
|
||||
|
||||
let result = get_i32_result(&tag)?;
|
||||
let display = snbt_colorful_display(&tag, 0)
|
||||
.map_err(|string| CommandError::CommandFailed(TextComponent::text(string)))?;
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATA_ENTITY_QUERY,
|
||||
translation::java::COMMANDS_DATA_ENTITY_QUERY,
|
||||
[target_name, display],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn get_i32_result(tag: &NbtTag) -> Result<i32, CommandError> {
|
||||
match tag {
|
||||
NbtTag::End => Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_DATA_GET_UNKNOWN,
|
||||
translation::java::COMMANDS_DATA_GET_UNKNOWN,
|
||||
[],
|
||||
))),
|
||||
|
||||
NbtTag::Byte(b) => Ok(*b as i32),
|
||||
NbtTag::Short(s) => Ok(*s as i32),
|
||||
NbtTag::Int(i) => Ok(*i),
|
||||
NbtTag::Long(l) => Ok((*l).clamp(i32::MIN as i64, i32::MAX as i64) as i32),
|
||||
NbtTag::Float(f) => Ok({
|
||||
let i = *f as i32;
|
||||
if *f < i as f32 { i - 1 } else { i }
|
||||
}),
|
||||
NbtTag::Double(d) => Ok({
|
||||
let i = *d as i32;
|
||||
if *d < i as f64 { i - 1 } else { i }
|
||||
}),
|
||||
|
||||
NbtTag::ByteArray(items) => Ok(items.len() as i32),
|
||||
NbtTag::IntArray(items) => Ok(items.len() as i32),
|
||||
NbtTag::LongArray(items) => Ok(items.len() as i32),
|
||||
|
||||
NbtTag::String(string) => Ok(string.len() as i32),
|
||||
NbtTag::List(nbt_tags) => Ok(nbt_tags.len() as i32),
|
||||
NbtTag::Compound(nbt_compound) => Ok(nbt_compound.child_tags.len() as i32),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
literal("get").then(
|
||||
literal("entity")
|
||||
.then(argument(ARG_ENTITY, EntityArgumentConsumer).execute(GetEntityDataExecutor)),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
use crate::command::CommandResult;
|
||||
use crate::command::args::gamemode::GamemodeArgumentConsumer;
|
||||
use crate::command::args::{Arg, GetCloned};
|
||||
use crate::command::dispatcher::CommandError::InvalidConsumption;
|
||||
use crate::command::tree::builder::argument;
|
||||
use crate::command::{CommandExecutor, CommandSender, args::ConsumedArgs, tree::CommandTree};
|
||||
use pumpkin_util::GameMode;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const NAMES: [&str; 1] = ["defaultgamemode"];
|
||||
|
||||
const DESCRIPTION: &str = "Change the default gamemode";
|
||||
|
||||
pub const ARG_GAMEMODE: &str = "gamemode";
|
||||
|
||||
pub struct DefaultGamemode {
|
||||
pub gamemode: GameMode,
|
||||
}
|
||||
|
||||
struct DefaultGamemodeExecutor;
|
||||
|
||||
impl CommandExecutor for DefaultGamemodeExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::GameMode(gamemode)) = args.get_cloned(&ARG_GAMEMODE) else {
|
||||
return Err(InvalidConsumption(Some(ARG_GAMEMODE.into())));
|
||||
};
|
||||
|
||||
let mut successful_changes: i32 = 0;
|
||||
if server.basic_config.force_gamemode {
|
||||
for player in server.get_all_players() {
|
||||
if player.set_gamemode(gamemode).await {
|
||||
successful_changes += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let gamemode_string = format!("{gamemode:?}").to_lowercase();
|
||||
let gamemode_string = format!("gameMode.{gamemode_string}");
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_DEFAULTGAMEMODE_SUCCESS,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_DEFAULTGAMEMODE_SUCCESS,
|
||||
[TextComponent::translate_cross(
|
||||
gamemode_string.clone(),
|
||||
gamemode_string,
|
||||
[],
|
||||
)],
|
||||
))
|
||||
.await;
|
||||
|
||||
//Change the default gamemode (not in configuration.toml)
|
||||
server.defaultgamemode.lock().await.gamemode = gamemode;
|
||||
|
||||
Ok(successful_changes)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION)
|
||||
.then(argument(ARG_GAMEMODE, GamemodeArgumentConsumer).execute(DefaultGamemodeExecutor))
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
use crate::command::CommandResult;
|
||||
use crate::{
|
||||
command::{
|
||||
CommandError, CommandExecutor, CommandSender,
|
||||
args::{
|
||||
Arg, ConsumedArgs,
|
||||
gameprofile::{GameProfileSuggestionMode, GameProfilesArgumentConsumer},
|
||||
},
|
||||
tree::CommandTree,
|
||||
tree::builder::argument,
|
||||
},
|
||||
data::SaveJSONConfiguration,
|
||||
};
|
||||
use CommandError::InvalidConsumption;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const NAMES: [&str; 1] = ["deop"];
|
||||
const DESCRIPTION: &str = "Revokes operator status from a player.";
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let mut config = server.data.operator_config.write().await;
|
||||
|
||||
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
|
||||
let mut succeeded_deops: i32 = 0;
|
||||
for profile in targets {
|
||||
if let Some(op_index) = config.ops.iter().position(|o| o.uuid == profile.id) {
|
||||
config.ops.remove(op_index);
|
||||
succeeded_deops += 1;
|
||||
|
||||
if let Some(player) = server.get_player_by_uuid(profile.id) {
|
||||
let command_dispatcher = server.command_dispatcher.read().await;
|
||||
player
|
||||
.set_permission_lvl(
|
||||
server,
|
||||
pumpkin_util::PermissionLvl::Zero,
|
||||
&command_dispatcher,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
let msg = TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_DEOP_SUCCESS,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_DEOP_SUCCESS,
|
||||
[TextComponent::text(profile.name.clone())],
|
||||
);
|
||||
sender.send_message(msg).await;
|
||||
}
|
||||
}
|
||||
|
||||
if succeeded_deops > 0 {
|
||||
config.save();
|
||||
}
|
||||
|
||||
if succeeded_deops == 0 {
|
||||
Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_DEOP_FAILED,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_DEOP_FAILED,
|
||||
[],
|
||||
)))
|
||||
} else {
|
||||
Ok(succeeded_deops)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(
|
||||
ARG_TARGETS,
|
||||
GameProfilesArgumentConsumer::new(GameProfileSuggestionMode::OpNames, false),
|
||||
)
|
||||
.execute(Executor),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command, literal};
|
||||
use crate::command::argument_types::dialog::{DialogArg, DialogArgumentType};
|
||||
use crate::command::argument_types::entity::EntityArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::LiteralCommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use pumpkin_protocol::IdOr;
|
||||
use pumpkin_protocol::java::client::dialog::DialogNBT;
|
||||
use pumpkin_protocol::java::client::play::{CPlayClearDialog, CPlayShowDialog};
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const DESCRIPTION: &str = "Manages player dialog screens.";
|
||||
const PERMISSION: &str = "minecraft:command.dialog";
|
||||
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
const ARG_DIALOG: &str = "dialog";
|
||||
|
||||
struct DialogClearExecutor;
|
||||
|
||||
impl CommandExecutor for DialogClearExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_players(context, ARG_TARGETS).await?;
|
||||
|
||||
let count = targets.len();
|
||||
let packet = CPlayClearDialog::new();
|
||||
for player in &targets {
|
||||
player.client.send_packet_now(&packet).await;
|
||||
}
|
||||
|
||||
let msg = if count == 1 {
|
||||
TextComponent::text(format!(
|
||||
"Cleared dialog for {}",
|
||||
targets[0].gameprofile.name
|
||||
))
|
||||
} else {
|
||||
TextComponent::text(format!("Cleared dialogs for {count} players"))
|
||||
};
|
||||
context.source.send_feedback(msg, true).await;
|
||||
|
||||
Ok(count as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
static REGISTRY_ERROR: LiteralCommandErrorType = LiteralCommandErrorType::new(
|
||||
"Registry-defined dialogs are not yet supported. Please specify the dialog inline using SNBT.",
|
||||
);
|
||||
|
||||
struct DialogShowExecutor;
|
||||
|
||||
impl CommandExecutor for DialogShowExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_players(context, ARG_TARGETS).await?;
|
||||
let dialog_arg = DialogArgumentType::get(context, ARG_DIALOG)?;
|
||||
|
||||
match dialog_arg {
|
||||
DialogArg::Nbt(compound) => {
|
||||
let count = targets.len();
|
||||
let dialog_nbt = DialogNBT::from_nbt(compound);
|
||||
let packet = CPlayShowDialog::new(IdOr::Value(dialog_nbt));
|
||||
|
||||
for player in &targets {
|
||||
player.client.send_packet_now(&packet).await;
|
||||
}
|
||||
|
||||
let msg = if count == 1 {
|
||||
TextComponent::text(format!(
|
||||
"Showed dialog to {}",
|
||||
targets[0].gameprofile.name
|
||||
))
|
||||
} else {
|
||||
TextComponent::text(format!("Showed dialog to {count} players"))
|
||||
};
|
||||
context.source.send_feedback(msg, true).await;
|
||||
|
||||
Ok(count as i32)
|
||||
}
|
||||
DialogArg::Id(_id) => Err(REGISTRY_ERROR.create_without_context()),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("dialog", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.then(literal("clear").then(
|
||||
argument(ARG_TARGETS, EntityArgumentType::Players).executes(DialogClearExecutor),
|
||||
))
|
||||
.then(
|
||||
literal("show").then(
|
||||
argument(ARG_TARGETS, EntityArgumentType::Players).then(
|
||||
argument(ARG_DIALOG, DialogArgumentType).executes(DialogShowExecutor),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, command, literal};
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_util::{Difficulty, PermissionLvl};
|
||||
|
||||
const DESCRIPTION: &str = "Query or change the difficulty of the world.";
|
||||
const PERMISSION: &str = "minecraft:command.difficulty";
|
||||
|
||||
const FAILURE_ERROR_TYPE: CommandErrorType<1> =
|
||||
CommandErrorType::new("commands.difficulty.failure", "commands.difficulty.failure");
|
||||
|
||||
struct DifficultyQueryExecutor;
|
||||
|
||||
impl CommandExecutor for DifficultyQueryExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let difficulty = context.server().get_difficulty();
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
"commands.difficulty.query",
|
||||
"commands.difficulty.query",
|
||||
[TextComponent::translate_cross(
|
||||
difficulty.translation_key(),
|
||||
difficulty.translation_key(),
|
||||
[],
|
||||
)],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(difficulty as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct DifficultySetExecutor(Difficulty);
|
||||
|
||||
impl CommandExecutor for DifficultySetExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let difficulty = self.0;
|
||||
let server = context.server();
|
||||
|
||||
{
|
||||
let level_info = server.level_info.load();
|
||||
|
||||
if level_info.difficulty == difficulty {
|
||||
return Err(FAILURE_ERROR_TYPE
|
||||
.create_without_context(TextComponent::text(difficulty.name())));
|
||||
}
|
||||
}
|
||||
|
||||
server.set_difficulty(difficulty, true).await;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_DIFFICULTY_SUCCESS,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_DIFFICULTY_SUCCESS,
|
||||
[TextComponent::translate_cross(
|
||||
difficulty.translation_key(),
|
||||
difficulty.translation_key(),
|
||||
[],
|
||||
)],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(0)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("difficulty", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.then(literal("peaceful").executes(DifficultySetExecutor(Difficulty::Peaceful)))
|
||||
.then(literal("easy").executes(DifficultySetExecutor(Difficulty::Easy)))
|
||||
.then(literal("normal").executes(DifficultySetExecutor(Difficulty::Normal)))
|
||||
.then(literal("hard").executes(DifficultySetExecutor(Difficulty::Hard)))
|
||||
.executes(DifficultyQueryExecutor),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
use crate::TextComponent;
|
||||
use crate::command::args::bool::BoolArgConsumer;
|
||||
use crate::command::args::bounded_num::BoundedNumArgumentConsumer;
|
||||
use crate::command::args::players::PlayersArgumentConsumer;
|
||||
use crate::command::args::resource::effect::EffectTypeArgumentConsumer;
|
||||
use crate::command::args::{Arg, ConsumedArgs, FindArgDefaultName};
|
||||
use crate::command::dispatcher::CommandError::{self, InvalidConsumption};
|
||||
use crate::command::tree::CommandTree;
|
||||
use crate::command::tree::builder::{argument, literal};
|
||||
use crate::command::{CommandExecutor, CommandResult, CommandSender};
|
||||
use crate::entity::EntityBase;
|
||||
use pumpkin_data::potion::Effect;
|
||||
|
||||
const NAMES: [&str; 1] = ["effect"];
|
||||
|
||||
const DESCRIPTION: &str = "Adds or removes the status effects of players and other entities.";
|
||||
|
||||
const ARG_CLEAR: &str = "clear";
|
||||
const ARG_GIVE: &str = "give";
|
||||
const ARG_EFFECT: &str = "effect";
|
||||
const ARG_TARGET: &str = "target";
|
||||
const ARG_SECOND: &str = "seconds";
|
||||
const ARG_INFINITE: &str = "infinite";
|
||||
const ARG_AMPLIFIER: &str = "amplifier";
|
||||
const ARG_HIDE_PARTICLE: &str = "hideParticles";
|
||||
|
||||
enum Time {
|
||||
Base,
|
||||
Specified,
|
||||
Infinite,
|
||||
}
|
||||
|
||||
enum Amplifier {
|
||||
Base,
|
||||
Specified,
|
||||
}
|
||||
|
||||
struct GiveExecutor(Time, Amplifier, bool);
|
||||
|
||||
impl CommandExecutor for GiveExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Players(targets)) = args.get(ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
let Some(Arg::Effect(effect)) = args.get(ARG_EFFECT) else {
|
||||
return Err(InvalidConsumption(Some(ARG_EFFECT.into())));
|
||||
};
|
||||
|
||||
//duration is in tick, so * 20 (not for the infinite because -1*20 cause visual glitch)
|
||||
let second = match self.0 {
|
||||
Time::Base => 30 * 20,
|
||||
Time::Specified => {
|
||||
BoundedNumArgumentConsumer::new()
|
||||
.name("seconds")
|
||||
.min(1)
|
||||
.max(1_000_000)
|
||||
.find_arg_default_name(args)??
|
||||
* 20
|
||||
}
|
||||
Time::Infinite => -1,
|
||||
};
|
||||
|
||||
let amplifier: u8 = match self.1 {
|
||||
Amplifier::Base => 0,
|
||||
Amplifier::Specified => BoundedNumArgumentConsumer::<i32>::new()
|
||||
.name("amplifier")
|
||||
.min(0)
|
||||
.max(255)
|
||||
.find_arg_default_name(args)?? as u8,
|
||||
};
|
||||
|
||||
let mut hide_particles = self.2;
|
||||
//if false -> parameter is referred
|
||||
if !hide_particles {
|
||||
let Some(Arg::Bool(hide_particle)) = args.get(ARG_HIDE_PARTICLE) else {
|
||||
return Err(InvalidConsumption(Some(ARG_HIDE_PARTICLE.into())));
|
||||
};
|
||||
|
||||
hide_particles = *hide_particle;
|
||||
}
|
||||
|
||||
let mut successes = 0;
|
||||
|
||||
for target in targets {
|
||||
if target.living_entity.has_effect(effect).await
|
||||
&& target
|
||||
.living_entity
|
||||
.get_effect(effect)
|
||||
.await
|
||||
.expect("Effect should exist because has_effect returned true")
|
||||
.amplifier
|
||||
>= amplifier
|
||||
{
|
||||
} else {
|
||||
target
|
||||
.add_effect(Effect {
|
||||
effect_type: effect,
|
||||
duration: second,
|
||||
amplifier,
|
||||
ambient: false, //this is not a beacon effect
|
||||
show_particles: !hide_particles,
|
||||
show_icon: true,
|
||||
blend: true, //Currently only used in the DARKNESS effect to apply extra void fog and adjust the gamma value for lighting.
|
||||
})
|
||||
.await;
|
||||
successes += 1;
|
||||
}
|
||||
}
|
||||
|
||||
let translation_name = TextComponent::translate_cross(
|
||||
effect.translation_key.to_string(),
|
||||
effect.translation_key.to_string(),
|
||||
[],
|
||||
);
|
||||
|
||||
if successes == 0 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.effect.give.failed",
|
||||
"commands.effect.give.failed",
|
||||
[],
|
||||
)));
|
||||
} else if targets.len() == 1 {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.give.success.single",
|
||||
"commands.effect.give.success.single",
|
||||
[translation_name, targets[0].get_display_name().await],
|
||||
))
|
||||
.await;
|
||||
} else {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.give.success.multiple",
|
||||
"commands.effect.give.success.multiple",
|
||||
[
|
||||
translation_name,
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(successes)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ClearExecutor(bool); //the param -> true = delete every effect, false = only one
|
||||
|
||||
impl CommandExecutor for ClearExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Players(targets)) = args.get(ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
|
||||
let effect;
|
||||
//Only one effect
|
||||
if self.0 {
|
||||
let mut succeeded_clears: i32 = 0;
|
||||
for target in targets {
|
||||
if target.remove_all_effects().await {
|
||||
succeeded_clears += 1;
|
||||
}
|
||||
}
|
||||
|
||||
//if the player or everyplayer don't have any effect
|
||||
if succeeded_clears == 0 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.effect.clear.everything.failed",
|
||||
"commands.effect.clear.everything.failed",
|
||||
[],
|
||||
)));
|
||||
}
|
||||
//a player have at least 1 effect
|
||||
else if targets.len() == 1 {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.clear.everything.success.single",
|
||||
"commands.effect.clear.everything.success.single",
|
||||
[targets[0].get_display_name().await],
|
||||
))
|
||||
.await;
|
||||
} else {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.clear.everything.success.multiple",
|
||||
"commands.effect.clear.everything.success.multiple",
|
||||
[TextComponent::text(targets.len().to_string())],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
Ok(succeeded_clears)
|
||||
} else {
|
||||
let Some(Arg::Effect(effect_type)) = args.get(ARG_EFFECT) else {
|
||||
return Err(InvalidConsumption(Some(ARG_EFFECT.into())));
|
||||
};
|
||||
|
||||
effect = *effect_type;
|
||||
|
||||
let mut succeeded_clears: i32 = 0;
|
||||
for target in targets {
|
||||
if target.living_entity.has_effect(effect).await {
|
||||
target.remove_effect(effect).await;
|
||||
succeeded_clears += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if succeeded_clears == 0 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.effect.clear.specific.failed",
|
||||
"commands.effect.clear.specific.failed",
|
||||
[],
|
||||
)));
|
||||
} else if targets.len() == 1 {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.clear.specific.success.single",
|
||||
"commands.effect.clear.specific.success.single",
|
||||
[
|
||||
TextComponent::translate_cross(
|
||||
effect.translation_key,
|
||||
effect.translation_key,
|
||||
[],
|
||||
),
|
||||
targets[0].get_display_name().await,
|
||||
],
|
||||
))
|
||||
.await;
|
||||
} else {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.effect.clear.specific.success.multiple",
|
||||
"commands.effect.clear.specific.success.multiple",
|
||||
[
|
||||
TextComponent::translate_cross(
|
||||
effect.translation_key,
|
||||
effect.translation_key,
|
||||
[],
|
||||
),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
Ok(succeeded_clears)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION)
|
||||
.then(
|
||||
literal(ARG_CLEAR).then(
|
||||
argument(ARG_TARGET, PlayersArgumentConsumer)
|
||||
.execute(ClearExecutor(true))
|
||||
.then(
|
||||
argument(ARG_EFFECT, EffectTypeArgumentConsumer)
|
||||
.execute(ClearExecutor(false)),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal(ARG_GIVE).then(
|
||||
argument(ARG_TARGET, PlayersArgumentConsumer).then(
|
||||
argument(ARG_EFFECT, EffectTypeArgumentConsumer)
|
||||
.execute(GiveExecutor(Time::Base, Amplifier::Base, true))
|
||||
//for specified time
|
||||
.then(
|
||||
argument(
|
||||
ARG_SECOND,
|
||||
BoundedNumArgumentConsumer::new()
|
||||
.name("seconds")
|
||||
.min(0)
|
||||
.max(1_000_000),
|
||||
)
|
||||
.execute(GiveExecutor(Time::Specified, Amplifier::Base, true))
|
||||
.then(
|
||||
argument(
|
||||
ARG_AMPLIFIER,
|
||||
BoundedNumArgumentConsumer::new()
|
||||
.name("amplifier")
|
||||
.min(1)
|
||||
.max(255),
|
||||
)
|
||||
.execute(GiveExecutor(Time::Specified, Amplifier::Specified, true))
|
||||
.then(
|
||||
argument(ARG_HIDE_PARTICLE, BoolArgConsumer).execute(
|
||||
GiveExecutor(Time::Specified, Amplifier::Specified, false),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal(ARG_INFINITE)
|
||||
.execute(GiveExecutor(Time::Infinite, Amplifier::Base, true))
|
||||
.then(
|
||||
argument(
|
||||
ARG_AMPLIFIER,
|
||||
BoundedNumArgumentConsumer::new()
|
||||
.name("amplifier")
|
||||
.min(1)
|
||||
.max(255),
|
||||
)
|
||||
.execute(GiveExecutor(
|
||||
Time::Infinite,
|
||||
Amplifier::Specified,
|
||||
true,
|
||||
))
|
||||
.then(
|
||||
argument(ARG_HIDE_PARTICLE, BoolArgConsumer).execute(
|
||||
GiveExecutor(
|
||||
Time::Infinite,
|
||||
Amplifier::Specified,
|
||||
false,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
use pumpkin_data::{Enchantment, translation};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::command::args::bounded_num::{BoundedNumArgumentConsumer, NotInBounds};
|
||||
use crate::command::args::entities::EntitiesArgumentConsumer;
|
||||
use crate::command::args::resource::enchantment::EnchantmentArgumentConsumer;
|
||||
use crate::command::args::{ConsumedArgs, FindArgDefaultName};
|
||||
use crate::command::tree::CommandTree;
|
||||
use crate::command::tree::builder::argument_default_name;
|
||||
use crate::command::{CommandError, CommandExecutor, CommandResult, CommandSender};
|
||||
use crate::entity::EntityBase;
|
||||
use pumpkin_data::data_component_impl::EnchantmentsImpl;
|
||||
|
||||
const NAMES: [&str; 1] = ["enchant"];
|
||||
const DESCRIPTION: &str = "Adds an enchantment to a player's selected item, subject to the same restrictions as an anvil. Also works on any mob or entity holding a weapon/tool/armor in its main hand.";
|
||||
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntitiesArgumentConsumer.find_arg_default_name(args)?;
|
||||
let enchantment = EnchantmentArgumentConsumer.find_arg_default_name(args)?;
|
||||
let level = match enchantment_level_consumer().find_arg_default_name(args) {
|
||||
Err(_) => 1,
|
||||
Ok(Ok(level)) => level,
|
||||
Ok(Err(err)) => {
|
||||
let err_msg = match err {
|
||||
NotInBounds::LowerBound(val, min) => TextComponent::translate_cross(
|
||||
"argument.integer.low",
|
||||
"argument.integer.low",
|
||||
&[
|
||||
TextComponent::text(min.to_string()),
|
||||
TextComponent::text(val.to_string()),
|
||||
],
|
||||
),
|
||||
NotInBounds::UpperBound(val, max) => TextComponent::translate_cross(
|
||||
"argument.integer.big",
|
||||
"argument.integer.big",
|
||||
&[
|
||||
TextComponent::text(max.to_string()),
|
||||
TextComponent::text(val.to_string()),
|
||||
],
|
||||
),
|
||||
};
|
||||
|
||||
return Err(CommandError::CommandFailed(err_msg));
|
||||
}
|
||||
};
|
||||
|
||||
if level > enchantment.max_level {
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ENCHANT_FAILED_LEVEL,
|
||||
translation::bedrock::COMMANDS_ENCHANT_INVALIDLEVEL,
|
||||
[
|
||||
TextComponent::text(level.to_string()),
|
||||
TextComponent::text(enchantment.max_level.to_string()),
|
||||
],
|
||||
);
|
||||
return Err(CommandError::CommandFailed(msg));
|
||||
}
|
||||
|
||||
let mut successful_targets = 0;
|
||||
|
||||
if targets.len() == 1 {
|
||||
return match enchant_target(&targets[0], enchantment, level).await {
|
||||
Ok(()) => {
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ENCHANT_SUCCESS_SINGLE,
|
||||
translation::bedrock::COMMANDS_ENCHANT_SUCCESS,
|
||||
[
|
||||
enchantment.get_fullname(level),
|
||||
targets[0].get_display_name().await,
|
||||
],
|
||||
);
|
||||
sender.send_message(msg).await;
|
||||
Ok(1)
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
}
|
||||
|
||||
for target in targets {
|
||||
if enchant_target(target, enchantment, level).await.is_ok() {
|
||||
successful_targets += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if successful_targets == 0 {
|
||||
return Err(commands_enchant_failed());
|
||||
}
|
||||
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ENCHANT_SUCCESS_MULTIPLE,
|
||||
translation::bedrock::COMMANDS_ENCHANT_SUCCESS,
|
||||
[
|
||||
enchantment.get_fullname(level),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
);
|
||||
sender.send_message(msg).await;
|
||||
Ok(successful_targets)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const fn enchantment_level_consumer() -> BoundedNumArgumentConsumer<i32> {
|
||||
BoundedNumArgumentConsumer::new()
|
||||
.name("level")
|
||||
.min(0)
|
||||
.max(i32::MAX)
|
||||
}
|
||||
|
||||
fn commands_enchant_failed() -> CommandError {
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ENCHANT_FAILED,
|
||||
translation::bedrock::COMMANDS_ENCHANT_CANTENCHANT,
|
||||
[TextComponent::text("")],
|
||||
);
|
||||
CommandError::CommandFailed(msg)
|
||||
}
|
||||
|
||||
async fn enchant_target(
|
||||
target: &Arc<dyn EntityBase>,
|
||||
enchantment: &'static Enchantment,
|
||||
level: i32,
|
||||
) -> Result<(), CommandError> {
|
||||
let Some(player) = target.get_player() else {
|
||||
return Err(commands_enchant_failed());
|
||||
};
|
||||
|
||||
let lock = player.inventory.held_item();
|
||||
let mut item = lock.lock().await;
|
||||
|
||||
if item.is_empty() {
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ENCHANT_FAILED_ITEMLESS,
|
||||
translation::bedrock::COMMANDS_ENCHANT_NOITEM,
|
||||
[target.get_display_name().await],
|
||||
);
|
||||
return Err(CommandError::CommandFailed(msg));
|
||||
}
|
||||
|
||||
if !enchantment.can_enchant(item.item) {
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ENCHANT_FAILED_INCOMPATIBLE,
|
||||
translation::bedrock::COMMANDS_ENCHANT_CANTENCHANT,
|
||||
[item.item.translated_name()],
|
||||
);
|
||||
return Err(CommandError::CommandFailed(msg));
|
||||
}
|
||||
|
||||
if let Some(data) = item.get_data_component::<EnchantmentsImpl>()
|
||||
&& !enchantment.is_enchantment_compatible(data)
|
||||
{
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ENCHANT_FAILED_INCOMPATIBLE,
|
||||
translation::bedrock::COMMANDS_ENCHANT_CANTENCHANT,
|
||||
[item.item.translated_name()],
|
||||
);
|
||||
return Err(CommandError::CommandFailed(msg));
|
||||
}
|
||||
|
||||
item.enchant(enchantment, level);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument_default_name(EntitiesArgumentConsumer).then(
|
||||
argument_default_name(EnchantmentArgumentConsumer)
|
||||
.then(argument_default_name(enchantment_level_consumer()).execute(Executor))
|
||||
.execute(Executor),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command, literal};
|
||||
use crate::command::argument_types::block::BlockArgumentType;
|
||||
use crate::command::argument_types::coordinates::block_pos::BlockPosArgumentType;
|
||||
use crate::command::argument_types::coordinates::rotation::RotationArgumentType;
|
||||
use crate::command::argument_types::coordinates::vec3::Vec3ArgumentType;
|
||||
use crate::command::argument_types::core::string::StringArgumentType;
|
||||
use crate::command::argument_types::entity::EntityArgumentType;
|
||||
use crate::command::argument_types::entity_anchor::EntityAnchorArgumentType;
|
||||
use crate::command::argument_types::resource_key::ResourceKeyArgument;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::attached::{CommandNodeId, NodeId};
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::tree::Tree;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult, RedirectModifier, Redirection};
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::identifier::Identifier;
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const DESCRIPTION: &str = "Execute a command with a modified context.";
|
||||
const PERMISSION: &str = "minecraft:command.execute";
|
||||
|
||||
static ERROR_INVALID_DIMENSION: CommandErrorType<1> =
|
||||
CommandErrorType::new("argument.dimension.invalid", "argument.dimension.invalid");
|
||||
|
||||
struct ExecuteRunExecutor;
|
||||
|
||||
impl CommandExecutor for ExecuteRunExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let command_str = StringArgumentType::get(context, "command")?;
|
||||
let dispatcher = context.server().command_dispatcher.read().await;
|
||||
let result = dispatcher
|
||||
.execute_input(command_str, &context.source)
|
||||
.await?;
|
||||
Ok(result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn execute_as_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
||||
let mut sources = Vec::new();
|
||||
for target in targets {
|
||||
let mut source = context.source.as_ref().clone();
|
||||
let display_name = target.get_display_name().await;
|
||||
let name = target.get_name().get_text();
|
||||
source.entity = Some(target.clone());
|
||||
source.name = name;
|
||||
source.display_name = display_name;
|
||||
sources.push(Arc::new(source));
|
||||
}
|
||||
Ok(sources)
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_at_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
||||
let mut sources = Vec::new();
|
||||
for target in targets {
|
||||
let entity = target.get_entity();
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.position = entity.pos.load();
|
||||
source.rotation = Vector2::new(entity.yaw.load(), entity.pitch.load());
|
||||
source.world = Some(entity.world.load().clone());
|
||||
sources.push(Arc::new(source));
|
||||
}
|
||||
Ok(sources)
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_in_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let dimension_key = ResourceKeyArgument::get_registry_key(
|
||||
context,
|
||||
"dimension",
|
||||
&Identifier::vanilla_static("dimension"),
|
||||
&ERROR_INVALID_DIMENSION,
|
||||
)?;
|
||||
let dimension_name = dimension_key.identifier.to_string();
|
||||
let server = context.server();
|
||||
let worlds = server.worlds.load();
|
||||
let target_world = worlds
|
||||
.iter()
|
||||
.find(|w| w.dimension.minecraft_name == dimension_name);
|
||||
|
||||
target_world.map_or_else(
|
||||
|| {
|
||||
Err(ERROR_INVALID_DIMENSION
|
||||
.create_without_context(TextComponent::text(dimension_name)))
|
||||
},
|
||||
|target_world| {
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.world = Some(target_world.clone());
|
||||
Ok(vec![Arc::new(source)])
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_positioned_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let pos = Vec3ArgumentType::get_vector3(context, "pos")?;
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.position = pos;
|
||||
Ok(vec![Arc::new(source)])
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_positioned_as_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
||||
let mut sources = Vec::new();
|
||||
for target in targets {
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.position = target.get_entity().pos.load();
|
||||
sources.push(Arc::new(source));
|
||||
}
|
||||
Ok(sources)
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_rotated_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let rot_coords = RotationArgumentType::get(context, "rotation")?;
|
||||
let rot = rot_coords.rotation(&context.source);
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.rotation = rot;
|
||||
Ok(vec![Arc::new(source)])
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_rotated_as_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
||||
let mut sources = Vec::new();
|
||||
for target in targets {
|
||||
let entity = target.get_entity();
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.rotation = Vector2::new(entity.yaw.load(), entity.pitch.load());
|
||||
sources.push(Arc::new(source));
|
||||
}
|
||||
Ok(sources)
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_if_entity_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
||||
if targets.is_empty() {
|
||||
Ok(vec![])
|
||||
} else {
|
||||
Ok(vec![context.source.clone()])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_unless_entity_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
||||
if targets.is_empty() {
|
||||
Ok(vec![context.source.clone()])
|
||||
} else {
|
||||
Ok(vec![])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_align_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let axes = StringArgumentType::get(context, "axes")?;
|
||||
let mut source = context.source.as_ref().clone();
|
||||
|
||||
let has_x = axes.contains('x');
|
||||
let has_y = axes.contains('y');
|
||||
let has_z = axes.contains('z');
|
||||
|
||||
if has_x {
|
||||
source.position.x = source.position.x.floor();
|
||||
}
|
||||
if has_y {
|
||||
source.position.y = source.position.y.floor();
|
||||
}
|
||||
if has_z {
|
||||
source.position.z = source.position.z.floor();
|
||||
}
|
||||
|
||||
Ok(vec![Arc::new(source)])
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_anchored_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let anchor = EntityAnchorArgumentType::get(context, "anchor")?;
|
||||
let mut source = context.source.as_ref().clone();
|
||||
source.entity_anchor = anchor;
|
||||
Ok(vec![Arc::new(source)])
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_facing_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let pos = Vec3ArgumentType::get_vector3(context, "pos")?;
|
||||
let mut source = context.source.as_ref().clone();
|
||||
|
||||
let dx = pos.x - source.position.x;
|
||||
let dy = pos.y - source.position.y;
|
||||
let dz = pos.z - source.position.z;
|
||||
|
||||
let xz_dist = dx.hypot(dz);
|
||||
let yaw = (dz.atan2(dx).to_degrees() as f32) - 90.0;
|
||||
let pitch = -(dy.atan2(xz_dist).to_degrees() as f32);
|
||||
|
||||
source.rotation = Vector2::new(yaw, pitch);
|
||||
Ok(vec![Arc::new(source)])
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_facing_entity_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
||||
let anchor = EntityAnchorArgumentType::get(context, "anchor")?;
|
||||
let mut sources = Vec::new();
|
||||
|
||||
for target in targets {
|
||||
let target_pos = anchor.position_at_entity(target.get_entity());
|
||||
let mut source = context.source.as_ref().clone();
|
||||
|
||||
let dx = target_pos.x - source.position.x;
|
||||
let dy = target_pos.y - source.position.y;
|
||||
let dz = target_pos.z - source.position.z;
|
||||
|
||||
let xz_dist = dx.hypot(dz);
|
||||
let yaw = (dz.atan2(dx).to_degrees() as f32) - 90.0;
|
||||
let pitch = -(dy.atan2(xz_dist).to_degrees() as f32);
|
||||
|
||||
source.rotation = Vector2::new(yaw, pitch);
|
||||
sources.push(Arc::new(source));
|
||||
}
|
||||
Ok(sources)
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_if_block_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||
let expected_block = BlockArgumentType::get(context, "block")?;
|
||||
|
||||
if let Some(ref world) = context.source.world {
|
||||
let block = world.get_block(&pos);
|
||||
if block == expected_block {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
}
|
||||
Ok(vec![])
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_unless_block_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||
let expected_block = BlockArgumentType::get(context, "block")?;
|
||||
|
||||
if let Some(ref world) = context.source.world {
|
||||
let block = world.get_block(&pos);
|
||||
if block != expected_block {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
} else {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
Ok(vec![])
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_if_loaded_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||
|
||||
if let Some(ref world) = context.source.world
|
||||
&& world.is_loaded(&pos)
|
||||
{
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
Ok(vec![])
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_unless_loaded_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||
|
||||
if let Some(ref world) = context.source.world {
|
||||
if !world.is_loaded(&pos) {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
} else {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
Ok(vec![])
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_if_dimension_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let dimension_key = ResourceKeyArgument::get_registry_key(
|
||||
context,
|
||||
"dimension",
|
||||
&Identifier::vanilla_static("dimension"),
|
||||
&ERROR_INVALID_DIMENSION,
|
||||
)?;
|
||||
let dimension_name = dimension_key.identifier.to_string();
|
||||
|
||||
if let Some(ref world) = context.source.world
|
||||
&& world.dimension.minecraft_name == dimension_name
|
||||
{
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
Ok(vec![])
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_unless_dimension_modifier<'a>(
|
||||
context: &'a CommandContext,
|
||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
||||
Box::pin(async move {
|
||||
let dimension_key = ResourceKeyArgument::get_registry_key(
|
||||
context,
|
||||
"dimension",
|
||||
&Identifier::vanilla_static("dimension"),
|
||||
&ERROR_INVALID_DIMENSION,
|
||||
)?;
|
||||
let dimension_name = dimension_key.identifier.to_string();
|
||||
|
||||
if let Some(ref world) = context.source.world {
|
||||
if world.dimension.minecraft_name != dimension_name {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
} else {
|
||||
return Ok(vec![context.source.clone()]);
|
||||
}
|
||||
Ok(vec![])
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_lines)]
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
));
|
||||
|
||||
let builder = command("execute", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.then(literal("run").then(
|
||||
argument("command", StringArgumentType::GreedyPhrase).executes(ExecuteRunExecutor),
|
||||
))
|
||||
.then(
|
||||
literal("as").then(argument("targets", EntityArgumentType::Entities).fork(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_as_modifier)),
|
||||
)),
|
||||
)
|
||||
.then(
|
||||
literal("at").then(argument("targets", EntityArgumentType::Entities).fork(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_at_modifier)),
|
||||
)),
|
||||
)
|
||||
.then(
|
||||
literal("in").then(
|
||||
argument(
|
||||
"dimension",
|
||||
ResourceKeyArgument(Identifier::vanilla_static("dimension")),
|
||||
)
|
||||
.redirect_with_modifier(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_in_modifier)),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("positioned")
|
||||
.then(
|
||||
literal("as").then(argument("targets", EntityArgumentType::Entities).fork(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_positioned_as_modifier)),
|
||||
)),
|
||||
)
|
||||
.then(
|
||||
argument("pos", Vec3ArgumentType::Default).redirect_with_modifier(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_positioned_modifier)),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("rotated")
|
||||
.then(
|
||||
literal("as").then(argument("targets", EntityArgumentType::Entities).fork(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_rotated_as_modifier)),
|
||||
)),
|
||||
)
|
||||
.then(
|
||||
argument("rotation", RotationArgumentType).redirect_with_modifier(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_rotated_modifier)),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(literal("align").then(
|
||||
argument("axes", StringArgumentType::SingleWord).redirect_with_modifier(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_align_modifier)),
|
||||
),
|
||||
))
|
||||
.then(literal("anchored").then(
|
||||
argument("anchor", EntityAnchorArgumentType).redirect_with_modifier(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_anchored_modifier)),
|
||||
),
|
||||
))
|
||||
.then(
|
||||
literal("facing")
|
||||
.then(literal("entity").then(
|
||||
argument("targets", EntityArgumentType::Entities).then(
|
||||
argument("anchor", EntityAnchorArgumentType).fork(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_facing_entity_modifier)),
|
||||
),
|
||||
),
|
||||
))
|
||||
.then(
|
||||
argument("pos", Vec3ArgumentType::Default).redirect_with_modifier(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_facing_modifier)),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("if")
|
||||
.then(literal("entity").then(
|
||||
argument("targets", EntityArgumentType::Entities).redirect_with_modifier(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_if_entity_modifier)),
|
||||
),
|
||||
))
|
||||
.then(
|
||||
literal("block").then(argument("pos", BlockPosArgumentType).then(
|
||||
argument("block", BlockArgumentType).redirect_with_modifier(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_if_block_modifier)),
|
||||
),
|
||||
)),
|
||||
)
|
||||
.then(literal("loaded").then(
|
||||
argument("pos", BlockPosArgumentType).redirect_with_modifier(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_if_loaded_modifier)),
|
||||
),
|
||||
))
|
||||
.then(
|
||||
literal("dimension").then(
|
||||
argument(
|
||||
"dimension",
|
||||
ResourceKeyArgument(Identifier::vanilla_static("dimension")),
|
||||
)
|
||||
.redirect_with_modifier(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_if_dimension_modifier)),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("unless")
|
||||
.then(literal("entity").then(
|
||||
argument("targets", EntityArgumentType::Entities).redirect_with_modifier(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_unless_entity_modifier)),
|
||||
),
|
||||
))
|
||||
.then(
|
||||
literal("block").then(argument("pos", BlockPosArgumentType).then(
|
||||
argument("block", BlockArgumentType).redirect_with_modifier(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_unless_block_modifier)),
|
||||
),
|
||||
)),
|
||||
)
|
||||
.then(literal("loaded").then(
|
||||
argument("pos", BlockPosArgumentType).redirect_with_modifier(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_unless_loaded_modifier)),
|
||||
),
|
||||
))
|
||||
.then(
|
||||
literal("dimension").then(
|
||||
argument(
|
||||
"dimension",
|
||||
ResourceKeyArgument(Identifier::vanilla_static("dimension")),
|
||||
)
|
||||
.redirect_with_modifier(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(execute_unless_dimension_modifier)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
let execute_node_id = dispatcher.register(builder);
|
||||
|
||||
set_redirects_to_execute(
|
||||
&mut dispatcher.tree,
|
||||
NodeId::from(execute_node_id),
|
||||
execute_node_id,
|
||||
);
|
||||
}
|
||||
|
||||
fn set_redirects_to_execute(tree: &mut Tree, parent: NodeId, execute_id: CommandNodeId) {
|
||||
for child_id in tree.get_children(parent) {
|
||||
if let Some(redirect) = tree[child_id].redirect()
|
||||
&& matches!(redirect, Redirection::Root)
|
||||
{
|
||||
tree[child_id].set_redirect(Some(Redirection::Local(NodeId::from(execute_id))));
|
||||
}
|
||||
set_redirects_to_execute(tree, child_id, execute_id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use pumpkin_util::math::experience;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::command::args::bounded_num::BoundedNumArgumentConsumer;
|
||||
use crate::command::args::players::PlayersArgumentConsumer;
|
||||
use crate::command::args::{ConsumedArgs, FindArg};
|
||||
use crate::command::dispatcher::CommandError;
|
||||
use crate::command::tree::CommandTree;
|
||||
use crate::command::tree::builder::{argument, literal};
|
||||
use crate::command::{CommandExecutor, CommandResult, CommandSender};
|
||||
use crate::entity::EntityBase;
|
||||
use crate::entity::player::Player;
|
||||
|
||||
const NAMES: [&str; 2] = ["experience", "xp"];
|
||||
const DESCRIPTION: &str = "Add, set or query player experience.";
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
const ARG_AMOUNT: &str = "amount";
|
||||
|
||||
const fn xp_amount() -> BoundedNumArgumentConsumer<i32> {
|
||||
BoundedNumArgumentConsumer::new()
|
||||
.name(ARG_AMOUNT)
|
||||
.min(0)
|
||||
.max(i32::MAX)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Mode {
|
||||
Add,
|
||||
Set,
|
||||
Query,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum ExpType {
|
||||
Points,
|
||||
Levels,
|
||||
}
|
||||
|
||||
struct Executor {
|
||||
mode: Mode,
|
||||
exp_type: ExpType,
|
||||
}
|
||||
|
||||
impl Executor {
|
||||
async fn handle_query(&self, sender: &CommandSender, target: &Player) -> i32 {
|
||||
let (val, translation_key) = match self.exp_type {
|
||||
ExpType::Levels => (
|
||||
target.experience_level.load(Ordering::Relaxed),
|
||||
"commands.experience.query.levels",
|
||||
),
|
||||
ExpType::Points => (
|
||||
target.experience_points.load(Ordering::Relaxed),
|
||||
"commands.experience.query.points",
|
||||
),
|
||||
};
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation_key,
|
||||
translation_key,
|
||||
[
|
||||
target.get_display_name().await,
|
||||
TextComponent::text(val.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
|
||||
val
|
||||
}
|
||||
|
||||
fn get_success_message(
|
||||
&self,
|
||||
amount: i32,
|
||||
targets: &[Arc<Player>],
|
||||
first_target_name: TextComponent,
|
||||
) -> TextComponent {
|
||||
let type_str = match self.exp_type {
|
||||
ExpType::Points => "points",
|
||||
ExpType::Levels => "levels",
|
||||
};
|
||||
let mode_str = match self.mode {
|
||||
Mode::Add => "add",
|
||||
Mode::Set => "set",
|
||||
Mode::Query => "query",
|
||||
};
|
||||
|
||||
let bedrock_key = match self.exp_type {
|
||||
ExpType::Points => pumpkin_data::translation::bedrock::COMMANDS_XP_SUCCESS,
|
||||
ExpType::Levels => {
|
||||
if amount >= 0 {
|
||||
pumpkin_data::translation::bedrock::COMMANDS_XP_SUCCESS_LEVELS
|
||||
} else {
|
||||
pumpkin_data::translation::bedrock::COMMANDS_XP_SUCCESS_NEGATIVE_LEVELS
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let bedrock_amount = if amount >= 0 { amount } else { amount.abs() };
|
||||
|
||||
if targets.len() > 1 {
|
||||
TextComponent::translate_cross(
|
||||
format!("commands.experience.{mode_str}.{type_str}.success.multiple"),
|
||||
bedrock_key,
|
||||
[
|
||||
TextComponent::text(bedrock_amount.to_string()),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
format!("commands.experience.{mode_str}.{type_str}.success.single"),
|
||||
bedrock_key,
|
||||
[
|
||||
TextComponent::text(bedrock_amount.to_string()),
|
||||
first_target_name,
|
||||
],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if successful. Otherwise, there was a problem setting the points of a player.
|
||||
async fn handle_modify(&self, target: &Arc<Player>, amount: i32) -> bool {
|
||||
match self.exp_type {
|
||||
ExpType::Levels => {
|
||||
if self.mode == Mode::Add {
|
||||
target.add_experience_levels(amount).await;
|
||||
} else {
|
||||
target.set_experience_level(amount, true).await;
|
||||
}
|
||||
}
|
||||
ExpType::Points => {
|
||||
if self.mode == Mode::Add {
|
||||
target.add_experience_points(amount).await;
|
||||
} else {
|
||||
let current_lvl = target.experience_level.load(Ordering::Relaxed);
|
||||
if amount > experience::points_in_level(current_lvl) {
|
||||
return false;
|
||||
}
|
||||
target.set_experience_points(amount).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = PlayersArgumentConsumer::find_arg(args, ARG_TARGETS)?;
|
||||
|
||||
if self.mode == Mode::Query {
|
||||
let target = targets.first().ok_or_else(|| {
|
||||
CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"argument.player.unknown",
|
||||
"argument.player.unknown",
|
||||
[],
|
||||
))
|
||||
})?;
|
||||
|
||||
if targets.len() > 1 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"argument.player.toomany",
|
||||
"argument.player.toomany",
|
||||
[],
|
||||
)));
|
||||
}
|
||||
return Ok(self.handle_query(sender, target).await);
|
||||
}
|
||||
|
||||
// Handle Add/Set
|
||||
let amount = BoundedNumArgumentConsumer::<i32>::find_arg(args, ARG_AMOUNT)??;
|
||||
|
||||
let mut successes = 0;
|
||||
for target in targets {
|
||||
if self.handle_modify(target, amount).await {
|
||||
successes += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if successes == 0 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.experience.set.points.invalid",
|
||||
"commands.experience.set.points.invalid",
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
// Safe to access first() because successes > 0
|
||||
let first_name = targets[0].get_display_name().await;
|
||||
let msg = self.get_success_message(amount, targets, first_name);
|
||||
sender.send_message(msg).await;
|
||||
|
||||
Ok(successes)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION)
|
||||
.then(
|
||||
literal("add").then(
|
||||
argument(ARG_TARGETS, PlayersArgumentConsumer).then(
|
||||
argument(ARG_AMOUNT, xp_amount())
|
||||
.then(literal("levels").execute(Executor {
|
||||
mode: Mode::Add,
|
||||
exp_type: ExpType::Levels,
|
||||
}))
|
||||
.then(literal("points").execute(Executor {
|
||||
mode: Mode::Add,
|
||||
exp_type: ExpType::Points,
|
||||
}))
|
||||
.execute(Executor {
|
||||
mode: Mode::Add,
|
||||
exp_type: ExpType::Points,
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("set").then(
|
||||
argument(ARG_TARGETS, PlayersArgumentConsumer).then(
|
||||
argument(ARG_AMOUNT, xp_amount())
|
||||
.then(literal("levels").execute(Executor {
|
||||
mode: Mode::Set,
|
||||
exp_type: ExpType::Levels,
|
||||
}))
|
||||
.then(literal("points").execute(Executor {
|
||||
mode: Mode::Set,
|
||||
exp_type: ExpType::Points,
|
||||
}))
|
||||
.execute(Executor {
|
||||
mode: Mode::Set,
|
||||
exp_type: ExpType::Points,
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("query").then(
|
||||
argument(ARG_TARGETS, PlayersArgumentConsumer)
|
||||
.then(literal("levels").execute(Executor {
|
||||
mode: Mode::Query,
|
||||
exp_type: ExpType::Levels,
|
||||
}))
|
||||
.then(literal("points").execute(Executor {
|
||||
mode: Mode::Query,
|
||||
exp_type: ExpType::Points,
|
||||
})),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::command::args::block::{
|
||||
BlockArgumentConsumer, BlockPredicate, BlockPredicateArgumentConsumer,
|
||||
};
|
||||
use crate::command::args::position_block::BlockPosArgumentConsumer;
|
||||
use crate::command::args::{ConsumedArgs, FindArg};
|
||||
use crate::command::tree::CommandTree;
|
||||
use crate::command::tree::builder::{argument, literal};
|
||||
use crate::command::{CommandError, CommandExecutor, CommandResult, CommandSender};
|
||||
use crate::world::World;
|
||||
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_data::{Block, BlockStateId};
|
||||
use pumpkin_util::math::position::BlockPos;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_world::world::BlockFlags;
|
||||
|
||||
const NAMES: [&str; 1] = ["fill"];
|
||||
|
||||
const DESCRIPTION: &str = "Fills all or parts of a region with a specific block.";
|
||||
|
||||
const ARG_BLOCK: &str = "block";
|
||||
const ARG_FROM: &str = "from";
|
||||
const ARG_TO: &str = "to";
|
||||
const ARG_FILTER: &str = "filter";
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
enum Mode {
|
||||
/// Destroys blocks with particles and item drops
|
||||
Destroy,
|
||||
/// Leaves only the outer layer of blocks, removes the inner ones (creates a hollow space)
|
||||
Hollow,
|
||||
/// Only replaces air blocks, keeping non-air blocks unchanged
|
||||
Keep,
|
||||
/// Like Hollow but doesn't replace inner blocks with air, just the outline
|
||||
Outline,
|
||||
/// Replaces all blocks with the new block state, without particles
|
||||
#[default]
|
||||
Replace,
|
||||
/// Replaces all blocks with the new block state, without particles and neighbors update
|
||||
Strict,
|
||||
}
|
||||
|
||||
struct Executor(Mode);
|
||||
|
||||
fn not_in_filter(filter: &BlockPredicate, old_block: &Block) -> bool {
|
||||
match filter {
|
||||
BlockPredicate::Tag(tag) => !tag.contains(&old_block.id.as_u16()),
|
||||
BlockPredicate::Block(block) => *block != old_block.id,
|
||||
}
|
||||
}
|
||||
|
||||
enum FillerResult {
|
||||
DidNotPlaceBlock = 0,
|
||||
PlacedBlock = 1,
|
||||
PlacedBlockWithoutUpdate = 2,
|
||||
}
|
||||
|
||||
struct Context {
|
||||
block_state_id: BlockStateId,
|
||||
option_filter: Option<BlockPredicate>,
|
||||
world: Arc<World>,
|
||||
placed_blocks: i32,
|
||||
to_update: Vec<BlockPos>,
|
||||
|
||||
start_x: i32,
|
||||
start_y: i32,
|
||||
start_z: i32,
|
||||
end_x: i32,
|
||||
end_y: i32,
|
||||
end_z: i32,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
/// Checks whether the block position is at the edge of the region stored by this context.
|
||||
#[inline]
|
||||
const fn is_edge(&self, block_position: BlockPos) -> bool {
|
||||
let pos = block_position.0;
|
||||
pos.x == self.start_x
|
||||
|| pos.x == self.end_x
|
||||
|| pos.y == self.start_y
|
||||
|| pos.y == self.end_y
|
||||
|| pos.z == self.start_z
|
||||
|| pos.z == self.end_z
|
||||
}
|
||||
}
|
||||
|
||||
trait Filler {
|
||||
async fn execute_for_pos(context: &Context, block_position: BlockPos) -> FillerResult;
|
||||
|
||||
async fn execute_for_region(context: &mut Context) {
|
||||
for x in context.start_x..=context.end_x {
|
||||
for y in context.start_y..=context.end_y {
|
||||
for z in context.start_z..=context.end_z {
|
||||
let block_position = BlockPos(Vector3::new(x, y, z));
|
||||
let filler_result = Self::execute_for_pos(context, block_position).await;
|
||||
match filler_result {
|
||||
FillerResult::PlacedBlock => {
|
||||
context.placed_blocks += 1;
|
||||
context.to_update.push(block_position);
|
||||
}
|
||||
FillerResult::PlacedBlockWithoutUpdate => {
|
||||
context.placed_blocks += 1;
|
||||
}
|
||||
FillerResult::DidNotPlaceBlock => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct DestroyFiller;
|
||||
impl Filler for DestroyFiller {
|
||||
async fn execute_for_pos(context: &Context, block_position: BlockPos) -> FillerResult {
|
||||
if let Some(filter) = &context.option_filter
|
||||
&& not_in_filter(filter, context.world.get_block(&block_position))
|
||||
{
|
||||
return FillerResult::DidNotPlaceBlock;
|
||||
}
|
||||
context
|
||||
.world
|
||||
.break_block(
|
||||
&block_position,
|
||||
None,
|
||||
BlockFlags::SKIP_DROPS | BlockFlags::FORCE_STATE,
|
||||
)
|
||||
.await;
|
||||
context
|
||||
.world
|
||||
.set_block_state(
|
||||
&block_position,
|
||||
context.block_state_id,
|
||||
BlockFlags::FORCE_STATE,
|
||||
)
|
||||
.await;
|
||||
FillerResult::PlacedBlock
|
||||
}
|
||||
}
|
||||
|
||||
struct HollowFiller;
|
||||
impl Filler for HollowFiller {
|
||||
async fn execute_for_pos(context: &Context, block_position: BlockPos) -> FillerResult {
|
||||
if let Some(filter) = &context.option_filter
|
||||
&& not_in_filter(filter, context.world.get_block(&block_position))
|
||||
{
|
||||
return FillerResult::DidNotPlaceBlock;
|
||||
}
|
||||
if context.is_edge(block_position) {
|
||||
context
|
||||
.world
|
||||
.set_block_state(
|
||||
&block_position,
|
||||
context.block_state_id,
|
||||
BlockFlags::FORCE_STATE,
|
||||
)
|
||||
.await;
|
||||
} else {
|
||||
context
|
||||
.world
|
||||
.set_block_state(&block_position, BlockStateId::AIR, BlockFlags::FORCE_STATE)
|
||||
.await;
|
||||
}
|
||||
FillerResult::PlacedBlock
|
||||
}
|
||||
}
|
||||
|
||||
struct KeepFiller;
|
||||
impl Filler for KeepFiller {
|
||||
async fn execute_for_pos(context: &Context, block_position: BlockPos) -> FillerResult {
|
||||
let (old_block, old_state) = context.world.get_block_and_state(&block_position);
|
||||
if old_state.is_air() {
|
||||
if let Some(filter) = &context.option_filter
|
||||
&& not_in_filter(filter, old_block)
|
||||
{
|
||||
return FillerResult::DidNotPlaceBlock;
|
||||
}
|
||||
context
|
||||
.world
|
||||
.set_block_state(
|
||||
&block_position,
|
||||
context.block_state_id,
|
||||
BlockFlags::FORCE_STATE,
|
||||
)
|
||||
.await;
|
||||
FillerResult::PlacedBlock
|
||||
} else {
|
||||
FillerResult::DidNotPlaceBlock
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct OutlineFiller;
|
||||
impl Filler for OutlineFiller {
|
||||
async fn execute_for_pos(context: &Context, block_position: BlockPos) -> FillerResult {
|
||||
if !context.is_edge(block_position) {
|
||||
return FillerResult::DidNotPlaceBlock;
|
||||
}
|
||||
if let Some(filter) = &context.option_filter
|
||||
&& not_in_filter(filter, context.world.get_block(&block_position))
|
||||
{
|
||||
return FillerResult::DidNotPlaceBlock;
|
||||
}
|
||||
context
|
||||
.world
|
||||
.set_block_state(
|
||||
&block_position,
|
||||
context.block_state_id,
|
||||
BlockFlags::FORCE_STATE,
|
||||
)
|
||||
.await;
|
||||
FillerResult::PlacedBlock
|
||||
}
|
||||
}
|
||||
|
||||
struct ReplaceFiller;
|
||||
impl Filler for ReplaceFiller {
|
||||
async fn execute_for_pos(context: &Context, block_position: BlockPos) -> FillerResult {
|
||||
if let Some(filter) = &context.option_filter
|
||||
&& not_in_filter(filter, context.world.get_block(&block_position))
|
||||
{
|
||||
return FillerResult::DidNotPlaceBlock;
|
||||
}
|
||||
context
|
||||
.world
|
||||
.set_block_state(
|
||||
&block_position,
|
||||
context.block_state_id,
|
||||
BlockFlags::FORCE_STATE,
|
||||
)
|
||||
.await;
|
||||
FillerResult::PlacedBlock
|
||||
}
|
||||
}
|
||||
|
||||
struct StrictFiller;
|
||||
impl Filler for StrictFiller {
|
||||
async fn execute_for_pos(context: &Context, block_position: BlockPos) -> FillerResult {
|
||||
if let Some(filter) = &context.option_filter
|
||||
&& not_in_filter(filter, context.world.get_block(&block_position))
|
||||
{
|
||||
return FillerResult::DidNotPlaceBlock;
|
||||
}
|
||||
context
|
||||
.world
|
||||
.set_block_state(
|
||||
&block_position,
|
||||
context.block_state_id,
|
||||
BlockFlags::SKIP_BLOCK_ADDED_CALLBACK,
|
||||
)
|
||||
.await;
|
||||
FillerResult::PlacedBlockWithoutUpdate
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let block = BlockArgumentConsumer::find_arg(args, ARG_BLOCK)?;
|
||||
let block_state_id = block.default_state.id;
|
||||
let from = BlockPosArgumentConsumer::find_arg(args, ARG_FROM)?;
|
||||
let to = BlockPosArgumentConsumer::find_arg(args, ARG_TO)?;
|
||||
let mode = self.0;
|
||||
|
||||
let mut context = Context {
|
||||
block_state_id,
|
||||
option_filter: BlockPredicateArgumentConsumer::find_arg(args, ARG_FILTER)?,
|
||||
world: sender
|
||||
.world_or_first(server)
|
||||
.ok_or(CommandError::InvalidRequirement)?,
|
||||
placed_blocks: 0,
|
||||
to_update: Vec::new(),
|
||||
|
||||
start_x: from.0.x.min(to.0.x),
|
||||
start_y: from.0.y.min(to.0.y),
|
||||
start_z: from.0.z.min(to.0.z),
|
||||
|
||||
end_x: from.0.x.max(to.0.x),
|
||||
end_y: from.0.y.max(to.0.y),
|
||||
end_z: from.0.z.max(to.0.z),
|
||||
};
|
||||
|
||||
if !context.world.is_in_build_limit(from) || !context.world.is_in_build_limit(to) {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::ARGUMENT_POS_OUTOFBOUNDS,
|
||||
translation::java::ARGUMENT_POS_OUTOFBOUNDS,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
let max_block_modifications = {
|
||||
let level_info = server.level_info.load();
|
||||
level_info.game_rules.max_block_modifications
|
||||
};
|
||||
|
||||
let total_blocks = (context.end_x - context.start_x + 1) as i64
|
||||
* (context.end_y - context.start_y + 1) as i64
|
||||
* (context.end_z - context.start_z + 1) as i64;
|
||||
|
||||
if total_blocks > max_block_modifications {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FILL_TOOBIG,
|
||||
translation::java::COMMANDS_FILL_TOOBIG,
|
||||
[
|
||||
TextComponent::text(max_block_modifications.to_string()),
|
||||
TextComponent::text(total_blocks.to_string()),
|
||||
],
|
||||
)));
|
||||
}
|
||||
|
||||
match mode {
|
||||
Mode::Destroy => DestroyFiller::execute_for_region(&mut context).await,
|
||||
Mode::Replace => ReplaceFiller::execute_for_region(&mut context).await,
|
||||
Mode::Keep => KeepFiller::execute_for_region(&mut context).await,
|
||||
Mode::Hollow => HollowFiller::execute_for_region(&mut context).await,
|
||||
Mode::Outline => OutlineFiller::execute_for_region(&mut context).await,
|
||||
Mode::Strict => StrictFiller::execute_for_region(&mut context).await,
|
||||
}
|
||||
|
||||
for i in context.to_update {
|
||||
context.world.update_neighbors(&i, None).await;
|
||||
}
|
||||
|
||||
if context.placed_blocks == 0 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FILL_FAILED,
|
||||
translation::bedrock::COMMANDS_FILL_FAILED,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FILL_SUCCESS,
|
||||
translation::bedrock::COMMANDS_FILL_SUCCESS,
|
||||
[TextComponent::text(context.placed_blocks.to_string())],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(context.placed_blocks)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(ARG_FROM, BlockPosArgumentConsumer).then(
|
||||
argument(ARG_TO, BlockPosArgumentConsumer).then(
|
||||
argument(ARG_BLOCK, BlockArgumentConsumer)
|
||||
.then(literal("destroy").execute(Executor(Mode::Destroy)))
|
||||
.then(literal("hollow").execute(Executor(Mode::Hollow)))
|
||||
.then(literal("keep").execute(Executor(Mode::Keep)))
|
||||
.then(literal("outline").execute(Executor(Mode::Outline)))
|
||||
.then(
|
||||
literal("replace")
|
||||
.then(
|
||||
argument(ARG_FILTER, BlockPredicateArgumentConsumer)
|
||||
.then(literal("destroy").execute(Executor(Mode::Destroy)))
|
||||
.then(literal("hollow").execute(Executor(Mode::Hollow)))
|
||||
.then(literal("keep").execute(Executor(Mode::Keep)))
|
||||
.then(literal("outline").execute(Executor(Mode::Outline)))
|
||||
.then(literal("strict").execute(Executor(Mode::Strict)))
|
||||
.execute(Executor(Mode::Replace)),
|
||||
)
|
||||
.execute(Executor(Mode::Replace)),
|
||||
)
|
||||
.then(literal("strict").execute(Executor(Mode::Strict)))
|
||||
.execute(Executor(Mode::Replace)),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command};
|
||||
use crate::command::argument_types::coordinates::block_pos::{
|
||||
BlockPosArgumentType, OUT_OF_BOUNDS_ERROR_TYPE,
|
||||
};
|
||||
use crate::command::argument_types::resource_key::{BIOME_REGISTRY, ResourceKeyArgument};
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_protocol::java::client::play::CChunkData;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::collections::HashMap;
|
||||
|
||||
const DESCRIPTION: &str = "Changes biomes of an area.";
|
||||
const PERMISSION: &str = "minecraft:command.fillbiome";
|
||||
|
||||
const MAX_BIOME_BLOCKS: i64 = 32768;
|
||||
|
||||
static ERROR_TOOBIG: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_FILLBIOME_TOOBIG,
|
||||
translation::java::COMMANDS_FILLBIOME_TOOBIG,
|
||||
);
|
||||
|
||||
struct FillBiomeExecutor {
|
||||
has_replace: bool,
|
||||
}
|
||||
|
||||
impl CommandExecutor for FillBiomeExecutor {
|
||||
#[expect(clippy::too_many_lines)]
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let from_pos = BlockPosArgumentType::get_block_pos(context, "from")?;
|
||||
let to_pos = BlockPosArgumentType::get_block_pos(context, "to")?;
|
||||
|
||||
let world = context.world();
|
||||
if !world.is_in_build_limit(from_pos) || !world.is_in_build_limit(to_pos) {
|
||||
return Err(OUT_OF_BOUNDS_ERROR_TYPE.create_without_context());
|
||||
}
|
||||
|
||||
let min_x = from_pos.0.x.min(to_pos.0.x);
|
||||
let max_x = from_pos.0.x.max(to_pos.0.x);
|
||||
let min_y = from_pos.0.y.min(to_pos.0.y);
|
||||
let max_y = from_pos.0.y.max(to_pos.0.y);
|
||||
let min_z = from_pos.0.z.min(to_pos.0.z);
|
||||
let max_z = from_pos.0.z.max(to_pos.0.z);
|
||||
|
||||
let biome_min_x = min_x >> 2;
|
||||
let biome_max_x = max_x >> 2;
|
||||
let biome_min_y = min_y >> 2;
|
||||
let biome_max_y = max_y >> 2;
|
||||
let biome_min_z = min_z >> 2;
|
||||
let biome_max_z = max_z >> 2;
|
||||
|
||||
let volume = (biome_max_x - biome_min_x + 1) as i64
|
||||
* (biome_max_y - biome_min_y + 1) as i64
|
||||
* (biome_max_z - biome_min_z + 1) as i64;
|
||||
|
||||
if volume > MAX_BIOME_BLOCKS {
|
||||
return Err(ERROR_TOOBIG.create_without_context_args_slice(&[
|
||||
TextComponent::text(MAX_BIOME_BLOCKS.to_string()),
|
||||
TextComponent::text(volume.to_string()),
|
||||
]));
|
||||
}
|
||||
|
||||
let target_biome = ResourceKeyArgument::get_biome(context, "biome")?;
|
||||
|
||||
let replace_biome = if self.has_replace {
|
||||
Some(ResourceKeyArgument::get_biome(context, "replace_biome")?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let mut chunk_modifications: HashMap<Vector2<i32>, Vec<(usize, usize, usize)>> =
|
||||
HashMap::new();
|
||||
for y in biome_min_y..=biome_max_y {
|
||||
for z in biome_min_z..=biome_max_z {
|
||||
for x in biome_min_x..=biome_max_x {
|
||||
let chunk_pos = Vector2::new(x >> 2, z >> 2);
|
||||
let rel_x = (x & 3) as usize;
|
||||
let rel_z = (z & 3) as usize;
|
||||
let rel_y = (y - (world.min_y >> 2)) as usize;
|
||||
chunk_modifications
|
||||
.entry(chunk_pos)
|
||||
.or_default()
|
||||
.push((rel_x, rel_y, rel_z));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let target_biome_id = target_biome.id;
|
||||
let replace_biome_id = replace_biome.map(|b| b.id);
|
||||
let mut changed_count = 0;
|
||||
|
||||
for (chunk_pos, mods) in chunk_modifications {
|
||||
let (has_replaced, count) = world
|
||||
.level
|
||||
.get_or_fetch_chunk(chunk_pos, |chunk| {
|
||||
let mut local_count = 0;
|
||||
let mut modified = false;
|
||||
for &(rel_x, rel_y, rel_z) in &mods {
|
||||
let section_index = rel_y / 4;
|
||||
let scale_y = rel_y % 4;
|
||||
if let Some(current_id) =
|
||||
chunk
|
||||
.section
|
||||
.get_noise_biome(section_index, rel_x, scale_y, rel_z)
|
||||
{
|
||||
if let Some(replace_id) = replace_biome_id {
|
||||
if current_id == replace_id {
|
||||
chunk.section.set_relative_biome(
|
||||
rel_x,
|
||||
rel_y,
|
||||
rel_z,
|
||||
target_biome_id,
|
||||
);
|
||||
local_count += 1;
|
||||
modified = true;
|
||||
}
|
||||
} else {
|
||||
chunk.section.set_relative_biome(
|
||||
rel_x,
|
||||
rel_y,
|
||||
rel_z,
|
||||
target_biome_id,
|
||||
);
|
||||
local_count += 1;
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
(modified, local_count)
|
||||
})
|
||||
.await;
|
||||
|
||||
if has_replaced {
|
||||
changed_count += count;
|
||||
let chunk = world
|
||||
.level
|
||||
.get_or_fetch_chunk(chunk_pos, std::clone::Clone::clone)
|
||||
.await;
|
||||
world.broadcast_to_chunk_except(chunk_pos, &[], &CChunkData(&chunk));
|
||||
}
|
||||
}
|
||||
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FILLBIOME_SUCCESS_COUNT,
|
||||
translation::java::COMMANDS_FILLBIOME_SUCCESS_COUNT,
|
||||
[TextComponent::text(changed_count.to_string())],
|
||||
);
|
||||
context.source.send_feedback(msg, true).await;
|
||||
|
||||
Ok(changed_count)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
));
|
||||
|
||||
let builder = command("fillbiome", DESCRIPTION).requires(PERMISSION).then(
|
||||
argument("from", BlockPosArgumentType).then(
|
||||
argument("to", BlockPosArgumentType).then(
|
||||
argument("biome", ResourceKeyArgument(BIOME_REGISTRY.clone()))
|
||||
.executes(FillBiomeExecutor { has_replace: false })
|
||||
.then(
|
||||
argument("replace_biome", ResourceKeyArgument(BIOME_REGISTRY.clone()))
|
||||
.executes(FillBiomeExecutor { has_replace: true }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
dispatcher.register(builder);
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command, literal};
|
||||
use crate::command::argument_types::coordinates::Coordinates;
|
||||
use crate::command::argument_types::coordinates::column_pos::ColumnPosArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_util::text::color::{Color, NamedColor};
|
||||
|
||||
const DESCRIPTION: &str = "Constantly load chunks in the world.";
|
||||
const PERMISSION: &str = "minecraft:command.forceload";
|
||||
|
||||
static ERROR_FAILED_ADD: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_FAILURE,
|
||||
"No world in source",
|
||||
);
|
||||
static ERROR_FAILED_REMOVE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_FAILURE,
|
||||
"No world in source",
|
||||
);
|
||||
static ERROR_FAILED_QUERY: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_FORCELOAD_QUERY_FAILURE,
|
||||
"No world in source",
|
||||
);
|
||||
static ERROR_TOO_MANY: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_FORCELOAD_TOOBIG,
|
||||
"Too many chunks",
|
||||
);
|
||||
|
||||
struct ForceloadAddExecutor;
|
||||
|
||||
impl CommandExecutor for ForceloadAddExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let from_pos = ColumnPosArgumentType::get_column_pos(context, "from")?;
|
||||
|
||||
let to_pos = if context.get_argument::<Coordinates>("to").is_ok() {
|
||||
ColumnPosArgumentType::get_column_pos(context, "to")?
|
||||
} else {
|
||||
from_pos
|
||||
};
|
||||
|
||||
let world = context
|
||||
.source
|
||||
.world
|
||||
.as_ref()
|
||||
.ok_or_else(|| ERROR_FAILED_ADD.create_without_context())?;
|
||||
|
||||
let chunk_x_start = from_pos.0.x >> 4;
|
||||
let chunk_z_start = from_pos.0.y >> 4;
|
||||
|
||||
let chunk_x_end = to_pos.0.x >> 4;
|
||||
let chunk_z_end = to_pos.0.y >> 4;
|
||||
|
||||
let min_x = chunk_x_start.min(chunk_x_end);
|
||||
let max_x = chunk_x_start.max(chunk_x_end);
|
||||
let min_z = chunk_z_start.min(chunk_z_end);
|
||||
let max_z = chunk_z_start.max(chunk_z_end);
|
||||
|
||||
let count_x = max_x - min_x + 1;
|
||||
let count_z = max_z - min_z + 1;
|
||||
let total_chunks = count_x * count_z;
|
||||
|
||||
if total_chunks > 256 {
|
||||
return Err(ERROR_TOO_MANY.create_without_context(
|
||||
TextComponent::text("256"),
|
||||
TextComponent::text(total_chunks.to_string()),
|
||||
));
|
||||
}
|
||||
|
||||
{
|
||||
let mut forced = world.forced_chunks.lock().unwrap();
|
||||
for x in min_x..=max_x {
|
||||
for z in min_z..=max_z {
|
||||
forced.insert(Vector2::new(x, z));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
world.update_active_chunks();
|
||||
|
||||
let text = if total_chunks == 1 {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_SINGLE,
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_SINGLE,
|
||||
[
|
||||
TextComponent::text(min_x.to_string()),
|
||||
TextComponent::text(min_z.to_string()),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_MULTIPLE,
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_MULTIPLE,
|
||||
[
|
||||
TextComponent::text(total_chunks.to_string()),
|
||||
TextComponent::text(min_x.to_string()),
|
||||
TextComponent::text(min_z.to_string()),
|
||||
TextComponent::text(max_x.to_string()),
|
||||
TextComponent::text(max_z.to_string()),
|
||||
],
|
||||
)
|
||||
};
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Green)), false)
|
||||
.await;
|
||||
|
||||
Ok(total_chunks)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ForceloadRemoveExecutor;
|
||||
|
||||
impl CommandExecutor for ForceloadRemoveExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let from_pos = ColumnPosArgumentType::get_column_pos(context, "from")?;
|
||||
|
||||
let to_pos = if context.get_argument::<Coordinates>("to").is_ok() {
|
||||
ColumnPosArgumentType::get_column_pos(context, "to")?
|
||||
} else {
|
||||
from_pos
|
||||
};
|
||||
|
||||
let world = context
|
||||
.source
|
||||
.world
|
||||
.as_ref()
|
||||
.ok_or_else(|| ERROR_FAILED_REMOVE.create_without_context())?;
|
||||
|
||||
let chunk_x_start = from_pos.0.x >> 4;
|
||||
let chunk_z_start = from_pos.0.y >> 4;
|
||||
|
||||
let chunk_x_end = to_pos.0.x >> 4;
|
||||
let chunk_z_end = to_pos.0.y >> 4;
|
||||
|
||||
let min_x = chunk_x_start.min(chunk_x_end);
|
||||
let max_x = chunk_x_start.max(chunk_x_end);
|
||||
let min_z = chunk_z_start.min(chunk_z_end);
|
||||
let max_z = chunk_z_start.max(chunk_z_end);
|
||||
|
||||
let count_x = max_x - min_x + 1;
|
||||
let count_z = max_z - min_z + 1;
|
||||
let total_chunks = count_x * count_z;
|
||||
|
||||
if total_chunks > 256 {
|
||||
return Err(ERROR_TOO_MANY.create_without_context(
|
||||
TextComponent::text("256"),
|
||||
TextComponent::text(total_chunks.to_string()),
|
||||
));
|
||||
}
|
||||
|
||||
{
|
||||
let mut forced = world.forced_chunks.lock().unwrap();
|
||||
for x in min_x..=max_x {
|
||||
for z in min_z..=max_z {
|
||||
forced.remove(&Vector2::new(x, z));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
world.update_active_chunks();
|
||||
|
||||
let text = if total_chunks == 1 {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_SINGLE,
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_SINGLE,
|
||||
[
|
||||
TextComponent::text(min_x.to_string()),
|
||||
TextComponent::text(min_z.to_string()),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_MULTIPLE,
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_MULTIPLE,
|
||||
[
|
||||
TextComponent::text(total_chunks.to_string()),
|
||||
TextComponent::text(min_x.to_string()),
|
||||
TextComponent::text(min_z.to_string()),
|
||||
TextComponent::text(max_x.to_string()),
|
||||
TextComponent::text(max_z.to_string()),
|
||||
],
|
||||
)
|
||||
};
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Green)), false)
|
||||
.await;
|
||||
|
||||
Ok(total_chunks)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ForceloadRemoveAllExecutor;
|
||||
|
||||
impl CommandExecutor for ForceloadRemoveAllExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let world = context
|
||||
.source
|
||||
.world
|
||||
.as_ref()
|
||||
.ok_or_else(|| ERROR_FAILED_REMOVE.create_without_context())?;
|
||||
|
||||
let removed_count = {
|
||||
let mut forced = world.forced_chunks.lock().unwrap();
|
||||
let count = forced.len();
|
||||
forced.clear();
|
||||
count
|
||||
};
|
||||
|
||||
world.update_active_chunks();
|
||||
|
||||
let text = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_ALL,
|
||||
translation::java::COMMANDS_FORCELOAD_REMOVED_ALL,
|
||||
[],
|
||||
);
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Green)), false)
|
||||
.await;
|
||||
|
||||
Ok(removed_count as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ForceloadQueryExecutor;
|
||||
|
||||
impl CommandExecutor for ForceloadQueryExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let world = context
|
||||
.source
|
||||
.world
|
||||
.as_ref()
|
||||
.ok_or_else(|| ERROR_FAILED_QUERY.create_without_context())?;
|
||||
|
||||
let chunk_pos = if context.get_argument::<Coordinates>("pos").is_ok() {
|
||||
let pos = ColumnPosArgumentType::get_column_pos(context, "pos")?;
|
||||
Vector2::new(pos.0.x >> 4, pos.0.y >> 4)
|
||||
} else {
|
||||
let block_x = context.source.position.x.floor() as i32;
|
||||
let block_z = context.source.position.z.floor() as i32;
|
||||
Vector2::new(block_x >> 4, block_z >> 4)
|
||||
};
|
||||
|
||||
let is_forced = {
|
||||
let forced = world.forced_chunks.lock().unwrap();
|
||||
forced.contains(&chunk_pos)
|
||||
};
|
||||
|
||||
if is_forced {
|
||||
let text = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_QUERY_SUCCESS,
|
||||
translation::java::COMMANDS_FORCELOAD_QUERY_SUCCESS,
|
||||
[
|
||||
TextComponent::text(chunk_pos.x.to_string()),
|
||||
TextComponent::text(chunk_pos.y.to_string()),
|
||||
],
|
||||
);
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Green)), false)
|
||||
.await;
|
||||
} else {
|
||||
let text = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_QUERY_FAILURE,
|
||||
translation::java::COMMANDS_FORCELOAD_QUERY_FAILURE,
|
||||
[
|
||||
TextComponent::text(chunk_pos.x.to_string()),
|
||||
TextComponent::text(chunk_pos.y.to_string()),
|
||||
],
|
||||
);
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Red)), false)
|
||||
.await;
|
||||
}
|
||||
|
||||
let all_forced = {
|
||||
let forced = world.forced_chunks.lock().unwrap();
|
||||
forced
|
||||
.iter()
|
||||
.map(|pos| format!("[{}, {}]", pos.x, pos.y))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
if all_forced.is_empty() {
|
||||
let text = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_NONE,
|
||||
translation::java::COMMANDS_FORCELOAD_ADDED_NONE,
|
||||
[],
|
||||
);
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Gray)), false)
|
||||
.await;
|
||||
} else {
|
||||
let list_str = all_forced.join(", ");
|
||||
let text = if all_forced.len() == 1 {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_LIST_SINGLE,
|
||||
translation::java::COMMANDS_FORCELOAD_LIST_SINGLE,
|
||||
[TextComponent::text(list_str)],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_FORCELOAD_LIST_MULTIPLE,
|
||||
translation::java::COMMANDS_FORCELOAD_LIST_MULTIPLE,
|
||||
[TextComponent::text(list_str)],
|
||||
)
|
||||
};
|
||||
context
|
||||
.source
|
||||
.send_feedback(text.color(Color::Named(NamedColor::Gray)), false)
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(i32::from(is_forced))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
));
|
||||
|
||||
let builder = command("forceload", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.then(
|
||||
literal("add").then(
|
||||
argument("from", ColumnPosArgumentType)
|
||||
.executes(ForceloadAddExecutor)
|
||||
.then(argument("to", ColumnPosArgumentType).executes(ForceloadAddExecutor)),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("remove")
|
||||
.then(literal("all").executes(ForceloadRemoveAllExecutor))
|
||||
.then(
|
||||
argument("from", ColumnPosArgumentType)
|
||||
.executes(ForceloadRemoveExecutor)
|
||||
.then(
|
||||
argument("to", ColumnPosArgumentType).executes(ForceloadRemoveExecutor),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("query")
|
||||
.executes(ForceloadQueryExecutor)
|
||||
.then(argument("pos", ColumnPosArgumentType).executes(ForceloadQueryExecutor)),
|
||||
);
|
||||
|
||||
dispatcher.register(builder);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
use crate::command::args::GetCloned;
|
||||
use crate::command::args::gamemode::GamemodeArgumentConsumer;
|
||||
|
||||
use crate::TextComponent;
|
||||
use pumpkin_data::translation;
|
||||
|
||||
use crate::command::args::players::PlayersArgumentConsumer;
|
||||
|
||||
use crate::command::args::{Arg, ConsumedArgs};
|
||||
use crate::command::dispatcher::CommandError::{InvalidConsumption, InvalidRequirement};
|
||||
use crate::command::tree::CommandTree;
|
||||
use crate::command::tree::builder::{argument, require};
|
||||
use crate::command::{CommandExecutor, CommandResult, CommandSender};
|
||||
use crate::entity::EntityBase;
|
||||
|
||||
const NAMES: [&str; 1] = ["gamemode"];
|
||||
|
||||
const DESCRIPTION: &str = "Change a player's gamemode.";
|
||||
|
||||
const ARG_GAMEMODE: &str = "gamemode";
|
||||
const ARG_TARGET: &str = "target";
|
||||
|
||||
struct TargetExecutor {
|
||||
is_self: bool,
|
||||
}
|
||||
|
||||
impl CommandExecutor for TargetExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::GameMode(gamemode)) = args.get_cloned(&ARG_GAMEMODE) else {
|
||||
return Err(InvalidConsumption(Some(ARG_GAMEMODE.into())));
|
||||
};
|
||||
|
||||
let targets = if self.is_self {
|
||||
let Some(player) = sender.as_player() else {
|
||||
return Err(InvalidRequirement);
|
||||
};
|
||||
&[player]
|
||||
} else {
|
||||
let Some(Arg::Players(targets)) = args.get(ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
targets.as_slice()
|
||||
};
|
||||
|
||||
let mut succeeded: i32 = 0;
|
||||
for target in targets {
|
||||
if target.set_gamemode(gamemode).await {
|
||||
succeeded += 1;
|
||||
let gamemode_string = format!("{gamemode:?}").to_lowercase();
|
||||
let gamemode_string = format!("gameMode.{gamemode_string}");
|
||||
// Checking if the target was the sender of this command.
|
||||
let gamemode_comp = TextComponent::translate_cross(
|
||||
gamemode_string.clone(),
|
||||
gamemode_string.clone(),
|
||||
[],
|
||||
);
|
||||
if sender.as_player().as_ref() == Some(target) {
|
||||
target
|
||||
.send_system_message(&TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_GAMEMODE_SUCCESS_SELF,
|
||||
translation::bedrock::COMMANDS_GAMEMODE_SUCCESS_SELF,
|
||||
[gamemode_comp],
|
||||
))
|
||||
.await;
|
||||
} else {
|
||||
if server.level_info.load().game_rules.send_command_feedback {
|
||||
target
|
||||
.send_system_message(&TextComponent::translate_cross(
|
||||
translation::java::GAMEMODE_CHANGED,
|
||||
translation::bedrock::GAMEMODE_CHANGED,
|
||||
[gamemode_comp.clone()],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_GAMEMODE_SUCCESS_OTHER,
|
||||
translation::bedrock::COMMANDS_GAMEMODE_SUCCESS_OTHER,
|
||||
[target.get_display_name().await, gamemode_comp],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(succeeded)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::redundant_closure_for_method_calls)]
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(ARG_GAMEMODE, GamemodeArgumentConsumer)
|
||||
.then(require(|sender| sender.is_player()).execute(TargetExecutor { is_self: true }))
|
||||
.then(
|
||||
argument(ARG_TARGET, PlayersArgumentConsumer)
|
||||
.execute(TargetExecutor { is_self: false }),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
use pumpkin_data::game_rules::{GameRule, GameRuleRegistry, GameRuleValue};
|
||||
|
||||
use crate::command::args::FindArg;
|
||||
use crate::command::args::bool::BoolArgConsumer;
|
||||
use crate::command::args::bounded_num::BoundedNumArgumentConsumer;
|
||||
|
||||
use crate::TextComponent;
|
||||
|
||||
use crate::command::args::ConsumedArgs;
|
||||
use crate::command::tree::CommandTree;
|
||||
use crate::command::tree::builder::{argument, literal};
|
||||
use crate::command::{CommandExecutor, CommandResult, CommandSender};
|
||||
|
||||
const NAMES: [&str; 1] = ["gamerule"];
|
||||
|
||||
const DESCRIPTION: &str = "Sets or queries a game rule value.";
|
||||
|
||||
const ARG_NAME: &str = "value";
|
||||
|
||||
struct QueryExecutor(GameRule);
|
||||
|
||||
impl CommandExecutor for QueryExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let key = TextComponent::text(self.0.to_string());
|
||||
let level_info = server.level_info.load();
|
||||
let game_rule = level_info.game_rules.get(&self.0);
|
||||
let game_rule_i32_value = match game_rule {
|
||||
GameRuleValue::Int(value) => {
|
||||
(*value).clamp(i32::MIN as i64, i32::MAX as i64) as i32
|
||||
}
|
||||
GameRuleValue::Bool(value) => *value as i32,
|
||||
};
|
||||
let value = TextComponent::text(game_rule.to_string());
|
||||
drop(level_info);
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.gamerule.query",
|
||||
"commands.gamerule.query",
|
||||
[key, value],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(game_rule_i32_value)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct SetExecutor(GameRule);
|
||||
|
||||
impl CommandExecutor for SetExecutor {
|
||||
#[expect(unused)]
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let key = TextComponent::text(self.0.to_string());
|
||||
let current_info = server.level_info.load();
|
||||
|
||||
let mut new_info = (**current_info).clone();
|
||||
|
||||
let mut output_value = String::new();
|
||||
let mut result_i32: i32;
|
||||
|
||||
let raw_value = new_info.game_rules.get_mut(&self.0);
|
||||
|
||||
match raw_value {
|
||||
GameRuleValue::Int(value) => {
|
||||
let arg_value = BoundedNumArgumentConsumer::<i64>::find_arg(args, ARG_NAME)??;
|
||||
*value = arg_value;
|
||||
output_value = arg_value.to_string();
|
||||
// TODO: Should integer gamerule values be kept as a `i64` or should it be changed to an `i32`?
|
||||
// For now, we can cast it
|
||||
result_i32 = arg_value.clamp(i32::MIN as i64, i32::MAX as i64) as i32;
|
||||
}
|
||||
GameRuleValue::Bool(value) => {
|
||||
let arg_value = BoolArgConsumer::find_arg(args, ARG_NAME)?;
|
||||
*value = arg_value;
|
||||
output_value = arg_value.to_string();
|
||||
result_i32 = *value as i32;
|
||||
}
|
||||
}
|
||||
|
||||
server.level_info.store(std::sync::Arc::new(new_info));
|
||||
|
||||
let value_component = TextComponent::text(output_value);
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.gamerule.set",
|
||||
"commands.gamerule.set",
|
||||
[key, value_component],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(result_i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
let mut command_tree = CommandTree::new(NAMES, DESCRIPTION);
|
||||
let rule_registry = GameRuleRegistry::default();
|
||||
for rule in GameRule::all() {
|
||||
let arg = match rule_registry.get(rule) {
|
||||
GameRuleValue::Int(_) => argument(ARG_NAME, BoundedNumArgumentConsumer::<i64>::new()),
|
||||
GameRuleValue::Bool(_) => argument(ARG_NAME, BoolArgConsumer),
|
||||
};
|
||||
command_tree = command_tree.then(
|
||||
literal(rule.to_string())
|
||||
.execute(QueryExecutor(rule.clone()))
|
||||
.then(arg.execute(SetExecutor(rule.clone()))),
|
||||
);
|
||||
}
|
||||
command_tree
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
use pumpkin_data::data_component::DataComponent::MaxStackSize;
|
||||
use pumpkin_data::data_component_impl::{MaxStackSizeImpl, get};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_util::text::hover::HoverEvent;
|
||||
|
||||
use crate::command::args::bounded_num::BoundedNumArgumentConsumer;
|
||||
use crate::command::args::players::PlayersArgumentConsumer;
|
||||
use crate::command::args::resource::item::ItemArgumentConsumer;
|
||||
use crate::command::args::{ConsumedArgs, FindArg, FindArgDefaultName};
|
||||
use crate::command::tree::CommandTree;
|
||||
use crate::command::tree::builder::{argument, argument_default_name};
|
||||
use crate::command::{CommandExecutor, CommandResult, CommandSender};
|
||||
use crate::entity::EntityBase;
|
||||
|
||||
const NAMES: [&str; 1] = ["give"];
|
||||
|
||||
const DESCRIPTION: &str = "Give items to player(s).";
|
||||
|
||||
const ARG_ITEM: &str = "item";
|
||||
|
||||
const fn item_count_consumer() -> BoundedNumArgumentConsumer<i32> {
|
||||
BoundedNumArgumentConsumer::new()
|
||||
.name("count")
|
||||
.min(1)
|
||||
.max(i32::MAX)
|
||||
}
|
||||
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = PlayersArgumentConsumer.find_arg_default_name(args)?;
|
||||
|
||||
let (item_name, parsed_stack) = ItemArgumentConsumer::find_arg(args, ARG_ITEM)?;
|
||||
let item = parsed_stack.item;
|
||||
|
||||
let item_count = match item_count_consumer().find_arg_default_name(args) {
|
||||
Err(_) => 1,
|
||||
Ok(Ok(count)) => count,
|
||||
Ok(Err(err)) => return Err(err.into()),
|
||||
};
|
||||
|
||||
for target in targets {
|
||||
let max_stack = i32::from(
|
||||
item.components
|
||||
.iter()
|
||||
.find_map(|(id, component)| {
|
||||
(id == &MaxStackSize).then(|| get::<MaxStackSizeImpl>(*component).size)
|
||||
})
|
||||
.expect("Item should have MaxStackSize component"),
|
||||
);
|
||||
let mut remaining = item_count;
|
||||
|
||||
while remaining > 0 {
|
||||
let take = remaining.min(max_stack);
|
||||
let mut stack = parsed_stack.clone();
|
||||
stack.item_count = take as u8;
|
||||
target.inventory().insert_stack_anywhere(&mut stack).await;
|
||||
if !stack.is_empty() {
|
||||
target.drop_item(stack).await;
|
||||
}
|
||||
remaining -= take;
|
||||
}
|
||||
}
|
||||
|
||||
let msg = if targets.len() == 1 {
|
||||
TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_GIVE_SUCCESS_SINGLE,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_GIVE_SUCCESS,
|
||||
[
|
||||
TextComponent::text(item_count.to_string()),
|
||||
TextComponent::text("[")
|
||||
.add_child(item.translated_name())
|
||||
.add_child(TextComponent::text("]"))
|
||||
.hover_event(HoverEvent::ShowItem {
|
||||
id: item_name.to_string().into(),
|
||||
count: Some(item_count.min(99)),
|
||||
}),
|
||||
targets[0].get_display_name().await,
|
||||
],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_GIVE_SUCCESS_MULTIPLE,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_GIVE_SUCCESS,
|
||||
[
|
||||
TextComponent::text(item_count.to_string()),
|
||||
TextComponent::text("[")
|
||||
.add_child(item.translated_name())
|
||||
.add_child(TextComponent::text("]"))
|
||||
.hover_event(HoverEvent::ShowItem {
|
||||
id: item_name.to_string().into(),
|
||||
count: Some(item_count.min(99)),
|
||||
}),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
)
|
||||
};
|
||||
sender.send_message(msg).await;
|
||||
|
||||
Ok(targets.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument_default_name(PlayersArgumentConsumer).then(
|
||||
argument(ARG_ITEM, ItemArgumentConsumer)
|
||||
.execute(Executor)
|
||||
.then(argument_default_name(item_count_consumer()).execute(Executor)),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command};
|
||||
use crate::command::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::command::argument_types::core::string::StringArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::command::errors::error_types::{
|
||||
CommandErrorType, INTEGER_TOO_HIGH, INTEGER_TOO_LOW, LiteralCommandErrorType,
|
||||
};
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use crate::command::string_reader::StringReader;
|
||||
use pumpkin_protocol::java::client::play::StringProtoArgBehavior;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_util::text::click::ClickEvent;
|
||||
use pumpkin_util::text::color::{Color, NamedColor};
|
||||
|
||||
const NO_COMMANDS_ERROR_TYPE: LiteralCommandErrorType =
|
||||
LiteralCommandErrorType::new("No commands are available to show help for");
|
||||
const FAILED_ERROR_TYPE: CommandErrorType<0> =
|
||||
CommandErrorType::new("commands.help.failed", "commands.help.failed");
|
||||
const PLUGIN_NOT_FOUND_ERROR_TYPE: LiteralCommandErrorType =
|
||||
LiteralCommandErrorType::new("Plugin not found or has no commands");
|
||||
|
||||
const DESCRIPTION: &str = "Print a help message.";
|
||||
const PERMISSION: &str = "minecraft:command.help";
|
||||
|
||||
const ARG: &str = "commandOrPage";
|
||||
|
||||
const COMMANDS_PER_PAGE: usize = 7;
|
||||
|
||||
enum HelpArgument {
|
||||
CommandOrPlugin(String),
|
||||
Page(usize),
|
||||
}
|
||||
|
||||
struct HelpArgumentType;
|
||||
impl ArgumentType for HelpArgumentType {
|
||||
type Item = HelpArgument;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let reader_start = reader.cursor();
|
||||
|
||||
match reader.read_int() {
|
||||
Ok(integer) => {
|
||||
if integer < 1 {
|
||||
reader.set_cursor(reader_start);
|
||||
Err(INTEGER_TOO_LOW.create(
|
||||
reader,
|
||||
TextComponent::text("1"),
|
||||
TextComponent::text(integer.to_string()),
|
||||
))
|
||||
} else if let Ok(a) = integer.try_into() {
|
||||
Ok(HelpArgument::Page(a))
|
||||
} else {
|
||||
reader.set_cursor(reader_start);
|
||||
Err(INTEGER_TOO_HIGH.create(
|
||||
reader,
|
||||
TextComponent::text(usize::MAX.to_string()),
|
||||
TextComponent::text(integer.to_string()),
|
||||
))
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
// Hacky way to greedily parse the remaining text.
|
||||
// This can never fail.
|
||||
//
|
||||
// We use greedy phrases for now
|
||||
// as the `?` command as the argument
|
||||
// doesn't work for the unquoted word one.
|
||||
let mut text = StringArgumentType::GreedyPhrase.parse(reader)?;
|
||||
|
||||
{
|
||||
let mut integer_text = text.as_str();
|
||||
if let Some(magnitude) = integer_text.strip_prefix("-") {
|
||||
integer_text = magnitude;
|
||||
}
|
||||
if !integer_text.is_empty() && integer_text.chars().all(|c| c.is_ascii_digit())
|
||||
{
|
||||
// The number was too large/small to be parsed into an i32.
|
||||
// Instead of parsing it as a command,
|
||||
// we act like we parsed it like an integer.
|
||||
reader.set_cursor(reader_start);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
|
||||
if text.starts_with('/') {
|
||||
text.remove(0);
|
||||
}
|
||||
|
||||
Ok(HelpArgument::CommandOrPlugin(text))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::String(StringProtoArgBehavior::GreedyPhrase)
|
||||
}
|
||||
}
|
||||
|
||||
impl HelpCommandExecutor {
|
||||
fn create_help_command_with_given_page_number(
|
||||
page_number: usize,
|
||||
arrow: &'static str,
|
||||
) -> TextComponent {
|
||||
let cmd = format!("/help {page_number}");
|
||||
TextComponent::text(arrow)
|
||||
.color(Color::Named(NamedColor::Aqua))
|
||||
.click_event(ClickEvent::RunCommand {
|
||||
command: cmd.into(),
|
||||
})
|
||||
}
|
||||
|
||||
fn page<'a>(context: &'a CommandContext, page_number: usize) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let server = context.server();
|
||||
|
||||
let dispatcher = server.command_dispatcher.read().await;
|
||||
let commands = dispatcher
|
||||
.get_all_permitted_commands_usage(&context.source)
|
||||
.await;
|
||||
|
||||
let commands_available = commands.len();
|
||||
if commands_available == 0 {
|
||||
return Err(NO_COMMANDS_ERROR_TYPE.create_without_context());
|
||||
}
|
||||
|
||||
let total_pages = commands_available.div_ceil(COMMANDS_PER_PAGE);
|
||||
let page = page_number.min(total_pages);
|
||||
|
||||
let start = (page - 1) * COMMANDS_PER_PAGE;
|
||||
let end = (start + COMMANDS_PER_PAGE).min(commands_available);
|
||||
|
||||
let page_commands = commands.into_iter().skip(start).take(end - start);
|
||||
|
||||
let arrow_left = if page > 1 {
|
||||
Self::create_help_command_with_given_page_number(page - 1, "<<<")
|
||||
} else {
|
||||
TextComponent::text("<<<").color(Color::Named(NamedColor::Gray))
|
||||
};
|
||||
|
||||
let arrow_right = if page < total_pages {
|
||||
Self::create_help_command_with_given_page_number(page + 1, ">>>")
|
||||
} else {
|
||||
TextComponent::text(">>>").color(Color::Named(NamedColor::Gray))
|
||||
};
|
||||
|
||||
let header_text = format!(" Help - Page {page}/{total_pages} ");
|
||||
|
||||
let dashes = 52usize.saturating_sub(header_text.len() + 3) / 2;
|
||||
|
||||
let mut message = TextComponent::empty()
|
||||
.add_child(
|
||||
TextComponent::text("-".repeat(dashes) + " ").color_named(NamedColor::Yellow),
|
||||
)
|
||||
.add_child(arrow_left.clone())
|
||||
.add_child(TextComponent::text(header_text.clone()))
|
||||
.add_child(arrow_right.clone())
|
||||
.add_child(
|
||||
TextComponent::text(" ".to_owned() + &"-".repeat(dashes) + "\n")
|
||||
.color_named(NamedColor::Yellow),
|
||||
);
|
||||
|
||||
for (command, (description, usage)) in page_commands {
|
||||
let command_declaration = format!("/{command}");
|
||||
message = message.add_child(
|
||||
TextComponent::text(command_declaration.clone())
|
||||
.color_named(NamedColor::Gold)
|
||||
.add_child(TextComponent::text(" - ").color_named(NamedColor::Yellow))
|
||||
.add_child(
|
||||
TextComponent::text(description.to_owned() + "\n")
|
||||
.color_named(NamedColor::White),
|
||||
)
|
||||
.add_child(
|
||||
TextComponent::text(" Usage: ").color_named(NamedColor::Yellow),
|
||||
)
|
||||
.add_child(
|
||||
TextComponent::text(usage.into_string()).color_named(NamedColor::White),
|
||||
)
|
||||
.add_child(TextComponent::text("\n").color_named(NamedColor::White))
|
||||
.click_event(ClickEvent::SuggestCommand {
|
||||
command: command_declaration.into(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
let footer_text = format!(" Page {page}/{total_pages} ");
|
||||
message = message
|
||||
.add_child(
|
||||
TextComponent::text("-".repeat(dashes) + " ").color_named(NamedColor::Yellow),
|
||||
)
|
||||
.add_child(arrow_left)
|
||||
.add_child(TextComponent::text(footer_text.clone()))
|
||||
.add_child(arrow_right)
|
||||
.add_child(
|
||||
TextComponent::text(" ".to_owned() + &"-".repeat(dashes))
|
||||
.color_named(NamedColor::Yellow),
|
||||
);
|
||||
|
||||
context.source.send_message(message).await;
|
||||
|
||||
Ok(commands_available as i32)
|
||||
})
|
||||
}
|
||||
|
||||
fn command<'a>(context: &'a CommandContext, command: &'a str) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let dispatcher = context.server().command_dispatcher.read().await;
|
||||
|
||||
let Some((description, usage)) = dispatcher
|
||||
.get_permitted_command_usage(&context.source, command)
|
||||
.await
|
||||
else {
|
||||
return Err(FAILED_ERROR_TYPE.create_without_context());
|
||||
};
|
||||
|
||||
let command_with_slash = format!("/{command}");
|
||||
let header_text = format!(" Help - /{command} ");
|
||||
|
||||
let dashes = 52usize.saturating_sub(header_text.len()) / 2;
|
||||
|
||||
let mut message = TextComponent::empty()
|
||||
.add_child(
|
||||
TextComponent::text("-".repeat(dashes) + " ").color_named(NamedColor::Yellow),
|
||||
)
|
||||
.add_child(TextComponent::text(header_text.clone()))
|
||||
.add_child(
|
||||
TextComponent::text(" ".to_owned() + &"-".repeat(dashes) + "\n")
|
||||
.color_named(NamedColor::Yellow),
|
||||
)
|
||||
.add_child(
|
||||
TextComponent::text("Command: ")
|
||||
.color_named(NamedColor::Aqua)
|
||||
.add_child(
|
||||
TextComponent::text(command_with_slash.clone())
|
||||
.color_named(NamedColor::Gold)
|
||||
.bold(),
|
||||
)
|
||||
.add_child(TextComponent::text("\n").color_named(NamedColor::White))
|
||||
.click_event(ClickEvent::SuggestCommand {
|
||||
command: command_with_slash.clone().into(),
|
||||
}),
|
||||
)
|
||||
.add_child(
|
||||
TextComponent::text("Description: ")
|
||||
.color_named(NamedColor::Aqua)
|
||||
.add_child(
|
||||
TextComponent::text(format!("{description}\n"))
|
||||
.color_named(NamedColor::White),
|
||||
),
|
||||
)
|
||||
.add_child(
|
||||
TextComponent::text("Usage: ")
|
||||
.color_named(NamedColor::Aqua)
|
||||
.add_child(
|
||||
TextComponent::text(format!("{usage}\n"))
|
||||
.color_named(NamedColor::White),
|
||||
)
|
||||
.click_event(ClickEvent::SuggestCommand {
|
||||
command: command_with_slash.into(),
|
||||
}),
|
||||
);
|
||||
|
||||
message = message
|
||||
.add_child(TextComponent::text("-".repeat(52)).color_named(NamedColor::Yellow));
|
||||
|
||||
context.source.send_message(message).await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
|
||||
fn plugin<'a>(context: &'a CommandContext, plugin_name: &'a str) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let server = context.server();
|
||||
let dispatcher = server.command_dispatcher.read().await;
|
||||
let commands = dispatcher
|
||||
.get_all_permitted_commands_usage_by_plugin(&context.source, plugin_name)
|
||||
.await;
|
||||
|
||||
if commands.is_empty() {
|
||||
return Err(PLUGIN_NOT_FOUND_ERROR_TYPE.create_without_context());
|
||||
}
|
||||
|
||||
let header_text = format!(" Help - Plugin: {plugin_name} ");
|
||||
let dashes = 52usize.saturating_sub(header_text.len() + 3) / 2;
|
||||
|
||||
let mut message = TextComponent::empty()
|
||||
.add_child(
|
||||
TextComponent::text("-".repeat(dashes) + " ").color_named(NamedColor::Yellow),
|
||||
)
|
||||
.add_child(TextComponent::text(header_text.clone()))
|
||||
.add_child(
|
||||
TextComponent::text(" ".to_owned() + &"-".repeat(dashes) + "\n")
|
||||
.color_named(NamedColor::Yellow),
|
||||
);
|
||||
|
||||
let commands_len = commands.len();
|
||||
for (command, (description, usage)) in commands {
|
||||
let command_declaration = format!("/{command}");
|
||||
message = message.add_child(
|
||||
TextComponent::text(command_declaration.clone())
|
||||
.color_named(NamedColor::Gold)
|
||||
.add_child(TextComponent::text(" - ").color_named(NamedColor::Yellow))
|
||||
.add_child(
|
||||
TextComponent::text(description.to_owned() + "\n")
|
||||
.color_named(NamedColor::White),
|
||||
)
|
||||
.add_child(
|
||||
TextComponent::text(" Usage: ").color_named(NamedColor::Yellow),
|
||||
)
|
||||
.add_child(
|
||||
TextComponent::text(usage.into_string()).color_named(NamedColor::White),
|
||||
)
|
||||
.add_child(TextComponent::text("\n").color_named(NamedColor::White))
|
||||
.click_event(ClickEvent::SuggestCommand {
|
||||
command: command_declaration.into(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
message = message
|
||||
.add_child(TextComponent::text("-".repeat(52)).color_named(NamedColor::Yellow));
|
||||
|
||||
context.source.send_message(message).await;
|
||||
Ok(commands_len as i32)
|
||||
})
|
||||
}
|
||||
|
||||
fn command_or_plugin<'a>(
|
||||
context: &'a CommandContext,
|
||||
input: &'a str,
|
||||
) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
// Prioritize commands ig
|
||||
{
|
||||
let dispatcher = context.server().command_dispatcher.read().await;
|
||||
if dispatcher
|
||||
.get_permitted_command_usage(&context.source, input)
|
||||
.await
|
||||
.is_some()
|
||||
{
|
||||
return Self::command(context, input).await;
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
let dispatcher = context.server().command_dispatcher.read().await;
|
||||
let plugin_commands = dispatcher
|
||||
.get_all_permitted_commands_usage_by_plugin(&context.source, input)
|
||||
.await;
|
||||
|
||||
if !plugin_commands.is_empty() {
|
||||
return Self::plugin(context, input).await;
|
||||
}
|
||||
}
|
||||
|
||||
Err(FAILED_ERROR_TYPE.create_without_context())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct HelpCommandExecutor;
|
||||
impl CommandExecutor for HelpCommandExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
let arg = context.get_argument(ARG).unwrap_or(&HelpArgument::Page(1));
|
||||
|
||||
match arg {
|
||||
HelpArgument::CommandOrPlugin(input) => Self::command_or_plugin(context, input),
|
||||
HelpArgument::Page(page_number) => Self::page(context, *page_number),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Allow,
|
||||
));
|
||||
|
||||
dispatcher.register_with_aliases(
|
||||
command("help", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.then(argument(ARG, HelpArgumentType).executes(HelpCommandExecutor))
|
||||
.executes(HelpCommandExecutor),
|
||||
&["h", "?"],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
use pumpkin_data::data_component_impl::EquipmentSlot;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_inventory::screen_handler::InventoryPlayer;
|
||||
use pumpkin_protocol::codec::item_stack_seralizer::ItemStackSerializer;
|
||||
use pumpkin_protocol::java::client::play::CSetContainerSlot;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_util::text::hover::HoverEvent;
|
||||
use pumpkin_world::inventory::Inventory;
|
||||
|
||||
use crate::command::args::bounded_num::BoundedNumArgumentConsumer;
|
||||
use crate::command::args::entities::EntitiesArgumentConsumer;
|
||||
use crate::command::args::position_block::BlockPosArgumentConsumer;
|
||||
use crate::command::args::resource::item::ItemArgumentConsumer;
|
||||
use crate::command::args::slot::SlotArgumentConsumer;
|
||||
use crate::command::args::{ConsumedArgs, FindArg, FindArgDefaultName};
|
||||
use crate::command::dispatcher::CommandError;
|
||||
use crate::command::tree::CommandTree;
|
||||
use crate::command::tree::builder::{argument, argument_default_name, literal};
|
||||
use crate::command::{CommandExecutor, CommandResult, CommandSender};
|
||||
|
||||
const NAMES: [&str; 1] = ["item"];
|
||||
const DESCRIPTION: &str = "Modifies items in block or entity inventories.";
|
||||
|
||||
const ARG_POS: &str = "pos";
|
||||
const ARG_SLOT: &str = "slot";
|
||||
const ARG_ITEM: &str = "item";
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
|
||||
const fn count_consumer() -> BoundedNumArgumentConsumer<i32> {
|
||||
BoundedNumArgumentConsumer::new()
|
||||
.name("count")
|
||||
.min(1)
|
||||
.max(99)
|
||||
}
|
||||
|
||||
struct BlockReplaceExecutor;
|
||||
|
||||
impl CommandExecutor for BlockReplaceExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let world = match sender {
|
||||
CommandSender::Console | CommandSender::Rcon(_) | CommandSender::Dummy => {
|
||||
let guard = server.worlds.load();
|
||||
guard
|
||||
.first()
|
||||
.cloned()
|
||||
.ok_or(CommandError::InvalidRequirement)?
|
||||
}
|
||||
CommandSender::Player(player) => player.world().clone(),
|
||||
CommandSender::CommandBlock(_, w) => w.clone(),
|
||||
};
|
||||
|
||||
let pos = BlockPosArgumentConsumer::find_loaded_arg(args, ARG_POS, &world)?;
|
||||
let (slot, slot_name) = SlotArgumentConsumer::find_arg(args, ARG_SLOT)?;
|
||||
let (item_name, parsed_stack) = ItemArgumentConsumer::find_arg(args, ARG_ITEM)?;
|
||||
let item = parsed_stack.item;
|
||||
let count = match count_consumer().find_arg_default_name(args) {
|
||||
Ok(Ok(c)) => c,
|
||||
Err(_) | Ok(Err(_)) => 1,
|
||||
};
|
||||
|
||||
let block_entity = world.get_block_entity(&pos).ok_or_else(|| {
|
||||
CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ITEM_TARGET_NOT_A_CONTAINER,
|
||||
translation::java::COMMANDS_ITEM_TARGET_NOT_A_CONTAINER,
|
||||
[
|
||||
TextComponent::text(pos.0.x.to_string()),
|
||||
TextComponent::text(pos.0.y.to_string()),
|
||||
TextComponent::text(pos.0.z.to_string()),
|
||||
],
|
||||
))
|
||||
})?;
|
||||
|
||||
let inventory = block_entity.get_inventory().ok_or_else(|| {
|
||||
CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ITEM_TARGET_NOT_A_CONTAINER,
|
||||
translation::java::COMMANDS_ITEM_TARGET_NOT_A_CONTAINER,
|
||||
[
|
||||
TextComponent::text(pos.0.x.to_string()),
|
||||
TextComponent::text(pos.0.y.to_string()),
|
||||
TextComponent::text(pos.0.z.to_string()),
|
||||
],
|
||||
))
|
||||
})?;
|
||||
|
||||
if slot >= inventory.size() {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ITEM_TARGET_NO_SUCH_SLOT,
|
||||
translation::java::COMMANDS_ITEM_TARGET_NO_SUCH_SLOT,
|
||||
[TextComponent::text(slot_name)],
|
||||
)));
|
||||
}
|
||||
|
||||
let mut item_stack = parsed_stack.clone();
|
||||
item_stack.item_count = count as u8;
|
||||
inventory.set_stack(slot, item_stack.clone()).await;
|
||||
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ITEM_BLOCK_SET_SUCCESS,
|
||||
translation::java::COMMANDS_ITEM_BLOCK_SET_SUCCESS,
|
||||
[
|
||||
TextComponent::text(pos.0.x.to_string()),
|
||||
TextComponent::text(pos.0.y.to_string()),
|
||||
TextComponent::text(pos.0.z.to_string()),
|
||||
TextComponent::text("[")
|
||||
.add_child(item.translated_name())
|
||||
.add_child(TextComponent::text("]"))
|
||||
.hover_event(HoverEvent::ShowItem {
|
||||
id: item_name.to_string().into(),
|
||||
count: Some(count),
|
||||
}),
|
||||
],
|
||||
);
|
||||
sender.send_message(msg).await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct EntityReplaceExecutor;
|
||||
|
||||
impl CommandExecutor for EntityReplaceExecutor {
|
||||
#[expect(clippy::too_many_lines)]
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntitiesArgumentConsumer.find_arg_default_name(args)?;
|
||||
let (mojang_slot, slot_name) = SlotArgumentConsumer::find_arg(args, ARG_SLOT)?;
|
||||
let (item_name, parsed_stack) = ItemArgumentConsumer::find_arg(args, ARG_ITEM)?;
|
||||
let item = parsed_stack.item;
|
||||
let count = match count_consumer().find_arg_default_name(args) {
|
||||
Ok(Ok(c)) => c,
|
||||
Err(_) | Ok(Err(_)) => 1,
|
||||
};
|
||||
|
||||
let mut modified_count = 0;
|
||||
let mut item_stack = parsed_stack.clone();
|
||||
item_stack.item_count = count as u8;
|
||||
|
||||
for target in targets {
|
||||
if let Some(player) = target.get_player() {
|
||||
if (200..=226).contains(&mojang_slot) {
|
||||
let ender_slot = mojang_slot - 200;
|
||||
if ender_slot < player.ender_chest_inventory.size() {
|
||||
player
|
||||
.ender_chest_inventory
|
||||
.set_stack(ender_slot, item_stack.clone())
|
||||
.await;
|
||||
modified_count += 1;
|
||||
}
|
||||
} else {
|
||||
let inventory = player.inventory();
|
||||
let mapped_slot = if mojang_slot == 98 {
|
||||
Some(inventory.get_selected_slot() as usize)
|
||||
} else if mojang_slot == 99 {
|
||||
Some(40)
|
||||
} else if mojang_slot == 100 {
|
||||
Some(36)
|
||||
} else if mojang_slot == 101 {
|
||||
Some(37)
|
||||
} else if mojang_slot == 102 {
|
||||
Some(38)
|
||||
} else if mojang_slot == 103 {
|
||||
Some(39)
|
||||
} else if mojang_slot <= 35 {
|
||||
Some(mojang_slot)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(slot) = mapped_slot
|
||||
&& slot < inventory.size()
|
||||
{
|
||||
inventory.set_stack(slot, item_stack.clone()).await;
|
||||
|
||||
let stack_serializer = ItemStackSerializer::from(item_stack.clone());
|
||||
let packet =
|
||||
CSetContainerSlot::new(0, 0, slot as i16, &stack_serializer);
|
||||
player.enqueue_slot_packet(&packet).await;
|
||||
|
||||
let eq_slot = if slot == 36 {
|
||||
Some(EquipmentSlot::FEET)
|
||||
} else if slot == 37 {
|
||||
Some(EquipmentSlot::LEGS)
|
||||
} else if slot == 38 {
|
||||
Some(EquipmentSlot::CHEST)
|
||||
} else if slot == 39 {
|
||||
Some(EquipmentSlot::HEAD)
|
||||
} else if slot == 40 {
|
||||
Some(EquipmentSlot::OFF_HAND)
|
||||
} else if slot == inventory.get_selected_slot() as usize {
|
||||
Some(EquipmentSlot::MAIN_HAND)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(eq) = eq_slot {
|
||||
player
|
||||
.living_entity
|
||||
.send_equipment_changes(&[(eq, item_stack.clone())]);
|
||||
}
|
||||
|
||||
modified_count += 1;
|
||||
}
|
||||
}
|
||||
} else if let Some(living) = target.get_living_entity() {
|
||||
let mapped_eq = if mojang_slot == 98 {
|
||||
Some(EquipmentSlot::MAIN_HAND)
|
||||
} else if mojang_slot == 99 {
|
||||
Some(EquipmentSlot::OFF_HAND)
|
||||
} else if mojang_slot == 100 {
|
||||
Some(EquipmentSlot::FEET)
|
||||
} else if mojang_slot == 101 {
|
||||
Some(EquipmentSlot::LEGS)
|
||||
} else if mojang_slot == 102 {
|
||||
Some(EquipmentSlot::CHEST)
|
||||
} else if mojang_slot == 103 {
|
||||
Some(EquipmentSlot::HEAD)
|
||||
} else if mojang_slot == 105 {
|
||||
Some(EquipmentSlot::BODY)
|
||||
} else if mojang_slot == 106 {
|
||||
Some(EquipmentSlot::SADDLE)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(eq) = mapped_eq {
|
||||
living
|
||||
.entity_equipment
|
||||
.lock()
|
||||
.await
|
||||
.put(&eq, item_stack.clone())
|
||||
.await;
|
||||
living.send_equipment_changes(&[(eq, item_stack.clone())]);
|
||||
modified_count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if modified_count == 0 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ITEM_TARGET_NO_SUCH_SLOT,
|
||||
translation::java::COMMANDS_ITEM_TARGET_NO_SUCH_SLOT,
|
||||
[TextComponent::text(slot_name)],
|
||||
)));
|
||||
}
|
||||
|
||||
let msg = if targets.len() == 1 {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ITEM_ENTITY_SET_SUCCESS_SINGLE,
|
||||
translation::java::COMMANDS_ITEM_ENTITY_SET_SUCCESS_SINGLE,
|
||||
[
|
||||
targets[0].get_display_name().await,
|
||||
TextComponent::text("[")
|
||||
.add_child(item.translated_name())
|
||||
.add_child(TextComponent::text("]"))
|
||||
.hover_event(HoverEvent::ShowItem {
|
||||
id: item_name.to_string().into(),
|
||||
count: Some(count),
|
||||
}),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ITEM_ENTITY_SET_SUCCESS_MULTIPLE,
|
||||
translation::java::COMMANDS_ITEM_ENTITY_SET_SUCCESS_MULTIPLE,
|
||||
[
|
||||
TextComponent::text(modified_count.to_string()),
|
||||
TextComponent::text("[")
|
||||
.add_child(item.translated_name())
|
||||
.add_child(TextComponent::text("]"))
|
||||
.hover_event(HoverEvent::ShowItem {
|
||||
id: item_name.to_string().into(),
|
||||
count: Some(count),
|
||||
}),
|
||||
],
|
||||
)
|
||||
};
|
||||
sender.send_message(msg).await;
|
||||
|
||||
Ok(modified_count)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
literal("replace")
|
||||
.then(
|
||||
literal("block").then(
|
||||
argument(ARG_POS, BlockPosArgumentConsumer).then(
|
||||
argument(ARG_SLOT, SlotArgumentConsumer)
|
||||
.then(
|
||||
argument(ARG_ITEM, ItemArgumentConsumer)
|
||||
.execute(BlockReplaceExecutor)
|
||||
.then(
|
||||
argument_default_name(count_consumer())
|
||||
.execute(BlockReplaceExecutor),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("with").then(
|
||||
argument(ARG_ITEM, ItemArgumentConsumer)
|
||||
.execute(BlockReplaceExecutor)
|
||||
.then(
|
||||
argument_default_name(count_consumer())
|
||||
.execute(BlockReplaceExecutor),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("entity").then(
|
||||
argument(ARG_TARGETS, EntitiesArgumentConsumer).then(
|
||||
argument(ARG_SLOT, SlotArgumentConsumer)
|
||||
.then(
|
||||
argument(ARG_ITEM, ItemArgumentConsumer)
|
||||
.execute(EntityReplaceExecutor)
|
||||
.then(
|
||||
argument_default_name(count_consumer())
|
||||
.execute(EntityReplaceExecutor),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("with").then(
|
||||
argument(ARG_ITEM, ItemArgumentConsumer)
|
||||
.execute(EntityReplaceExecutor)
|
||||
.then(
|
||||
argument_default_name(count_consumer())
|
||||
.execute(EntityReplaceExecutor),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_util::text::color::NamedColor;
|
||||
|
||||
use crate::command::args::message::MsgArgConsumer;
|
||||
use crate::command::args::players::PlayersArgumentConsumer;
|
||||
use crate::command::args::{Arg, ConsumedArgs};
|
||||
use crate::command::tree::CommandTree;
|
||||
use crate::command::tree::builder::argument;
|
||||
use crate::command::{CommandError, CommandResult};
|
||||
use crate::command::{CommandExecutor, CommandSender};
|
||||
use crate::entity::EntityBase;
|
||||
use crate::net::DisconnectReason;
|
||||
use CommandError::InvalidConsumption;
|
||||
|
||||
const NAMES: [&str; 1] = ["kick"];
|
||||
const DESCRIPTION: &str = "Kicks the target player from the server.";
|
||||
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
|
||||
const ARG_REASON: &str = "reason";
|
||||
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
|
||||
let custom_reason = args.get(&ARG_REASON);
|
||||
let reason = match custom_reason {
|
||||
Some(Arg::Msg(r)) => TextComponent::text(r.clone()),
|
||||
_ => TextComponent::translate_cross(
|
||||
translation::java::MULTIPLAYER_DISCONNECT_KICKED,
|
||||
translation::bedrock::DISCONNECT_KICKED,
|
||||
[],
|
||||
),
|
||||
};
|
||||
|
||||
for target in targets {
|
||||
target.kick(DisconnectReason::Kicked, reason.clone()).await;
|
||||
|
||||
let feedback = if custom_reason.is_some() {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_KICK_SUCCESS,
|
||||
translation::bedrock::COMMANDS_KICK_SUCCESS_REASON,
|
||||
[target.get_display_name().await, reason.clone()],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_KICK_SUCCESS,
|
||||
translation::bedrock::COMMANDS_KICK_SUCCESS,
|
||||
[target.get_display_name().await, reason.clone()],
|
||||
)
|
||||
};
|
||||
|
||||
sender
|
||||
.send_message(feedback.color_named(NamedColor::Blue))
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(targets.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Permission
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(ARG_TARGETS, PlayersArgumentConsumer)
|
||||
.execute(Executor)
|
||||
.then(argument(ARG_REASON, MsgArgConsumer).execute(Executor)),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command};
|
||||
use crate::command::argument_types::entity::EntityArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const DESCRIPTION: &str = "Kills all target entities.";
|
||||
|
||||
const PERMISSION: &str = "minecraft:command.kill";
|
||||
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
|
||||
struct TargetsExecutor;
|
||||
|
||||
impl CommandExecutor for TargetsExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_entities(context, ARG_TARGETS).await?;
|
||||
|
||||
let target_count = targets.len();
|
||||
for target in &targets {
|
||||
target.kill(target.as_ref()).await;
|
||||
}
|
||||
|
||||
let msg = if target_count == 1 {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_KILL_SUCCESS_SINGLE,
|
||||
translation::bedrock::COMMANDS_KILL_SUCCESSFUL,
|
||||
[targets[0].get_display_name().await],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_KILL_SUCCESS_MULTIPLE,
|
||||
translation::bedrock::COMMANDS_KILL_SUCCESSFUL,
|
||||
[TextComponent::text(target_count.to_string())],
|
||||
)
|
||||
};
|
||||
|
||||
context.source.send_feedback(msg, true).await;
|
||||
|
||||
Ok(target_count as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct SelfExecutor;
|
||||
|
||||
impl CommandExecutor for SelfExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = context.source.entity_or_err()?;
|
||||
target.kill(&*target).await;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_KILL_SUCCESS_SINGLE,
|
||||
translation::bedrock::COMMANDS_KILL_SUCCESSFUL,
|
||||
[target.get_display_name().await],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Four),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("kill", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.then(argument(ARG_TARGETS, EntityArgumentType::Entities).executes(TargetsExecutor))
|
||||
.executes(SelfExecutor),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use pumpkin_data::translation::java::{COMMANDS_LIST_NAMEANDID, COMMANDS_LIST_PLAYERS};
|
||||
use pumpkin_util::{
|
||||
permission::{Permission, PermissionDefault, PermissionRegistry},
|
||||
text::TextComponent,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
command::{
|
||||
argument_builder::{ArgumentBuilder, command, literal},
|
||||
context::command_context::CommandContext,
|
||||
node::{CommandExecutor, CommandExecutorResult, dispatcher::CommandDispatcher},
|
||||
},
|
||||
entity::{EntityBase, EntityBaseFuture, player::Player},
|
||||
};
|
||||
|
||||
const DESCRIPTION: &str = "Print the list of online players.";
|
||||
|
||||
const PERMISSION: &str = "minecraft:command.list";
|
||||
|
||||
enum ListMode {
|
||||
Names,
|
||||
Uuids,
|
||||
}
|
||||
|
||||
struct ListCommandExecutor(ListMode);
|
||||
|
||||
impl CommandExecutor for ListCommandExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let players: Vec<Arc<Player>> = context.server().get_all_players();
|
||||
let players_len = players.len();
|
||||
|
||||
let list = match self.0 {
|
||||
ListMode::Names => get_player_names(&players).await,
|
||||
ListMode::Uuids => get_player_names_and_ids(&players),
|
||||
};
|
||||
|
||||
let max_players = context.source.output.as_player().map_or_else(
|
||||
|| context.server().advanced_config.networking.java.max_players,
|
||||
|player| match player.client.as_ref() {
|
||||
crate::net::ClientPlatform::Java(_) => {
|
||||
context.server().advanced_config.networking.java.max_players
|
||||
}
|
||||
crate::net::ClientPlatform::Bedrock(_) => {
|
||||
context
|
||||
.server()
|
||||
.advanced_config
|
||||
.networking
|
||||
.bedrock
|
||||
.max_players
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
COMMANDS_LIST_PLAYERS,
|
||||
COMMANDS_LIST_PLAYERS,
|
||||
[
|
||||
TextComponent::text(players_len.to_string()),
|
||||
TextComponent::text(max_players.to_string()),
|
||||
list,
|
||||
],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(players_len as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_player_names(players: &[Arc<Player>]) -> TextComponent {
|
||||
let display_name_futures: Vec<EntityBaseFuture<'_, TextComponent>> =
|
||||
players.iter().map(|p| p.get_display_name()).collect();
|
||||
let display_names = futures::future::join_all(display_name_futures).await;
|
||||
TextComponent::join_with_comma(display_names)
|
||||
}
|
||||
|
||||
fn get_player_names_and_ids(players: &[Arc<Player>]) -> TextComponent {
|
||||
let names_and_ids = players
|
||||
.iter()
|
||||
.map(|p| {
|
||||
TextComponent::translate_cross(
|
||||
COMMANDS_LIST_NAMEANDID,
|
||||
COMMANDS_LIST_NAMEANDID,
|
||||
&[
|
||||
p.get_name(),
|
||||
TextComponent::text(p.gameprofile.id.to_string()),
|
||||
],
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
TextComponent::join_with_comma(names_and_ids)
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Allow,
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("list", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.then(literal("uuids").executes(ListCommandExecutor(ListMode::Uuids)))
|
||||
.executes(ListCommandExecutor(ListMode::Names)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command, literal};
|
||||
use crate::command::argument_types::coordinates::block_pos::BlockPosArgumentType;
|
||||
use crate::command::argument_types::core::string::StringArgumentType;
|
||||
use crate::command::argument_types::entity::EntityArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use crate::world::loot::LootTableExt;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const DESCRIPTION: &str =
|
||||
"Drops the given loot table into the specified inventory or into the world.";
|
||||
const PERMISSION: &str = "minecraft:command.loot";
|
||||
|
||||
static ERROR_INVALID_LOOT_TABLE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::bedrock::COMMANDS_LOOT_FAILURE_INVALIDLOOTTABLE,
|
||||
"Loot table '%s' not found",
|
||||
);
|
||||
|
||||
static ERROR_ENTITY_NO_LOOT_TABLE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::bedrock::COMMANDS_LOOT_FAILURE_ENTITYNOLOOTTABLE,
|
||||
"Entity %s has no loot table",
|
||||
);
|
||||
|
||||
static ERROR_NO_CONTAINER: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::bedrock::COMMANDS_LOOT_FAILURE_NOCONTAINER,
|
||||
"Target position %s is not a container",
|
||||
);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Target {
|
||||
Give,
|
||||
Spawn,
|
||||
Insert,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Source {
|
||||
Loot,
|
||||
Kill,
|
||||
Mine { has_tool: bool },
|
||||
}
|
||||
|
||||
struct LootExecutor {
|
||||
target: Target,
|
||||
source: Source,
|
||||
}
|
||||
|
||||
async fn insert_into_inventory(
|
||||
inventory: &dyn pumpkin_world::inventory::Inventory,
|
||||
mut stack: pumpkin_data::item_stack::ItemStack,
|
||||
) -> pumpkin_data::item_stack::ItemStack {
|
||||
for i in 0..inventory.size() {
|
||||
if stack.is_empty() {
|
||||
break;
|
||||
}
|
||||
let slot = inventory.get_stack(i).await;
|
||||
let mut slot_stack = slot.lock().await;
|
||||
if !slot_stack.is_empty() && slot_stack.get_item().id == stack.get_item().id {
|
||||
let max_stack_size = 64;
|
||||
let space = max_stack_size - slot_stack.item_count;
|
||||
if space > 0 {
|
||||
let to_add = stack.item_count.min(space);
|
||||
slot_stack.item_count += to_add;
|
||||
stack.item_count -= to_add;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for i in 0..inventory.size() {
|
||||
if stack.is_empty() {
|
||||
break;
|
||||
}
|
||||
let slot = inventory.get_stack(i).await;
|
||||
let mut slot_stack = slot.lock().await;
|
||||
if slot_stack.is_empty() {
|
||||
*slot_stack = stack.clone();
|
||||
stack.item_count = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
stack
|
||||
}
|
||||
|
||||
impl CommandExecutor for LootExecutor {
|
||||
#[allow(clippy::too_many_lines)]
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let mut stacks = Vec::new();
|
||||
|
||||
match self.source {
|
||||
Source::Loot => {
|
||||
let loot_table_str = StringArgumentType::get(context, "loot_table")?;
|
||||
let formatted_key = if loot_table_str.contains(':') {
|
||||
loot_table_str.to_string()
|
||||
} else {
|
||||
format!("minecraft:{loot_table_str}")
|
||||
};
|
||||
|
||||
let chest_table =
|
||||
pumpkin_data::chest_loot_table::get_chest_loot_table(&formatted_key);
|
||||
if let Some(table) = chest_table {
|
||||
let seed: i64 = rand::random();
|
||||
stacks = crate::world::loot::generate_chest_loot(table, seed);
|
||||
} else {
|
||||
return Err(ERROR_INVALID_LOOT_TABLE.create_without_context(
|
||||
TextComponent::text(loot_table_str.to_string()),
|
||||
));
|
||||
}
|
||||
}
|
||||
Source::Kill => {
|
||||
let target_entities =
|
||||
EntityArgumentType::get_entities(context, "target_entity").await?;
|
||||
let mut has_loot = false;
|
||||
for entity in target_entities {
|
||||
if let Some(loot_table) = &entity.get_entity().entity_type.loot_table {
|
||||
has_loot = true;
|
||||
let params = crate::world::loot::LootContextParameters {
|
||||
world_time: context.world().level_info.load().day_time as u64,
|
||||
..Default::default()
|
||||
};
|
||||
stacks.extend(loot_table.get_loot(params));
|
||||
}
|
||||
}
|
||||
if !has_loot {
|
||||
let entity_name = "selected entity".to_string();
|
||||
return Err(ERROR_ENTITY_NO_LOOT_TABLE
|
||||
.create_without_context(TextComponent::text(entity_name)));
|
||||
}
|
||||
}
|
||||
Source::Mine { has_tool } => {
|
||||
let pos = BlockPosArgumentType::get_block_pos(context, "mine_pos")
|
||||
.or_else(|_| BlockPosArgumentType::get_block_pos(context, "pos"))?;
|
||||
let world = context.world();
|
||||
let block = world.get_block(&pos);
|
||||
|
||||
if let Some(loot_table) = &block.loot_table {
|
||||
let tool_item = if has_tool {
|
||||
let tool_str = StringArgumentType::get(context, "tool")?;
|
||||
let key = tool_str.strip_prefix("minecraft:").unwrap_or(tool_str);
|
||||
pumpkin_data::item::Item::from_registry_key(key)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let tool_stack =
|
||||
tool_item.map(|item| pumpkin_data::item_stack::ItemStack::new(1, item));
|
||||
|
||||
let params = crate::world::loot::LootContextParameters {
|
||||
block_state: Some(world.get_block_state(&pos)),
|
||||
tool: tool_stack,
|
||||
world_time: world.level_info.load().day_time as u64,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
stacks.extend(loot_table.get_loot(params));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let total_items: i32 = stacks.iter().map(|s| s.item_count as i32).sum();
|
||||
|
||||
match self.target {
|
||||
Target::Give => {
|
||||
let targets = EntityArgumentType::get_players(context, "targets").await?;
|
||||
for player in &targets {
|
||||
for stack in &stacks {
|
||||
let mut remaining = stack.clone();
|
||||
player.inventory.insert_stack_anywhere(&mut remaining).await;
|
||||
if !remaining.is_empty() {
|
||||
player.drop_item(remaining).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Target::Spawn => {
|
||||
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||
let world = context.world();
|
||||
for stack in stacks {
|
||||
world.drop_stack(&pos, stack).await;
|
||||
}
|
||||
}
|
||||
Target::Insert => {
|
||||
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||
let world = context.world();
|
||||
if let Some(block_entity) = world.get_block_entity(&pos) {
|
||||
if let Some(inventory) = block_entity.get_inventory() {
|
||||
for stack in stacks {
|
||||
let remaining =
|
||||
insert_into_inventory(inventory.as_ref(), stack).await;
|
||||
if !remaining.is_empty() {
|
||||
world.drop_stack(&pos, remaining).await;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Err(ERROR_NO_CONTAINER
|
||||
.create_without_context(TextComponent::text(pos.to_string())));
|
||||
}
|
||||
} else {
|
||||
return Err(ERROR_NO_CONTAINER
|
||||
.create_without_context(TextComponent::text(pos.to_string())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::bedrock::COMMANDS_LOOT_SUCCESS,
|
||||
translation::bedrock::COMMANDS_LOOT_SUCCESS,
|
||||
[TextComponent::text(total_items.to_string())],
|
||||
);
|
||||
context.source.send_feedback(msg, true).await;
|
||||
|
||||
Ok(total_items)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::too_many_lines)]
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
));
|
||||
|
||||
let builder = command("loot", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
// give <targets>
|
||||
.then(
|
||||
literal("give").then(
|
||||
argument("targets", EntityArgumentType::Players)
|
||||
.then(literal("loot").then(
|
||||
argument("loot_table", StringArgumentType::SingleWord).executes(
|
||||
LootExecutor {
|
||||
target: Target::Give,
|
||||
source: Source::Loot,
|
||||
},
|
||||
),
|
||||
))
|
||||
.then(literal("kill").then(
|
||||
argument("target_entity", EntityArgumentType::Entities).executes(
|
||||
LootExecutor {
|
||||
target: Target::Give,
|
||||
source: Source::Kill,
|
||||
},
|
||||
),
|
||||
))
|
||||
.then(
|
||||
literal("mine").then(
|
||||
argument("pos", BlockPosArgumentType)
|
||||
.executes(LootExecutor {
|
||||
target: Target::Give,
|
||||
source: Source::Mine { has_tool: false },
|
||||
})
|
||||
.then(argument("tool", StringArgumentType::SingleWord).executes(
|
||||
LootExecutor {
|
||||
target: Target::Give,
|
||||
source: Source::Mine { has_tool: true },
|
||||
},
|
||||
)),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
// spawn <pos>
|
||||
.then(
|
||||
literal("spawn").then(
|
||||
argument("pos", BlockPosArgumentType)
|
||||
.then(literal("loot").then(
|
||||
argument("loot_table", StringArgumentType::SingleWord).executes(
|
||||
LootExecutor {
|
||||
target: Target::Spawn,
|
||||
source: Source::Loot,
|
||||
},
|
||||
),
|
||||
))
|
||||
.then(literal("kill").then(
|
||||
argument("target_entity", EntityArgumentType::Entities).executes(
|
||||
LootExecutor {
|
||||
target: Target::Spawn,
|
||||
source: Source::Kill,
|
||||
},
|
||||
),
|
||||
))
|
||||
.then(
|
||||
literal("mine").then(
|
||||
argument("mine_pos", BlockPosArgumentType)
|
||||
.executes(LootExecutor {
|
||||
target: Target::Spawn,
|
||||
source: Source::Mine { has_tool: false },
|
||||
})
|
||||
.then(argument("tool", StringArgumentType::SingleWord).executes(
|
||||
LootExecutor {
|
||||
target: Target::Spawn,
|
||||
source: Source::Mine { has_tool: true },
|
||||
},
|
||||
)),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
// insert <pos>
|
||||
.then(
|
||||
literal("insert").then(
|
||||
argument("pos", BlockPosArgumentType)
|
||||
.then(literal("loot").then(
|
||||
argument("loot_table", StringArgumentType::SingleWord).executes(
|
||||
LootExecutor {
|
||||
target: Target::Insert,
|
||||
source: Source::Loot,
|
||||
},
|
||||
),
|
||||
))
|
||||
.then(literal("kill").then(
|
||||
argument("target_entity", EntityArgumentType::Entities).executes(
|
||||
LootExecutor {
|
||||
target: Target::Insert,
|
||||
source: Source::Kill,
|
||||
},
|
||||
),
|
||||
))
|
||||
.then(
|
||||
literal("mine").then(
|
||||
argument("mine_pos", BlockPosArgumentType)
|
||||
.executes(LootExecutor {
|
||||
target: Target::Insert,
|
||||
source: Source::Mine { has_tool: false },
|
||||
})
|
||||
.then(argument("tool", StringArgumentType::SingleWord).executes(
|
||||
LootExecutor {
|
||||
target: Target::Insert,
|
||||
source: Source::Mine { has_tool: true },
|
||||
},
|
||||
)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
dispatcher.register(builder);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
use pumpkin_data::world::EMOTE_COMMAND;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::command::{
|
||||
CommandError, CommandExecutor, CommandResult, CommandSender,
|
||||
args::{Arg, ConsumedArgs, message::MsgArgConsumer},
|
||||
tree::{CommandTree, builder::argument},
|
||||
};
|
||||
use CommandError::InvalidConsumption;
|
||||
|
||||
const NAMES: [&str; 1] = ["me"];
|
||||
|
||||
const DESCRIPTION: &str = "Broadcasts a narrative message about yourself.";
|
||||
|
||||
const ARG_MESSAGE: &str = "action";
|
||||
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Msg(msg)) = args.get(ARG_MESSAGE) else {
|
||||
return Err(InvalidConsumption(Some(ARG_MESSAGE.into())));
|
||||
};
|
||||
|
||||
let Some(server_arc) = sender
|
||||
.world_or_first(server)
|
||||
.and_then(|w| w.server.upgrade())
|
||||
else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(
|
||||
"Failed to get server instance",
|
||||
)));
|
||||
};
|
||||
|
||||
server_arc
|
||||
.broadcast_message(
|
||||
&TextComponent::text(msg.clone()),
|
||||
&TextComponent::text(format!("{sender}")),
|
||||
EMOTE_COMMAND,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION)
|
||||
.then(argument(ARG_MESSAGE, MsgArgConsumer).execute(Executor))
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use pumpkin_config::BasicConfiguration;
|
||||
use pumpkin_util::{
|
||||
PermissionLvl,
|
||||
permission::{Permission, PermissionDefault, PermissionRegistry},
|
||||
};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
mod advancement;
|
||||
mod attribute;
|
||||
mod ban;
|
||||
mod banip;
|
||||
mod banlist;
|
||||
mod bossbar;
|
||||
mod clear;
|
||||
mod clone;
|
||||
mod damage;
|
||||
mod data;
|
||||
pub mod defaultgamemode;
|
||||
mod deop;
|
||||
mod dialog;
|
||||
mod difficulty;
|
||||
mod effect;
|
||||
mod enchant;
|
||||
mod execute;
|
||||
mod experience;
|
||||
mod fill;
|
||||
mod fillbiome;
|
||||
mod forceload;
|
||||
mod gamemode;
|
||||
mod gamerule;
|
||||
mod give;
|
||||
mod help;
|
||||
mod item;
|
||||
mod kick;
|
||||
mod kill;
|
||||
mod list;
|
||||
mod loot;
|
||||
mod me;
|
||||
mod msg;
|
||||
mod op;
|
||||
mod pardon;
|
||||
mod pardonip;
|
||||
mod particle;
|
||||
mod place;
|
||||
mod playsound;
|
||||
mod plugin;
|
||||
mod plugins;
|
||||
mod pumpkin;
|
||||
mod random;
|
||||
mod recipe;
|
||||
mod ride;
|
||||
mod rotate;
|
||||
mod saveall;
|
||||
mod saveoff;
|
||||
mod saveon;
|
||||
mod say;
|
||||
mod scoreboard;
|
||||
mod seed;
|
||||
mod setblock;
|
||||
mod setidletimeout;
|
||||
mod setworldspawn;
|
||||
mod spawnpoint;
|
||||
mod spectate;
|
||||
mod spreadplayers;
|
||||
mod stop;
|
||||
mod stopsound;
|
||||
mod summon;
|
||||
mod tag;
|
||||
mod team;
|
||||
mod teammsg;
|
||||
mod teleport;
|
||||
mod tellraw;
|
||||
mod tick;
|
||||
mod time;
|
||||
mod title;
|
||||
mod tps;
|
||||
mod transfer;
|
||||
mod trigger;
|
||||
mod weather;
|
||||
mod whitelist;
|
||||
mod worldborder;
|
||||
|
||||
#[allow(clippy::too_many_lines)]
|
||||
#[must_use]
|
||||
pub async fn default_dispatcher(
|
||||
registry: &RwLock<PermissionRegistry>,
|
||||
_basic_config: &BasicConfiguration,
|
||||
) -> CommandDispatcher {
|
||||
let mut dispatcher = crate::command::dispatcher::CommandDispatcher::default();
|
||||
|
||||
let mut registry_lock = registry.write().await;
|
||||
let registry = &mut *registry_lock;
|
||||
|
||||
register_permissions(registry);
|
||||
|
||||
// Zero
|
||||
dispatcher.register(pumpkin::init_command_tree(), "pumpkin:command.pumpkin");
|
||||
dispatcher.register(me::init_command_tree(), "minecraft:command.me");
|
||||
dispatcher.register(msg::init_command_tree(), "minecraft:command.msg");
|
||||
// Two
|
||||
dispatcher.register(
|
||||
worldborder::init_command_tree(),
|
||||
"minecraft:command.worldborder",
|
||||
);
|
||||
dispatcher.register(effect::init_command_tree(), "minecraft:command.effect");
|
||||
dispatcher.register(teleport::init_command_tree(), "minecraft:command.teleport");
|
||||
dispatcher.register(time::init_command_tree(), "minecraft:command.time");
|
||||
dispatcher.register(give::init_command_tree(), "minecraft:command.give");
|
||||
dispatcher.register(item::init_command_tree(), "minecraft:command.item");
|
||||
dispatcher.register(enchant::init_command_tree(), "minecraft:command.enchant");
|
||||
dispatcher.register(clear::init_command_tree(), "minecraft:command.clear");
|
||||
dispatcher.register(setblock::init_command_tree(), "minecraft:command.setblock");
|
||||
dispatcher.register(tps::init_command_tree(), "pumpkin:command.tps");
|
||||
dispatcher.register(fill::init_command_tree(), "minecraft:command.fill");
|
||||
dispatcher.register(
|
||||
playsound::init_command_tree(),
|
||||
"minecraft:command.playsound",
|
||||
);
|
||||
dispatcher.register(tellraw::init_command_tree(), "minecraft:command.tellraw");
|
||||
dispatcher.register(title::init_command_tree(), "minecraft:command.title");
|
||||
dispatcher.register(summon::init_command_tree(), "minecraft:command.summon");
|
||||
dispatcher.register(
|
||||
experience::init_command_tree(),
|
||||
"minecraft:command.experience",
|
||||
);
|
||||
dispatcher.register(weather::init_command_tree(), "minecraft:command.weather");
|
||||
dispatcher.register(particle::init_command_tree(), "minecraft:command.particle");
|
||||
dispatcher.register(rotate::init_command_tree(), "minecraft:command.rotate");
|
||||
dispatcher.register(damage::init_command_tree(), "minecraft:command.damage");
|
||||
dispatcher.register(bossbar::init_command_tree(), "minecraft:command.bossbar");
|
||||
dispatcher.register(say::init_command_tree(), "minecraft:command.say");
|
||||
dispatcher.register(gamemode::init_command_tree(), "minecraft:command.gamemode");
|
||||
dispatcher.register(gamerule::init_command_tree(), "minecraft:command.gamerule");
|
||||
dispatcher.register(
|
||||
stopsound::init_command_tree(),
|
||||
"minecraft:command.stopsound",
|
||||
);
|
||||
dispatcher.register(
|
||||
defaultgamemode::init_command_tree(),
|
||||
"minecraft:command.defaultgamemode",
|
||||
);
|
||||
dispatcher.register(
|
||||
setworldspawn::init_command_tree(),
|
||||
"minecraft:command.setworldspawn",
|
||||
);
|
||||
dispatcher.register(
|
||||
spawnpoint::init_command_tree(),
|
||||
"minecraft:command.spawnpoint",
|
||||
);
|
||||
dispatcher.register(spectate::init_command_tree(), "minecraft:command.spectate");
|
||||
dispatcher.register(data::init_command_tree(), "minecraft:command.data");
|
||||
// Three
|
||||
dispatcher.register(deop::init_command_tree(), "minecraft:command.deop");
|
||||
dispatcher.register(kick::init_command_tree(), "minecraft:command.kick");
|
||||
dispatcher.register(plugin::init_command_tree(), "pumpkin:command.plugin");
|
||||
dispatcher.register(plugins::init_command_tree(), "pumpkin:command.plugins");
|
||||
dispatcher.register(ban::init_command_tree(), "minecraft:command.ban");
|
||||
dispatcher.register(banip::init_command_tree(), "minecraft:command.banip");
|
||||
dispatcher.register(pardon::init_command_tree(), "minecraft:command.pardon");
|
||||
dispatcher.register(pardonip::init_command_tree(), "minecraft:command.pardonip");
|
||||
dispatcher.register(
|
||||
whitelist::init_command_tree(),
|
||||
"minecraft:command.whitelist",
|
||||
);
|
||||
dispatcher.register(transfer::init_command_tree(), "minecraft:command.transfer");
|
||||
|
||||
let mut dispatcher = {
|
||||
let mut wrapper_dispatcher = CommandDispatcher::new();
|
||||
wrapper_dispatcher.fallback_dispatcher = dispatcher;
|
||||
wrapper_dispatcher
|
||||
};
|
||||
|
||||
banlist::register(&mut dispatcher, registry);
|
||||
difficulty::register(&mut dispatcher, registry);
|
||||
dialog::register(&mut dispatcher, registry);
|
||||
execute::register(&mut dispatcher, registry);
|
||||
fillbiome::register(&mut dispatcher, registry);
|
||||
forceload::register(&mut dispatcher, registry);
|
||||
ride::register(&mut dispatcher, registry);
|
||||
recipe::register(&mut dispatcher, registry);
|
||||
help::register(&mut dispatcher, registry);
|
||||
kill::register(&mut dispatcher, registry);
|
||||
op::register(&mut dispatcher, registry);
|
||||
place::register(&mut dispatcher, registry);
|
||||
random::register(&mut dispatcher, registry);
|
||||
list::register(&mut dispatcher, registry);
|
||||
loot::register(&mut dispatcher, registry);
|
||||
seed::register(&mut dispatcher, registry);
|
||||
saveall::register(&mut dispatcher, registry);
|
||||
saveoff::register(&mut dispatcher, registry);
|
||||
saveon::register(&mut dispatcher, registry);
|
||||
setidletimeout::register(&mut dispatcher, registry);
|
||||
spreadplayers::register(&mut dispatcher, registry);
|
||||
stop::register(&mut dispatcher, registry);
|
||||
tag::register(&mut dispatcher, registry);
|
||||
tick::register(&mut dispatcher, registry);
|
||||
advancement::register(&mut dispatcher, registry);
|
||||
trigger::register(&mut dispatcher, registry);
|
||||
scoreboard::register(&mut dispatcher, registry);
|
||||
team::register(&mut dispatcher, registry);
|
||||
teammsg::register(&mut dispatcher, registry);
|
||||
clone::register(&mut dispatcher, registry);
|
||||
attribute::register(&mut dispatcher, registry);
|
||||
dispatcher
|
||||
}
|
||||
|
||||
fn register_permissions(registry: &mut PermissionRegistry) {
|
||||
// Register level 0 permissions (allowed by default)
|
||||
register_level_0_permissions(registry);
|
||||
|
||||
// Register level 2 permissions (OP level 2)
|
||||
register_level_2_permissions(registry);
|
||||
|
||||
// Register level 3 permissions (OP level 3)
|
||||
register_level_3_permissions(registry);
|
||||
|
||||
// Register our entity selector permission as well.
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.selector",
|
||||
"Allows a player to use selector variables",
|
||||
PermissionDefault::Allow,
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
}
|
||||
|
||||
fn register_level_0_permissions(registry: &mut PermissionRegistry) {
|
||||
// Register permissions for builtin commands that are allowed for everyone
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"pumpkin:command.pumpkin",
|
||||
"Shows information about the Pumpkin server",
|
||||
PermissionDefault::Allow,
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.me",
|
||||
"Broadcasts a narrative message about the player",
|
||||
PermissionDefault::Allow,
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.msg",
|
||||
"Sends a private message to another player",
|
||||
PermissionDefault::Allow,
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
}
|
||||
|
||||
#[expect(clippy::too_many_lines)]
|
||||
fn register_level_2_permissions(registry: &mut PermissionRegistry) {
|
||||
// Register permissions for commands with PermissionLvl::Two
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.worldborder",
|
||||
"Manages the world border",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.effect",
|
||||
"Adds or removes status effects",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.teleport",
|
||||
"Teleports entities to other locations",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.time",
|
||||
"Changes or queries the world's game time",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.give",
|
||||
"Gives an item to a player",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.item",
|
||||
"Replace items in inventories",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.clear",
|
||||
"Clears items from player inventory",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.setblock",
|
||||
"Changes a block to another block",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.fill",
|
||||
"Fills a region with a specific block",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.playsound",
|
||||
"Plays a sound to players",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.tellraw",
|
||||
"Displays a JSON message to players",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.title",
|
||||
"Controls screen titles displayed to players",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.summon",
|
||||
"Summons an entity",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.experience",
|
||||
"Adds, removes or queries player experience",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.weather",
|
||||
"Sets the weather in the server",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.particle",
|
||||
"Creates particles in the world",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.rotate",
|
||||
"Changes the rotation of an entity",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.damage",
|
||||
"Damages entities",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.bossbar",
|
||||
"Creates and manages boss bars",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.say",
|
||||
"Broadcasts a message to multiple players",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.gamemode",
|
||||
"Sets a player's game mode",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.gamerule",
|
||||
"Sets a player's game mode",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.stopsound",
|
||||
"Stops sounds from playing",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.defaultgamemode",
|
||||
"Sets the default game mode for new players",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.data",
|
||||
"Query and modify data of entities and blocks",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.enchant",
|
||||
"Adds an enchantment to a player's selected item, subject to the same restrictions as an anvil. Also works on any mob or entity holding a weapon/tool/armor in its main hand.",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.spawnpoint",
|
||||
"Sets the spawn point for a player",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.spectate",
|
||||
"Allows a player to spectate another entity",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"pumpkin:command.tps",
|
||||
"Displays the server TPS and MSPT",
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
}
|
||||
|
||||
fn register_level_3_permissions(registry: &mut PermissionRegistry) {
|
||||
// Register permissions for commands with PermissionLvl::Three
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.setworldspawn",
|
||||
"Sets the world spawn point",
|
||||
PermissionDefault::Op(PermissionLvl::Three),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.deop",
|
||||
"Revokes operator status from a player",
|
||||
PermissionDefault::Op(PermissionLvl::Three),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.kick",
|
||||
"Removes players from the server",
|
||||
PermissionDefault::Op(PermissionLvl::Three),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"pumpkin:command.plugin",
|
||||
"Manages server plugins",
|
||||
PermissionDefault::Op(PermissionLvl::Three),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"pumpkin:command.plugins",
|
||||
"Lists all plugins loaded on the server",
|
||||
PermissionDefault::Op(PermissionLvl::Three),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.ban",
|
||||
"Adds players to banlist",
|
||||
PermissionDefault::Op(PermissionLvl::Three),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.banip",
|
||||
"Adds IP addresses to banlist",
|
||||
PermissionDefault::Op(PermissionLvl::Three),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.pardon",
|
||||
"Removes entries from the player banlist",
|
||||
PermissionDefault::Op(PermissionLvl::Three),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.pardonip",
|
||||
"Removes entries from the IP banlist",
|
||||
PermissionDefault::Op(PermissionLvl::Three),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.whitelist",
|
||||
"Manages server whitelist",
|
||||
PermissionDefault::Op(PermissionLvl::Three),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
registry
|
||||
.register_permission(Permission::new(
|
||||
"minecraft:command.transfer",
|
||||
"Transfers the player to another server",
|
||||
PermissionDefault::Op(PermissionLvl::Three),
|
||||
))
|
||||
.expect("Permission already registered");
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
use pumpkin_data::world::{MSG_COMMAND_INCOMING, MSG_COMMAND_OUTGOING};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::command::{
|
||||
CommandError, CommandExecutor, CommandResult, CommandSender,
|
||||
args::{
|
||||
Arg, ConsumedArgs, FindArgDefaultName, message::MsgArgConsumer,
|
||||
players::PlayersArgumentConsumer,
|
||||
},
|
||||
tree::{
|
||||
CommandTree,
|
||||
builder::{argument, argument_default_name},
|
||||
},
|
||||
};
|
||||
use crate::entity::EntityBase;
|
||||
use CommandError::InvalidConsumption;
|
||||
|
||||
const NAMES: [&str; 3] = ["msg", "tell", "w"];
|
||||
|
||||
const DESCRIPTION: &str = "Sends a private message to one or more players.";
|
||||
|
||||
const ARG_MESSAGE: &str = "message";
|
||||
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Msg(msg)) = args.get(ARG_MESSAGE) else {
|
||||
return Err(InvalidConsumption(Some(ARG_MESSAGE.into())));
|
||||
};
|
||||
let targets = PlayersArgumentConsumer.find_arg_default_name(args)?;
|
||||
let player = sender.as_player().ok_or(CommandError::InvalidRequirement)?;
|
||||
|
||||
for target in targets {
|
||||
player
|
||||
.send_message(
|
||||
&TextComponent::text(msg.clone()),
|
||||
MSG_COMMAND_OUTGOING,
|
||||
&player.get_display_name().await,
|
||||
Some(&target.get_display_name().await),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
for target in targets {
|
||||
target
|
||||
.send_message(
|
||||
&TextComponent::text(msg.clone()),
|
||||
MSG_COMMAND_INCOMING,
|
||||
&player.get_display_name().await,
|
||||
Some(&target.get_display_name().await),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(targets.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument_default_name(PlayersArgumentConsumer)
|
||||
.then(argument(ARG_MESSAGE, MsgArgConsumer).execute(Executor)),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command};
|
||||
use crate::command::argument_types::game_profile::GameProfileArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use crate::command::suggestion::provider::{SuggestionProvider, SuggestionProviderResult};
|
||||
use crate::command::suggestion::suggestions::SuggestionsBuilder;
|
||||
use crate::data::SaveJSONConfiguration;
|
||||
use pumpkin_config::op::Op;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
pub const ALREADY_OP_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_OP_FAILED,
|
||||
translation::bedrock::COMMANDS_OP_FAILED,
|
||||
);
|
||||
|
||||
const DESCRIPTION: &str = "Grants operator status to a player.";
|
||||
const PERMISSION: &str = "minecraft:command.op";
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
|
||||
struct OpCommandExecutor;
|
||||
|
||||
impl CommandExecutor for OpCommandExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let server = context.server();
|
||||
let profiles = GameProfileArgumentType::get(context, ARG_TARGETS).await?;
|
||||
|
||||
let mut config = server.data.operator_config.write().await;
|
||||
let mut successes: i32 = 0;
|
||||
let new_level = server.basic_config.op_permission_level;
|
||||
|
||||
for profile in profiles {
|
||||
let maybe_existing_entry = config.ops.iter_mut().find(|o| o.uuid == profile.id);
|
||||
|
||||
if let Some(op) = maybe_existing_entry {
|
||||
if op.level == new_level {
|
||||
continue;
|
||||
}
|
||||
|
||||
op.level = new_level;
|
||||
op.name.clone_from(&profile.name);
|
||||
} else {
|
||||
let op_entry = Op::new(profile.id, profile.name.clone(), new_level, false);
|
||||
config.ops.push(op_entry);
|
||||
}
|
||||
|
||||
if let Some(player) = server.get_player_by_uuid(profile.id) {
|
||||
let command_dispatcher = server.command_dispatcher.read().await;
|
||||
player
|
||||
.set_permission_lvl(server, new_level, &command_dispatcher)
|
||||
.await;
|
||||
}
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_OP_SUCCESS,
|
||||
translation::bedrock::COMMANDS_OP_SUCCESS,
|
||||
[TextComponent::text(profile.name.clone())],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
successes += 1;
|
||||
}
|
||||
|
||||
if successes > 0 {
|
||||
config.save();
|
||||
}
|
||||
|
||||
if successes == 0 {
|
||||
Err(ALREADY_OP_ERROR_TYPE.create_without_context())
|
||||
} else {
|
||||
Ok(successes)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct OpSuggestionProvider;
|
||||
|
||||
impl SuggestionProvider for OpSuggestionProvider {
|
||||
fn suggest<'a>(
|
||||
&'a self,
|
||||
context: &'a CommandContext,
|
||||
mut builder: SuggestionsBuilder,
|
||||
) -> SuggestionProviderResult<'a> {
|
||||
Box::pin(async move {
|
||||
// Suggest every non-opped player.
|
||||
let ops = context.server().data.operator_config.read().await;
|
||||
for player in context.source.server().get_all_players() {
|
||||
if ops.ops.iter().all(|op| op.uuid != player.gameprofile.id) {
|
||||
builder = builder.suggest(player.gameprofile.name.clone());
|
||||
}
|
||||
}
|
||||
builder.build()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Three),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("op", DESCRIPTION).requires(PERMISSION).then(
|
||||
argument(ARG_TARGETS, GameProfileArgumentType)
|
||||
.suggests(OpSuggestionProvider)
|
||||
.executes(OpCommandExecutor),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
use crate::{
|
||||
command::{
|
||||
CommandError, CommandExecutor, CommandResult, CommandSender,
|
||||
args::{
|
||||
Arg, ConsumedArgs,
|
||||
gameprofile::{GameProfileSuggestionMode, GameProfilesArgumentConsumer},
|
||||
},
|
||||
tree::{CommandTree, builder::argument},
|
||||
},
|
||||
data::SaveJSONConfiguration,
|
||||
};
|
||||
use CommandError::InvalidConsumption;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const NAMES: [&str; 1] = ["pardon"];
|
||||
const DESCRIPTION: &str = "unbans a player";
|
||||
|
||||
const ARG_TARGET: &str = "targets";
|
||||
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
|
||||
let mut lock = server.data.banned_player_list.write().await;
|
||||
let mut successes = 0;
|
||||
|
||||
for target in targets {
|
||||
let idx = lock
|
||||
.banned_players
|
||||
.iter()
|
||||
.position(|entry| entry.uuid == target.id);
|
||||
|
||||
if let Some(idx) = idx {
|
||||
lock.banned_players.remove(idx);
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_PARDON_SUCCESS,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_UNBAN_SUCCESS,
|
||||
[TextComponent::text(target.name.clone())],
|
||||
))
|
||||
.await;
|
||||
successes += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if successes > 0 {
|
||||
lock.save();
|
||||
Ok(successes)
|
||||
} else {
|
||||
let err_target = targets
|
||||
.first()
|
||||
.map_or_else(String::new, |first_target| first_target.name.clone());
|
||||
Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_PARDON_FAILED,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_UNBAN_FAILED,
|
||||
[TextComponent::text(err_target)],
|
||||
)))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_lines)]
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(
|
||||
ARG_TARGET,
|
||||
GameProfilesArgumentConsumer::new(GameProfileSuggestionMode::BannedNames, false),
|
||||
)
|
||||
.execute(Executor),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use std::{net::IpAddr, str::FromStr};
|
||||
|
||||
use crate::{
|
||||
command::{
|
||||
CommandError, CommandExecutor, CommandResult, CommandSender,
|
||||
args::{Arg, ConsumedArgs, simple::SimpleArgConsumer},
|
||||
tree::{CommandTree, builder::argument},
|
||||
},
|
||||
data::SaveJSONConfiguration,
|
||||
};
|
||||
use CommandError::InvalidConsumption;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const NAMES: [&str; 1] = ["pardon-ip"];
|
||||
const DESCRIPTION: &str = "unbans a ip";
|
||||
|
||||
const ARG_TARGET: &str = "ip";
|
||||
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Simple(target)) = args.get(&ARG_TARGET) else {
|
||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||
};
|
||||
|
||||
let Ok(ip) = IpAddr::from_str(target) else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_PARDONIP_INVALID,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_UNBANIP_INVALID,
|
||||
[],
|
||||
)));
|
||||
};
|
||||
|
||||
let mut lock = server.data.banned_ip_list.write().await;
|
||||
|
||||
let result = if let Some(idx) = lock.banned_ips.iter().position(|entry| entry.ip == ip)
|
||||
{
|
||||
lock.banned_ips.remove(idx);
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_PARDONIP_SUCCESS,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_UNBANIP_SUCCESS,
|
||||
[TextComponent::text(ip.to_string())],
|
||||
))
|
||||
.await;
|
||||
Ok(1)
|
||||
} else {
|
||||
Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_PARDONIP_FAILED,
|
||||
pumpkin_data::translation::java::COMMANDS_PARDONIP_FAILED,
|
||||
[],
|
||||
)))
|
||||
};
|
||||
|
||||
lock.save();
|
||||
|
||||
result
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION)
|
||||
.then(argument(ARG_TARGET, SimpleArgConsumer).execute(Executor))
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
use crate::block::entities::BlockEntity;
|
||||
use crate::command::{
|
||||
CommandError, CommandExecutor, CommandResult, CommandSender,
|
||||
args::{
|
||||
ConsumedArgs, FindArg, bounded_num::BoundedNumArgumentConsumer,
|
||||
position_3d::Position3DArgumentConsumer, resource::particle::ParticleArgumentConsumer,
|
||||
},
|
||||
tree::{CommandTree, builder::argument},
|
||||
};
|
||||
use crate::entity::EntityBase;
|
||||
use pumpkin_util::{math::vector3::Vector3, text::TextComponent};
|
||||
const NAMES: [&str; 1] = ["particle"];
|
||||
|
||||
const DESCRIPTION: &str = "Spawns a Particle at position.";
|
||||
|
||||
const ARG_NAME: &str = "name";
|
||||
|
||||
const ARG_POS: &str = "pos";
|
||||
const ARG_DELTA: &str = "delta";
|
||||
const ARG_SPEED: &str = "speed";
|
||||
const ARG_COUNT: &str = "count";
|
||||
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let particle = ParticleArgumentConsumer::find_arg(args, ARG_NAME)?;
|
||||
let pos = Position3DArgumentConsumer::find_arg(args, ARG_POS);
|
||||
let delta = Position3DArgumentConsumer::find_arg(args, ARG_DELTA);
|
||||
let speed = BoundedNumArgumentConsumer::<f32>::find_arg(args, ARG_SPEED);
|
||||
let count = BoundedNumArgumentConsumer::<i32>::find_arg(args, ARG_COUNT);
|
||||
|
||||
let delta = delta.unwrap_or(Vector3::new(0.0, 0.0, 0.0));
|
||||
let delta: Vector3<f32> = Vector3::new(delta.x as f32, delta.y as f32, delta.z as f32);
|
||||
let speed = speed.unwrap_or(Ok(0.0))?;
|
||||
let count = count.unwrap_or(Ok(0))?;
|
||||
let (world, pos) = match sender {
|
||||
CommandSender::Console | CommandSender::Rcon(_) | CommandSender::Dummy => {
|
||||
let guard = server.worlds.load();
|
||||
let world = guard
|
||||
.first()
|
||||
.cloned()
|
||||
.ok_or(CommandError::InvalidRequirement)?;
|
||||
// default position for spawning a player, in this case for particle
|
||||
let pos = {
|
||||
let info = &world.level_info.load();
|
||||
// default position for spawning a player, in this case for mob
|
||||
pos.unwrap_or(Vector3::new(
|
||||
f64::from(info.spawn_x) + 0.5,
|
||||
f64::from(info.spawn_y) + 1.0,
|
||||
f64::from(info.spawn_z) + 0.5,
|
||||
))
|
||||
};
|
||||
|
||||
(world, pos)
|
||||
}
|
||||
CommandSender::Player(player) => {
|
||||
let pos = pos.unwrap_or(player.get_entity().pos.load());
|
||||
|
||||
(player.world(), pos)
|
||||
}
|
||||
CommandSender::CommandBlock(c, w) => {
|
||||
(w.clone(), c.get_position().to_centered_f64())
|
||||
}
|
||||
};
|
||||
|
||||
world.spawn_particle(pos, delta, speed, count, *particle);
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_PARTICLE_SUCCESS,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_PARTICLE_SUCCESS,
|
||||
[
|
||||
TextComponent::text(format!("{particle:?}")),
|
||||
TextComponent::text(count.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
|
||||
// TODO: Add `viewers` arguments and change the logic for this result
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(ARG_NAME, ParticleArgumentConsumer)
|
||||
.execute(Executor)
|
||||
.then(
|
||||
argument(ARG_POS, Position3DArgumentConsumer)
|
||||
.execute(Executor)
|
||||
.then(
|
||||
argument(ARG_DELTA, Position3DArgumentConsumer)
|
||||
.execute(Executor)
|
||||
.then(
|
||||
argument(
|
||||
ARG_SPEED,
|
||||
BoundedNumArgumentConsumer::<f32>::new().min(0.0),
|
||||
)
|
||||
.execute(Executor)
|
||||
.then(
|
||||
argument(
|
||||
ARG_COUNT,
|
||||
BoundedNumArgumentConsumer::<i32>::new().min(0),
|
||||
)
|
||||
.execute(Executor),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
// TODO: Add NBT
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,750 @@
|
||||
use pumpkin_data::chunk_gen_settings::GenerationSettings;
|
||||
use pumpkin_data::placed_feature::PlacedFeature as PlacedFeatureKey;
|
||||
use pumpkin_data::structures::{Structure, StructureKeys, StructureType};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_data::{Block, BlockStateId, Mirror, Rotation};
|
||||
use pumpkin_util::identifier::Identifier;
|
||||
use pumpkin_util::math::block_box::BlockBox;
|
||||
use pumpkin_util::math::position::BlockPos;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
use pumpkin_util::random::hash_block_pos;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_world::generation::proto_chunk::ProtoChunk;
|
||||
use pumpkin_world::world::{BlockAccessor, WorldPortalExt};
|
||||
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command, literal};
|
||||
use crate::command::argument_types::coordinates::block_pos::BlockPosArgumentType;
|
||||
use crate::command::argument_types::core::integer::IntegerArgumentType;
|
||||
use crate::command::argument_types::identifier::IdentifierArgumentType;
|
||||
use crate::command::argument_types::placed_feature::PlacedFeatureNameArgumentType;
|
||||
use crate::command::argument_types::pool::PoolNameArgumentType;
|
||||
use crate::command::argument_types::structure::StructureNameArgumentType;
|
||||
use crate::command::argument_types::template::TemplateNameArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use crate::world::block_placer::WorldBlockPlacer;
|
||||
use pumpkin_world::generation::feature::configured_features::CONFIGURED_FEATURES;
|
||||
use pumpkin_world::generation::feature::placed_features::{Feature, PLACED_FEATURES};
|
||||
use pumpkin_world::generation::structure::structures::StructureGeneratorContext;
|
||||
use pumpkin_world::generation::structure::structures::jigsaw::{
|
||||
PoolElementStructurePiece, place_pool_element_templates,
|
||||
};
|
||||
use pumpkin_world::generation::structure::structures::jigsaw_placement::{
|
||||
DimensionPadding, JigsawPlacement, LiquidSettings, MaxDistance, PoolAliasLookup,
|
||||
};
|
||||
use pumpkin_world::generation::structure::template::BlockPlacer;
|
||||
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::random::RandomGenerator;
|
||||
use pumpkin_util::random::legacy_rand::LegacyRand;
|
||||
|
||||
const DESCRIPTION: &str = "Places a structure template in the world.";
|
||||
const PERMISSION: &str = "minecraft:command.place";
|
||||
|
||||
static TEMPLATE_NOT_FOUND: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_PLACE_TEMPLATE_INVALID,
|
||||
"commands.place.template.invalid",
|
||||
);
|
||||
static JIGSAW_FAILED: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_PLACE_JIGSAW_FAILED,
|
||||
"commands.place.jigsaw.failed",
|
||||
);
|
||||
static STRUCTURE_INVALID: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_PLACE_STRUCTURE_INVALID,
|
||||
"commands.place.structure.invalid",
|
||||
);
|
||||
static FEATURE_INVALID: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_PLACE_FEATURE_INVALID,
|
||||
"commands.place.feature.invalid",
|
||||
);
|
||||
|
||||
const CHUNK_DIM: i32 = 16;
|
||||
|
||||
/// Clamps a world Y into valid chunk bounds, placing the surface one block below the target.
|
||||
fn ground_y(block_y: i32, chunk_min_y: i32, chunk_height: i32) -> i32 {
|
||||
(block_y - 1).clamp(chunk_min_y, chunk_min_y + chunk_height - 1)
|
||||
}
|
||||
|
||||
/// Vanilla-style chunk-seed derivation used by structure pieces and feature generators.
|
||||
const fn chunk_population_seed(cx: i32, cz: i32, world_seed: u64) -> u64 {
|
||||
(cx as i64)
|
||||
.wrapping_mul(341873128712)
|
||||
.wrapping_add((cz as i64).wrapping_mul(132897987541))
|
||||
.wrapping_add(world_seed as i64) as u64
|
||||
}
|
||||
|
||||
/// Minimal `WorldPortalExt` implementation for synthetic chunk placement.
|
||||
struct CommandBlockRegistry;
|
||||
|
||||
impl WorldPortalExt for CommandBlockRegistry {
|
||||
fn can_place_at(
|
||||
&self,
|
||||
_block: &pumpkin_data::Block,
|
||||
_state: &pumpkin_data::BlockState,
|
||||
_block_accessor: &dyn BlockAccessor,
|
||||
_block_pos: &BlockPos,
|
||||
) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn mirror(
|
||||
&self,
|
||||
block: &pumpkin_data::Block,
|
||||
state_id: BlockStateId,
|
||||
mirror: Mirror,
|
||||
) -> &'static pumpkin_data::BlockState {
|
||||
block.mirror(state_id, mirror)
|
||||
}
|
||||
|
||||
fn rotate(
|
||||
&self,
|
||||
block: &pumpkin_data::Block,
|
||||
state_id: BlockStateId,
|
||||
rotation: Rotation,
|
||||
) -> &'static pumpkin_data::BlockState {
|
||||
block.rotate(state_id, rotation)
|
||||
}
|
||||
|
||||
fn spawn_mobs_for_chunk_generation(
|
||||
&self,
|
||||
_cache: &mut dyn pumpkin_world::generation::proto_chunk::GenerationCache,
|
||||
_biome: &'static pumpkin_data::biome::Biome,
|
||||
_chunk_x: i32,
|
||||
_chunk_z: i32,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlaceTemplateExecutor;
|
||||
|
||||
impl CommandExecutor for PlaceTemplateExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let template_name = context.get_argument::<String>("template")?.clone();
|
||||
|
||||
let block_pos =
|
||||
BlockPosArgumentType::get_block_pos(context, "pos").unwrap_or_else(|_| {
|
||||
let p = context.source.position;
|
||||
BlockPos::new(p.x as i32, p.y as i32, p.z as i32)
|
||||
});
|
||||
|
||||
let template_name = template_name
|
||||
.strip_prefix("minecraft:")
|
||||
.unwrap_or(&template_name)
|
||||
.to_string();
|
||||
let Some(template) =
|
||||
pumpkin_world::generation::structure::template::get_template(&template_name)
|
||||
else {
|
||||
return Err(TEMPLATE_NOT_FOUND
|
||||
.create_without_context(TextComponent::text(template_name.clone())));
|
||||
};
|
||||
|
||||
let mut placer = WorldBlockPlacer::new(context.world());
|
||||
pumpkin_world::generation::structure::template::place_template(
|
||||
&mut placer,
|
||||
&template,
|
||||
block_pos.0,
|
||||
(0, 0),
|
||||
Rotation::None,
|
||||
false,
|
||||
false,
|
||||
&[],
|
||||
None,
|
||||
);
|
||||
|
||||
placer.finalize();
|
||||
context
|
||||
.world()
|
||||
.queue_block_updates(&placer.changed_positions)
|
||||
.await;
|
||||
context.world().flush_block_updates().await;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate(
|
||||
translation::java::COMMANDS_PLACE_TEMPLATE_SUCCESS,
|
||||
[
|
||||
TextComponent::text(template_name.clone()),
|
||||
TextComponent::text(block_pos.0.x.to_string()),
|
||||
TextComponent::text(block_pos.0.y.to_string()),
|
||||
TextComponent::text(block_pos.0.z.to_string()),
|
||||
],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct PlaceJigsawExecutor;
|
||||
|
||||
impl CommandExecutor for PlaceJigsawExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let pool = context.get_argument::<Identifier>("pool")?.to_string();
|
||||
let target = context.get_argument::<Identifier>("target")?.to_string();
|
||||
let max_depth = *context.get_argument::<i32>("max_depth")?;
|
||||
|
||||
let block_pos =
|
||||
BlockPosArgumentType::get_block_pos(context, "pos").unwrap_or_else(|_| {
|
||||
let p = context.source.position;
|
||||
BlockPos::new(p.x as i32, p.y as i32, p.z as i32)
|
||||
});
|
||||
|
||||
let (piece_count, placer) = {
|
||||
let seed = hash_block_pos(block_pos.0.x, block_pos.0.y, block_pos.0.z) as u64;
|
||||
let random = RandomGenerator::Legacy(LegacyRand::from_seed(seed));
|
||||
let world_gen = &context.world().level.world_gen;
|
||||
let settings = GenerationSettings::from_dimension(world_gen.dimension());
|
||||
let mut structure_context = StructureGeneratorContext {
|
||||
seed: seed as i64,
|
||||
chunk_x: 0,
|
||||
chunk_z: 0,
|
||||
random,
|
||||
sea_level: settings.sea_level,
|
||||
min_y: world_gen.dimension().min_y,
|
||||
height_sampler: None,
|
||||
structure_key: None,
|
||||
};
|
||||
|
||||
let position = JigsawPlacement::add_pieces(
|
||||
&mut structure_context,
|
||||
&pool,
|
||||
Some(&target),
|
||||
max_depth,
|
||||
block_pos,
|
||||
false,
|
||||
false,
|
||||
&MaxDistance::new(128),
|
||||
&DimensionPadding::ZERO,
|
||||
LiquidSettings::ApplyWaterlog,
|
||||
&PoolAliasLookup::default(),
|
||||
)
|
||||
.ok_or_else(|| {
|
||||
JIGSAW_FAILED.create_without_context(TextComponent::text(pool.clone()))
|
||||
})?;
|
||||
|
||||
let collector = position.collector.lock().unwrap();
|
||||
let piece_count = collector.pieces.len();
|
||||
|
||||
let mut placer = WorldBlockPlacer::new(context.world());
|
||||
for piece in &collector.pieces {
|
||||
if let Some(jigsaw_piece) =
|
||||
piece.as_any().downcast_ref::<PoolElementStructurePiece>()
|
||||
{
|
||||
place_pool_element_templates(jigsaw_piece, &mut placer, None);
|
||||
}
|
||||
}
|
||||
|
||||
(piece_count, placer)
|
||||
};
|
||||
|
||||
placer.finalize();
|
||||
context
|
||||
.world()
|
||||
.queue_block_updates(&placer.changed_positions)
|
||||
.await;
|
||||
context.world().flush_block_updates().await;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate(
|
||||
translation::java::COMMANDS_PLACE_JIGSAW_SUCCESS,
|
||||
[
|
||||
TextComponent::text(piece_count.to_string()),
|
||||
TextComponent::text(block_pos.0.x.to_string()),
|
||||
TextComponent::text(block_pos.0.y.to_string()),
|
||||
TextComponent::text(block_pos.0.z.to_string()),
|
||||
],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct PlaceStructureExecutor;
|
||||
|
||||
#[allow(clippy::too_many_lines)]
|
||||
impl CommandExecutor for PlaceStructureExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let structure_id = context.get_argument::<Identifier>("structure")?;
|
||||
let structure_name = structure_id.to_string();
|
||||
|
||||
let key = StructureKeys::from_name(&structure_name).ok_or_else(|| {
|
||||
STRUCTURE_INVALID
|
||||
.create_without_context(TextComponent::text(structure_name.clone()))
|
||||
})?;
|
||||
|
||||
let structure = Structure::get(&key);
|
||||
|
||||
let block_pos =
|
||||
BlockPosArgumentType::get_block_pos(context, "pos").unwrap_or_else(|_| {
|
||||
let p = context.source.position;
|
||||
BlockPos::new(p.x as i32, p.y as i32, p.z as i32)
|
||||
});
|
||||
|
||||
let seed = hash_block_pos(block_pos.0.x, block_pos.0.y, block_pos.0.z) as u64;
|
||||
|
||||
let (_piece_count, placer) = {
|
||||
let world_gen = context.world().level.world_gen.clone();
|
||||
let settings = GenerationSettings::from_dimension(world_gen.dimension());
|
||||
|
||||
if structure.structure_type == StructureType::Jigsaw {
|
||||
let pool = structure.start_pool.ok_or_else(|| {
|
||||
STRUCTURE_INVALID
|
||||
.create_without_context(TextComponent::text(structure_name.clone()))
|
||||
})?;
|
||||
let size = structure.size.ok_or_else(|| {
|
||||
STRUCTURE_INVALID
|
||||
.create_without_context(TextComponent::text(structure_name.clone()))
|
||||
})?;
|
||||
|
||||
let random = RandomGenerator::Legacy(LegacyRand::from_seed(seed));
|
||||
|
||||
let position = JigsawPlacement::add_pieces(
|
||||
&mut StructureGeneratorContext {
|
||||
seed: seed as i64,
|
||||
chunk_x: block_pos.0.x >> 4,
|
||||
chunk_z: block_pos.0.z >> 4,
|
||||
random,
|
||||
sea_level: settings.sea_level,
|
||||
min_y: world_gen.dimension().min_y,
|
||||
height_sampler: None,
|
||||
structure_key: Some(key),
|
||||
},
|
||||
pool,
|
||||
structure.start_jigsaw_name,
|
||||
size,
|
||||
block_pos,
|
||||
structure.use_expansion_hack.unwrap_or(false),
|
||||
structure.project_start_to_heightmap.is_some(),
|
||||
&MaxDistance::new(structure.max_distance_from_center.unwrap_or(128)),
|
||||
&DimensionPadding::ZERO,
|
||||
LiquidSettings::ApplyWaterlog,
|
||||
&PoolAliasLookup::default(),
|
||||
)
|
||||
.ok_or_else(|| {
|
||||
JIGSAW_FAILED
|
||||
.create_without_context(TextComponent::text(structure_name.clone()))
|
||||
})?;
|
||||
|
||||
let collector = position.collector.lock().unwrap();
|
||||
let piece_count = collector.pieces.len();
|
||||
|
||||
let mut placer = WorldBlockPlacer::new(context.world());
|
||||
for piece in &collector.pieces {
|
||||
if let Some(jigsaw_piece) =
|
||||
piece.as_any().downcast_ref::<PoolElementStructurePiece>()
|
||||
{
|
||||
place_pool_element_templates(jigsaw_piece, &mut placer, None);
|
||||
}
|
||||
}
|
||||
|
||||
(piece_count, placer)
|
||||
} else {
|
||||
let random = RandomGenerator::Legacy(LegacyRand::from_seed(seed));
|
||||
|
||||
let position =
|
||||
pumpkin_world::generation::structure::generate_structure_position(
|
||||
&key,
|
||||
structure,
|
||||
StructureGeneratorContext {
|
||||
seed: seed as i64,
|
||||
chunk_x: block_pos.0.x >> 4,
|
||||
chunk_z: block_pos.0.z >> 4,
|
||||
random,
|
||||
sea_level: settings.sea_level,
|
||||
min_y: world_gen.dimension().min_y,
|
||||
height_sampler: None,
|
||||
structure_key: Some(key),
|
||||
},
|
||||
)
|
||||
.ok_or_else(|| {
|
||||
STRUCTURE_INVALID
|
||||
.create_without_context(TextComponent::text(structure_name.clone()))
|
||||
})?;
|
||||
|
||||
let mut collector = position.collector.lock().unwrap();
|
||||
let piece_count = collector.pieces.len();
|
||||
|
||||
let mut placer = WorldBlockPlacer::new(context.world());
|
||||
|
||||
for piece in &collector.pieces {
|
||||
if let Some(jigsaw_piece) =
|
||||
piece.as_any().downcast_ref::<PoolElementStructurePiece>()
|
||||
{
|
||||
place_pool_element_templates(jigsaw_piece, &mut placer, None);
|
||||
}
|
||||
}
|
||||
|
||||
let has_non_jigsaw = collector.pieces.iter().any(|p| {
|
||||
p.as_any()
|
||||
.downcast_ref::<PoolElementStructurePiece>()
|
||||
.is_none()
|
||||
});
|
||||
|
||||
if has_non_jigsaw {
|
||||
let reg = CommandBlockRegistry;
|
||||
|
||||
let mut min_x = i32::MAX;
|
||||
let mut min_z = i32::MAX;
|
||||
let mut max_x = i32::MIN;
|
||||
let mut max_z = i32::MIN;
|
||||
|
||||
for piece in &collector.pieces {
|
||||
if piece
|
||||
.as_any()
|
||||
.downcast_ref::<PoolElementStructurePiece>()
|
||||
.is_none()
|
||||
{
|
||||
let bb = piece.bounding_box();
|
||||
min_x = min_x.min(bb.min.x);
|
||||
min_z = min_z.min(bb.min.z);
|
||||
max_x = max_x.max(bb.max.x);
|
||||
max_z = max_z.max(bb.max.z);
|
||||
}
|
||||
}
|
||||
|
||||
let start_cx = min_x >> 4;
|
||||
let end_cx = max_x >> 4;
|
||||
let start_cz = min_z >> 4;
|
||||
let end_cz = max_z >> 4;
|
||||
|
||||
for cx in start_cx..=end_cx {
|
||||
for cz in start_cz..=end_cz {
|
||||
let mut chunk = ProtoChunk::new(cx, cz, &world_gen);
|
||||
let chunk_min_y = chunk.bottom_y() as i32;
|
||||
let chunk_height = chunk.height() as i32;
|
||||
let surface_y = ground_y(block_pos.0.y, chunk_min_y, chunk_height);
|
||||
|
||||
// Seed heightmaps and fill below-surface with stone so
|
||||
// pieces that carve through solid terrain have material
|
||||
let ground = surface_y as i16;
|
||||
chunk.flat_surface_height_map = [ground; 256];
|
||||
chunk.flat_ocean_floor_height_map = [ground; 256];
|
||||
chunk.flat_motion_blocking_height_map = [ground; 256];
|
||||
chunk.flat_motion_blocking_no_leaves_height_map = [ground; 256];
|
||||
|
||||
for x in 0..CHUNK_DIM {
|
||||
for z in 0..CHUNK_DIM {
|
||||
for y in chunk_min_y..surface_y {
|
||||
chunk.set_block_state(
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
Block::STONE.default_state,
|
||||
);
|
||||
}
|
||||
chunk.set_block_state(
|
||||
x,
|
||||
surface_y,
|
||||
z,
|
||||
Block::GRASS_BLOCK.default_state,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let chunk_box = BlockBox::new(
|
||||
cx << 4,
|
||||
chunk_min_y,
|
||||
cz << 4,
|
||||
(cx << 4) + CHUNK_DIM - 1,
|
||||
chunk_min_y + chunk_height - 1,
|
||||
(cz << 4) + CHUNK_DIM - 1,
|
||||
);
|
||||
|
||||
let snapshot =
|
||||
snapshot_blocks(&chunk, cx, cz, chunk_min_y, chunk_height);
|
||||
|
||||
let mut rng = RandomGenerator::Legacy(LegacyRand::from_seed(
|
||||
chunk_population_seed(cx, cz, seed),
|
||||
));
|
||||
|
||||
for piece in &mut collector.pieces {
|
||||
if piece.bounding_box().intersects(&chunk_box) {
|
||||
piece.place(
|
||||
&mut chunk,
|
||||
®,
|
||||
&mut rng,
|
||||
seed as i64,
|
||||
&chunk_box,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
apply_delta(
|
||||
&chunk,
|
||||
&snapshot,
|
||||
cx,
|
||||
cz,
|
||||
chunk_min_y,
|
||||
chunk_height,
|
||||
&mut placer,
|
||||
);
|
||||
|
||||
for nbt in chunk.pending_block_entities.drain(..) {
|
||||
placer.block_entity_nbts.push(nbt);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(piece_count, placer)
|
||||
}
|
||||
};
|
||||
|
||||
placer.finalize();
|
||||
context
|
||||
.world()
|
||||
.queue_block_updates(&placer.changed_positions)
|
||||
.await;
|
||||
context.world().flush_block_updates().await;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate(
|
||||
translation::java::COMMANDS_PLACE_STRUCTURE_SUCCESS,
|
||||
[
|
||||
TextComponent::text(structure_name),
|
||||
TextComponent::text(block_pos.0.x.to_string()),
|
||||
TextComponent::text(block_pos.0.y.to_string()),
|
||||
TextComponent::text(block_pos.0.z.to_string()),
|
||||
],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct PlaceFeatureExecutor;
|
||||
|
||||
impl CommandExecutor for PlaceFeatureExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let feature_id = context.get_argument::<Identifier>("feature")?;
|
||||
let feature_name = feature_id.to_string();
|
||||
|
||||
let key = PlacedFeatureKey::from_name(&feature_name).ok_or_else(|| {
|
||||
FEATURE_INVALID.create_without_context(TextComponent::text(feature_name.clone()))
|
||||
})?;
|
||||
|
||||
let placed = PLACED_FEATURES.get(&key).ok_or_else(|| {
|
||||
FEATURE_INVALID.create_without_context(TextComponent::text(feature_name.clone()))
|
||||
})?;
|
||||
|
||||
let configured = match &placed.feature {
|
||||
Feature::Named(name) => CONFIGURED_FEATURES.get(name).ok_or_else(|| {
|
||||
FEATURE_INVALID
|
||||
.create_without_context(TextComponent::text(feature_name.clone()))
|
||||
})?,
|
||||
Feature::Inlined(f) => f.as_ref(),
|
||||
};
|
||||
|
||||
let block_pos =
|
||||
BlockPosArgumentType::get_block_pos(context, "pos").unwrap_or_else(|_| {
|
||||
let p = context.source.position;
|
||||
BlockPos::new(p.x as i32, p.y as i32, p.z as i32)
|
||||
});
|
||||
|
||||
let world_gen = context.world().level.world_gen.clone();
|
||||
let cx = block_pos.0.x >> 4;
|
||||
let cz = block_pos.0.z >> 4;
|
||||
let mut chunk = ProtoChunk::new(cx, cz, &world_gen);
|
||||
let bottom_y = chunk.bottom_y();
|
||||
let height = chunk.height();
|
||||
let chunk_min_y = bottom_y as i32;
|
||||
let chunk_height = height as i32;
|
||||
let surface_y = ground_y(block_pos.0.y, chunk_min_y, chunk_height);
|
||||
|
||||
let ground = surface_y as i16;
|
||||
chunk.flat_surface_height_map = [ground; 256];
|
||||
chunk.flat_ocean_floor_height_map = [ground; 256];
|
||||
chunk.flat_motion_blocking_height_map = [ground; 256];
|
||||
chunk.flat_motion_blocking_no_leaves_height_map = [ground; 256];
|
||||
|
||||
// Feature generation runs against a synthetic solid terrain, not the
|
||||
// live chunk. Features that depend on existing air, caves, or fluids
|
||||
// may therefore differ from normal world generation.
|
||||
for x in 0..CHUNK_DIM {
|
||||
for z in 0..CHUNK_DIM {
|
||||
for y in chunk_min_y..surface_y {
|
||||
chunk.set_block_state(x, y, z, Block::STONE.default_state);
|
||||
}
|
||||
chunk.set_block_state(x, surface_y, z, Block::GRASS_BLOCK.default_state);
|
||||
}
|
||||
}
|
||||
|
||||
let snapshot = snapshot_blocks(&chunk, cx, cz, chunk_min_y, chunk_height);
|
||||
|
||||
let reg = CommandBlockRegistry;
|
||||
let seed = hash_block_pos(block_pos.0.x, block_pos.0.y, block_pos.0.z) as u64;
|
||||
let mut random = RandomGenerator::Legacy(LegacyRand::from_seed(seed));
|
||||
|
||||
configured.generate(
|
||||
&mut chunk,
|
||||
®,
|
||||
bottom_y,
|
||||
height,
|
||||
key,
|
||||
&mut random,
|
||||
block_pos,
|
||||
);
|
||||
|
||||
let mut placer = WorldBlockPlacer::new(context.world());
|
||||
apply_delta(
|
||||
&chunk,
|
||||
&snapshot,
|
||||
cx,
|
||||
cz,
|
||||
chunk_min_y,
|
||||
chunk_height,
|
||||
&mut placer,
|
||||
);
|
||||
|
||||
for nbt in chunk.pending_block_entities.drain(..) {
|
||||
placer.block_entity_nbts.push(nbt);
|
||||
}
|
||||
|
||||
placer.finalize();
|
||||
context
|
||||
.world()
|
||||
.queue_block_updates(&placer.changed_positions)
|
||||
.await;
|
||||
context.world().flush_block_updates().await;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate(
|
||||
translation::java::COMMANDS_PLACE_FEATURE_SUCCESS,
|
||||
[
|
||||
TextComponent::text(feature_name),
|
||||
TextComponent::text(block_pos.0.x.to_string()),
|
||||
TextComponent::text(block_pos.0.y.to_string()),
|
||||
TextComponent::text(block_pos.0.z.to_string()),
|
||||
],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot_blocks(
|
||||
chunk: &ProtoChunk,
|
||||
cx: i32,
|
||||
cz: i32,
|
||||
min_y: i32,
|
||||
height: i32,
|
||||
) -> Vec<BlockStateId> {
|
||||
let mut snap = Vec::with_capacity((CHUNK_DIM * height * CHUNK_DIM) as usize);
|
||||
for x in 0..CHUNK_DIM {
|
||||
for y in min_y..min_y + height {
|
||||
for z in 0..CHUNK_DIM {
|
||||
snap.push(chunk.get_block_state(&Vector3::new((cx << 4) + x, y, (cz << 4) + z)));
|
||||
}
|
||||
}
|
||||
}
|
||||
snap
|
||||
}
|
||||
|
||||
fn apply_delta(
|
||||
chunk: &ProtoChunk,
|
||||
snapshot: &[BlockStateId],
|
||||
cx: i32,
|
||||
cz: i32,
|
||||
min_y: i32,
|
||||
height: i32,
|
||||
placer: &mut WorldBlockPlacer<'_>,
|
||||
) {
|
||||
// The synthetic chunk is seeded with terrain so structure pieces can carve
|
||||
// against it. Applying the delta therefore intentionally propagates air
|
||||
// changes too, which can replace real terrain where a piece carved that
|
||||
// synthetic stone.
|
||||
let mut idx = 0usize;
|
||||
for x in 0..CHUNK_DIM {
|
||||
for y in min_y..min_y + height {
|
||||
for z in 0..CHUNK_DIM {
|
||||
let pos = Vector3::new((cx << 4) + x, y, (cz << 4) + z);
|
||||
let new_id = chunk.get_block_state(&pos);
|
||||
if new_id != snapshot[idx] {
|
||||
placer.set_block_state(&pos, new_id.to_state());
|
||||
}
|
||||
idx += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("place", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.then(
|
||||
literal("template").then(
|
||||
argument("template", TemplateNameArgumentType)
|
||||
.executes(PlaceTemplateExecutor)
|
||||
.then(
|
||||
argument("pos", BlockPosArgumentType).executes(PlaceTemplateExecutor),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("jigsaw").then(
|
||||
argument("pool", PoolNameArgumentType).then(
|
||||
argument("target", IdentifierArgumentType).then(
|
||||
argument("max_depth", IntegerArgumentType::new(1, 20))
|
||||
.executes(PlaceJigsawExecutor)
|
||||
.then(
|
||||
argument("pos", BlockPosArgumentType)
|
||||
.executes(PlaceJigsawExecutor),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("structure").then(
|
||||
argument("structure", StructureNameArgumentType)
|
||||
.executes(PlaceStructureExecutor)
|
||||
.then(
|
||||
argument("pos", BlockPosArgumentType).executes(PlaceStructureExecutor),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("feature").then(
|
||||
argument("feature", PlacedFeatureNameArgumentType)
|
||||
.executes(PlaceFeatureExecutor)
|
||||
.then(argument("pos", BlockPosArgumentType).executes(PlaceFeatureExecutor)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use pumpkin_data::sound::SoundCategory;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use rand::{RngExt, rng};
|
||||
|
||||
use crate::entity::EntityBase;
|
||||
use crate::{
|
||||
command::{
|
||||
CommandExecutor, CommandResult, CommandSender,
|
||||
args::{
|
||||
Arg, ConsumedArgs, FindArg, bounded_num::BoundedNumArgumentConsumer,
|
||||
players::PlayersArgumentConsumer, position_3d::Position3DArgumentConsumer,
|
||||
sound::SoundArgumentConsumer, sound_category::SoundCategoryArgumentConsumer,
|
||||
},
|
||||
dispatcher::CommandError,
|
||||
tree::{CommandTree, builder::argument},
|
||||
},
|
||||
entity::player::Player,
|
||||
};
|
||||
|
||||
/// Command: playsound <sound> [<source>] [<targets>] [<pos>] [<volume>] [<pitch>] [<minVolume>]
|
||||
///
|
||||
/// Plays a sound at specified position for target players.
|
||||
/// - sound: The sound resource location to play
|
||||
/// - source: Sound category (master, music, record, etc.)
|
||||
/// - targets: Players who will hear the sound
|
||||
/// - pos: Position to play the sound from
|
||||
/// - volume: Sound volume (>=0, default: 1.0)
|
||||
/// - pitch: Sound pitch (0.5-2.0, default: 1.0)
|
||||
/// - minVolume: Minimum volume for distant players (0.0-1.0, default: 0.0)
|
||||
const NAMES: [&str; 1] = ["playsound"];
|
||||
const DESCRIPTION: &str = "Plays a sound at a position.";
|
||||
const ARG_SOUND: &str = "sound";
|
||||
const ARG_SOURCE: &str = "source";
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
const ARG_POS: &str = "pos";
|
||||
const ARG_VOLUME: &str = "volume";
|
||||
const ARG_PITCH: &str = "pitch";
|
||||
const ARG_MIN_VOLUME: &str = "minVolume";
|
||||
|
||||
// Volume must be >= 0, no upper limit
|
||||
const fn volume_consumer() -> BoundedNumArgumentConsumer<f32> {
|
||||
BoundedNumArgumentConsumer::new().name(ARG_VOLUME).min(0.0)
|
||||
}
|
||||
|
||||
// Pitch must be between 0.0 and 2.0
|
||||
// Values below 0.5 are treated as 0.5
|
||||
const fn pitch_consumer() -> BoundedNumArgumentConsumer<f32> {
|
||||
BoundedNumArgumentConsumer::new()
|
||||
.name(ARG_PITCH)
|
||||
.min(0.0)
|
||||
.max(2.0)
|
||||
}
|
||||
|
||||
// Minimum volume must be between 0.0 and 1.0
|
||||
// Controls the volume for players outside normal hearing range
|
||||
const fn min_volume_consumer() -> BoundedNumArgumentConsumer<f32> {
|
||||
BoundedNumArgumentConsumer::new()
|
||||
.name(ARG_MIN_VOLUME)
|
||||
.min(0.0)
|
||||
.max(1.0)
|
||||
}
|
||||
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
// Get required sound argument
|
||||
let sound = SoundArgumentConsumer::find_arg(args, ARG_SOUND)?;
|
||||
|
||||
// Get optional sound category, defaults to Master
|
||||
let source = args
|
||||
.get(ARG_SOURCE)
|
||||
.map_or(SoundCategory::Master, |arg| match arg {
|
||||
Arg::SoundCategory(category) => *category,
|
||||
_ => SoundCategory::Master,
|
||||
});
|
||||
|
||||
// Get target players, defaults to sender if not specified
|
||||
let targets: &[Arc<Player>] = match (
|
||||
PlayersArgumentConsumer::find_arg(args, ARG_TARGETS),
|
||||
sender.as_player(),
|
||||
) {
|
||||
(Ok(players), _) => players,
|
||||
(_, Some(player)) => &[player],
|
||||
(_, _) => &[],
|
||||
};
|
||||
|
||||
// Get optional position, defaults to target's position
|
||||
let position = Position3DArgumentConsumer::find_arg(args, ARG_POS).ok();
|
||||
|
||||
// Get optional volume parameter
|
||||
let volume = match BoundedNumArgumentConsumer::<f32>::find_arg(args, ARG_VOLUME) {
|
||||
Ok(Ok(v)) => v,
|
||||
_ => 1.0, // Default volume
|
||||
};
|
||||
|
||||
// Get optional pitch parameter
|
||||
let pitch = match BoundedNumArgumentConsumer::<f32>::find_arg(args, ARG_PITCH) {
|
||||
Ok(Ok(p)) => p.max(0.5), // Values below 0.5 are clamped
|
||||
_ => 1.0, // Default pitch
|
||||
};
|
||||
|
||||
// Get optional minimum volume (currently unused in implementation)
|
||||
let min_volume = match BoundedNumArgumentConsumer::<f32>::find_arg(args, ARG_MIN_VOLUME)
|
||||
{
|
||||
Ok(Ok(v)) => v,
|
||||
_ => 0.0, // Default minimum volume
|
||||
};
|
||||
|
||||
// Use same random seed for all targets to ensure sound synchronization
|
||||
let seed = rng().random::<f64>();
|
||||
|
||||
// Track how many players actually received the sound
|
||||
let mut players_who_heard = 0;
|
||||
|
||||
// Play sound for each target player
|
||||
for target in targets {
|
||||
let pos = position.unwrap_or(target.living_entity.entity.pos.load());
|
||||
|
||||
// Check if player can hear the sound based on volume and distance
|
||||
let player_pos = target.living_entity.entity.pos.load();
|
||||
let distance = player_pos.squared_distance_to_vec(&pos);
|
||||
let max_distance: f64 = (16.0 * volume).into(); // 16 blocks is base distance at volume 1.0
|
||||
|
||||
if distance <= max_distance || min_volume > 0.0 {
|
||||
target
|
||||
.play_sound(sound as u16, source, &pos, volume, pitch, seed)
|
||||
.await;
|
||||
players_who_heard += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Send appropriate message based on results
|
||||
if players_who_heard == 0 {
|
||||
Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_PLAYSOUND_FAILED,
|
||||
translation::java::COMMANDS_PLAYSOUND_FAILED,
|
||||
[],
|
||||
)))
|
||||
} else {
|
||||
let sound_name = sound.to_name();
|
||||
if players_who_heard == 1 {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_PLAYSOUND_SUCCESS_SINGLE,
|
||||
translation::bedrock::COMMANDS_PLAYSOUND_SUCCESS,
|
||||
[
|
||||
TextComponent::text(sound_name),
|
||||
targets[0].get_display_name().await,
|
||||
],
|
||||
))
|
||||
.await;
|
||||
} else {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_PLAYSOUND_SUCCESS_MULTIPLE,
|
||||
translation::bedrock::COMMANDS_PLAYSOUND_SUCCESS,
|
||||
[
|
||||
TextComponent::text(sound_name),
|
||||
TextComponent::text(players_who_heard.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(players_who_heard)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(ARG_SOUND, SoundArgumentConsumer)
|
||||
.then(
|
||||
argument(ARG_SOURCE, SoundCategoryArgumentConsumer)
|
||||
.then(
|
||||
argument(ARG_TARGETS, PlayersArgumentConsumer)
|
||||
.then(
|
||||
argument(ARG_POS, Position3DArgumentConsumer)
|
||||
.then(
|
||||
argument(ARG_VOLUME, volume_consumer())
|
||||
.then(
|
||||
argument(ARG_PITCH, pitch_consumer())
|
||||
.then(
|
||||
argument(
|
||||
ARG_MIN_VOLUME,
|
||||
min_volume_consumer(),
|
||||
)
|
||||
.execute(Executor),
|
||||
)
|
||||
.execute(Executor),
|
||||
)
|
||||
.execute(Executor),
|
||||
)
|
||||
.execute(Executor),
|
||||
)
|
||||
.execute(Executor),
|
||||
)
|
||||
.execute(Executor),
|
||||
)
|
||||
.execute(Executor),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
use std::path::Path;
|
||||
|
||||
use pumpkin_util::{
|
||||
PermissionLvl,
|
||||
text::{TextComponent, color::NamedColor, hover::HoverEvent},
|
||||
};
|
||||
|
||||
use crate::command::{
|
||||
CommandExecutor, CommandResult, CommandSender,
|
||||
args::{Arg, ConsumedArgs, simple::SimpleArgConsumer},
|
||||
dispatcher::CommandError,
|
||||
tree::{
|
||||
CommandTree,
|
||||
builder::{argument, literal, require},
|
||||
},
|
||||
};
|
||||
|
||||
use crate::command::CommandError::InvalidConsumption;
|
||||
|
||||
const NAMES: [&str; 1] = ["plugin"];
|
||||
|
||||
const DESCRIPTION: &str = "Manage plugins.";
|
||||
|
||||
const PLUGIN_NAME: &str = "plugin_name";
|
||||
|
||||
struct ListExecutor;
|
||||
|
||||
impl CommandExecutor for ListExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let plugins = server.plugin_manager.active_plugins().await;
|
||||
|
||||
let message_text = if plugins.is_empty() {
|
||||
"There are no loaded plugins.".to_string()
|
||||
} else if plugins.len() == 1 {
|
||||
"There is 1 plugin loaded:\n".to_string()
|
||||
} else {
|
||||
format!("There are {} plugins loaded:\n", plugins.len())
|
||||
};
|
||||
let mut message = TextComponent::text(message_text);
|
||||
|
||||
for (i, metadata) in plugins.iter().enumerate() {
|
||||
let fmt = if i == plugins.len() - 1 {
|
||||
metadata.name.clone()
|
||||
} else {
|
||||
format!("{}, ", metadata.name)
|
||||
};
|
||||
let hover_text = format!(
|
||||
"Version: {}\nAuthors: {}\nDescription: {}",
|
||||
metadata.version,
|
||||
metadata.authors.join(", "),
|
||||
metadata.description
|
||||
);
|
||||
let component = TextComponent::text(fmt)
|
||||
.color_named(NamedColor::Green)
|
||||
.hover_event(HoverEvent::show_text(TextComponent::text(hover_text)));
|
||||
|
||||
message = message.add_child(component);
|
||||
}
|
||||
|
||||
sender.send_message(message).await;
|
||||
|
||||
Ok(plugins.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct LoadExecutor;
|
||||
|
||||
impl CommandExecutor for LoadExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Simple(plugin_name)) = args.get(PLUGIN_NAME) else {
|
||||
return Err(InvalidConsumption(Some(PLUGIN_NAME.into())));
|
||||
};
|
||||
|
||||
if server.plugin_manager.is_plugin_active(plugin_name).await {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(format!(
|
||||
"Plugin {plugin_name} is already loaded"
|
||||
))));
|
||||
}
|
||||
|
||||
let Some(server_arc) = sender
|
||||
.world_or_first(server)
|
||||
.and_then(|w| w.server.upgrade())
|
||||
else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(
|
||||
"Failed to get server instance",
|
||||
)));
|
||||
};
|
||||
|
||||
let result = server
|
||||
.plugin_manager
|
||||
.try_load_plugin(&server_arc, Path::new(plugin_name))
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(()) => {
|
||||
sender
|
||||
.send_message(
|
||||
TextComponent::text(format!(
|
||||
"Plugin {plugin_name} loaded successfully"
|
||||
))
|
||||
.color_named(NamedColor::Green),
|
||||
)
|
||||
.await;
|
||||
Ok(1)
|
||||
}
|
||||
Err(e) => Err(CommandError::CommandFailed(TextComponent::text(format!(
|
||||
"Failed to load plugin {plugin_name}: {e}"
|
||||
)))),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct UnloadExecutor;
|
||||
|
||||
impl CommandExecutor for UnloadExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Simple(plugin_name)) = args.get(PLUGIN_NAME) else {
|
||||
return Err(InvalidConsumption(Some(PLUGIN_NAME.into())));
|
||||
};
|
||||
|
||||
if !server.plugin_manager.is_plugin_active(plugin_name).await {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(format!(
|
||||
"Plugin {plugin_name} is not loaded"
|
||||
))));
|
||||
}
|
||||
|
||||
let result = server.plugin_manager.unload_plugin(plugin_name).await;
|
||||
|
||||
match result {
|
||||
Ok(()) => {
|
||||
sender
|
||||
.send_message(
|
||||
TextComponent::text(format!(
|
||||
"Plugin {plugin_name} unloaded successfully",
|
||||
))
|
||||
.color_named(NamedColor::Green),
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
}
|
||||
Err(e) => Err(CommandError::CommandFailed(TextComponent::text(format!(
|
||||
"Failed to unload plugin {plugin_name}: {e}"
|
||||
)))),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct HotReloadExecutor(bool);
|
||||
|
||||
impl CommandExecutor for HotReloadExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let enabled = self.0;
|
||||
|
||||
if enabled {
|
||||
let Some(server_arc) = sender
|
||||
.world_or_first(server)
|
||||
.and_then(|w| w.server.upgrade())
|
||||
else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(
|
||||
"Failed to get server instance",
|
||||
)));
|
||||
};
|
||||
|
||||
if let Err(e) = server.plugin_manager.start_watcher(&server_arc).await {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(format!(
|
||||
"Failed to start plugin watcher: {e}"
|
||||
))));
|
||||
}
|
||||
|
||||
sender
|
||||
.send_message(
|
||||
TextComponent::text("Hot reloading has been enabled.")
|
||||
.color_named(NamedColor::Green),
|
||||
)
|
||||
.await;
|
||||
sender
|
||||
.send_message(
|
||||
TextComponent::text("WARNING: Hot reloading can impact performance and should only be enabled during plugin development.")
|
||||
.color_named(NamedColor::Red),
|
||||
)
|
||||
.await;
|
||||
} else {
|
||||
server.plugin_manager.stop_watcher().await;
|
||||
|
||||
sender
|
||||
.send_message(
|
||||
TextComponent::text("Hot reloading has been disabled.")
|
||||
.color_named(NamedColor::Green),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
require(|sender| sender.has_permission_lvl(PermissionLvl::Three))
|
||||
.then(
|
||||
literal("load")
|
||||
.then(argument(PLUGIN_NAME, SimpleArgConsumer).execute(LoadExecutor)),
|
||||
)
|
||||
.then(
|
||||
literal("unload")
|
||||
.then(argument(PLUGIN_NAME, SimpleArgConsumer).execute(UnloadExecutor)),
|
||||
)
|
||||
.then(
|
||||
literal("hotreload")
|
||||
.then(literal("enable").execute(HotReloadExecutor(true)))
|
||||
.then(literal("disable").execute(HotReloadExecutor(false))),
|
||||
)
|
||||
.then(literal("list").execute(ListExecutor)),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use pumpkin_util::text::{TextComponent, color::NamedColor, hover::HoverEvent};
|
||||
|
||||
use crate::command::{
|
||||
CommandExecutor, CommandResult, CommandSender, args::ConsumedArgs, tree::CommandTree,
|
||||
};
|
||||
|
||||
const NAMES: [&str; 2] = ["pl", "plugins"];
|
||||
|
||||
const DESCRIPTION: &str = "List all available plugins.";
|
||||
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let plugins = server.plugin_manager.active_plugins().await;
|
||||
|
||||
let message_text = if plugins.is_empty() {
|
||||
"There are no loaded plugins.".to_string()
|
||||
} else if plugins.len() == 1 {
|
||||
"There is 1 plugin loaded:\n".to_string()
|
||||
} else {
|
||||
format!("There are {} plugins loaded:\n", plugins.len())
|
||||
};
|
||||
let mut message = TextComponent::text(message_text);
|
||||
|
||||
for (i, metadata) in plugins.clone().into_iter().enumerate() {
|
||||
let fmt = if i == plugins.len() - 1 {
|
||||
metadata.name.clone()
|
||||
} else {
|
||||
format!("{}, ", metadata.name)
|
||||
};
|
||||
let hover_text = format!(
|
||||
"Version: {}\nAuthors: {}\nDescription: {}",
|
||||
metadata.version,
|
||||
metadata.authors.join(", "),
|
||||
metadata.description
|
||||
);
|
||||
let component = TextComponent::text(fmt)
|
||||
.color_named(NamedColor::Green)
|
||||
.hover_event(HoverEvent::show_text(TextComponent::text(hover_text)));
|
||||
message = message.add_child(component);
|
||||
}
|
||||
|
||||
sender.send_message(message).await;
|
||||
|
||||
Ok(plugins.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).execute(Executor)
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
use pumpkin_data::packet::CURRENT_MC_VERSION;
|
||||
use pumpkin_util::text::click::ClickEvent;
|
||||
use pumpkin_util::text::hover::HoverEvent;
|
||||
use pumpkin_util::text::{TextComponent, color::NamedColor};
|
||||
use pumpkin_util::translation::get_translation_text;
|
||||
use serde::Deserialize;
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::command::CommandResult;
|
||||
use crate::command::{CommandExecutor, CommandSender, args::ConsumedArgs, tree::CommandTree};
|
||||
|
||||
const NAMES: [&str; 2] = ["pumpkin", "version"];
|
||||
|
||||
const DESCRIPTION: &str = "Display information about Pumpkin.";
|
||||
|
||||
struct Executor;
|
||||
|
||||
const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
const GIT_HASH: &str = env!("GIT_HASH");
|
||||
const GIT_HASH_FULL: &str = env!("GIT_HASH_FULL");
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Contributor {
|
||||
login: String,
|
||||
}
|
||||
|
||||
fn fetch_all_contributors() -> Vec<Contributor> {
|
||||
let mut all_contributors = Vec::new();
|
||||
let mut next_url = Some(
|
||||
"https://api.github.com/repos/Pumpkin-MC/Pumpkin/contributors?per_page=100".to_string(),
|
||||
);
|
||||
|
||||
while let Some(url) = next_url {
|
||||
let response = ureq::get(&url).header("User-Agent", "Pumpkin-MC").call();
|
||||
|
||||
match response {
|
||||
Ok(mut res) => {
|
||||
if let Ok(contributors) = res.body_mut().read_json::<Vec<Contributor>>() {
|
||||
all_contributors.extend(contributors);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
let link_header = res.headers().get("link").map(|s| s.to_str().unwrap_or(""));
|
||||
|
||||
next_url = link_header.and_then(extract_next_url);
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
|
||||
if all_contributors.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
|
||||
all_contributors
|
||||
}
|
||||
|
||||
fn extract_next_url(header: &str) -> Option<String> {
|
||||
header
|
||||
.split(',')
|
||||
.find(|part| part.contains("rel=\"next\""))
|
||||
.and_then(|part| {
|
||||
let start = part.find('<')? + 1;
|
||||
let end = part.find('>')?;
|
||||
Some(part[start..end].to_string())
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Donator {
|
||||
name: String,
|
||||
tier: String,
|
||||
tier_slug: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct DonatorResponse {
|
||||
current: Vec<Donator>,
|
||||
#[allow(dead_code)]
|
||||
past: Vec<Donator>,
|
||||
}
|
||||
|
||||
fn tier_priority(tier_slug: &str, tier_name: &str) -> u32 {
|
||||
let s = format!("{tier_slug} {tier_name}").to_lowercase();
|
||||
|
||||
if s.contains("corporate platinum") || s.contains("corp platinum") {
|
||||
1
|
||||
} else if s.contains("corporate gold") || s.contains("corp gold") {
|
||||
2
|
||||
} else if s.contains("corporate silver") || s.contains("corp silver") {
|
||||
3
|
||||
} else if s.contains("corporate bronze") || s.contains("corp bronze") {
|
||||
4
|
||||
} else if s.contains("diamond") {
|
||||
5
|
||||
} else if s.contains("titanium") {
|
||||
6
|
||||
} else if s.contains("platinum") {
|
||||
7
|
||||
} else if s.contains("gold") {
|
||||
8
|
||||
} else if s.contains("silver") {
|
||||
9
|
||||
} else if s.contains("bronze") {
|
||||
10
|
||||
} else {
|
||||
11
|
||||
}
|
||||
}
|
||||
|
||||
fn tier_color(tier_slug: &str, tier_name: &str) -> NamedColor {
|
||||
let s = format!("{tier_slug} {tier_name}").to_lowercase();
|
||||
|
||||
if s.contains("diamond") {
|
||||
NamedColor::Aqua
|
||||
} else if s.contains("titanium") {
|
||||
NamedColor::DarkAqua
|
||||
} else if s.contains("platinum") {
|
||||
NamedColor::LightPurple
|
||||
} else if s.contains("gold") {
|
||||
NamedColor::Gold
|
||||
} else if s.contains("silver") {
|
||||
NamedColor::Gray
|
||||
} else if s.contains("bronze") {
|
||||
NamedColor::DarkRed
|
||||
} else {
|
||||
NamedColor::White
|
||||
}
|
||||
}
|
||||
|
||||
fn fetch_donators_hover() -> TextComponent {
|
||||
let url = "https://market.pumpkinmc.org/api/v1/rest/donators";
|
||||
let response = ureq::get(url).header("User-Agent", "Pumpkin-MC").call();
|
||||
|
||||
let mut donators_text = TextComponent::text("Click to open Donate\n\nDonators:\n");
|
||||
|
||||
if let Ok(mut res) = response
|
||||
&& let Ok(data) = res.body_mut().read_json::<DonatorResponse>()
|
||||
{
|
||||
let mut current = data.current;
|
||||
current.sort_by(|a, b| {
|
||||
let prio_a = tier_priority(&a.tier_slug, &a.tier);
|
||||
let prio_b = tier_priority(&b.tier_slug, &b.tier);
|
||||
prio_a
|
||||
.cmp(&prio_b)
|
||||
.then_with(|| a.tier.cmp(&b.tier))
|
||||
.then_with(|| a.name.cmp(&b.name))
|
||||
});
|
||||
|
||||
if current.is_empty() {
|
||||
donators_text = donators_text.add_child(TextComponent::text("No active donators"));
|
||||
} else {
|
||||
let mut current_tier = String::new();
|
||||
for donator in current {
|
||||
if donator.tier != current_tier {
|
||||
current_tier.clone_from(&donator.tier);
|
||||
let color = tier_color(&donator.tier_slug, &donator.tier);
|
||||
donators_text = donators_text.add_child(
|
||||
TextComponent::text(format!("\n{current_tier}:\n"))
|
||||
.color_named(color)
|
||||
.bold(),
|
||||
);
|
||||
}
|
||||
let color = tier_color(&donator.tier_slug, &donator.tier);
|
||||
donators_text = donators_text.add_child(
|
||||
TextComponent::text(format!(" • {}\n", donator.name)).color_named(color),
|
||||
);
|
||||
}
|
||||
}
|
||||
return donators_text;
|
||||
}
|
||||
|
||||
donators_text.add_child(TextComponent::text("Unable to load donators"))
|
||||
}
|
||||
|
||||
#[expect(clippy::too_many_lines)]
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let contributors = fetch_all_contributors();
|
||||
let contributor_names = contributors
|
||||
.iter()
|
||||
.map(|c| c.login.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let locale = sender.get_locale();
|
||||
let profile = if cfg!(debug_assertions) {
|
||||
"debug"
|
||||
} else {
|
||||
"release"
|
||||
};
|
||||
let version_string = format!(
|
||||
"{} (Commit: {}/{}) - {} Contributors",
|
||||
CARGO_PKG_VERSION,
|
||||
GIT_HASH,
|
||||
profile,
|
||||
contributors.len()
|
||||
);
|
||||
let mut msg = TextComponent::text("");
|
||||
|
||||
let version_translation = get_translation_text(
|
||||
"pumpkin:commands.pumpkin.version",
|
||||
locale,
|
||||
vec![TextComponent::text(version_string.clone()).0],
|
||||
);
|
||||
msg = msg.add_child(
|
||||
TextComponent::text(version_translation.clone())
|
||||
.hover_event(HoverEvent::show_text(
|
||||
TextComponent::text(format!("Commit: {GIT_HASH_FULL}\n\nContributors:\n"))
|
||||
.add_child(
|
||||
TextComponent::text(contributor_names)
|
||||
.gradient_named(&[NamedColor::DarkGreen, NamedColor::Green])
|
||||
.new_line(),
|
||||
),
|
||||
))
|
||||
.click_event(ClickEvent::CopyToClipboard {
|
||||
value: Cow::from(version_translation.replace('\n', "")),
|
||||
})
|
||||
.color_named(NamedColor::Green),
|
||||
);
|
||||
|
||||
let desc_translation =
|
||||
get_translation_text("pumpkin:commands.pumpkin.description", locale, vec![]);
|
||||
let desc_hover_translation =
|
||||
get_translation_text("pumpkin:commands.pumpkin.description.hover", locale, vec![]);
|
||||
msg = msg.add_child(
|
||||
TextComponent::text(desc_translation.clone())
|
||||
.click_event(ClickEvent::CopyToClipboard {
|
||||
value: Cow::from(desc_translation.replace('\n', "")),
|
||||
})
|
||||
.hover_event(HoverEvent::show_text(TextComponent::text(
|
||||
desc_hover_translation,
|
||||
)))
|
||||
.color_named(NamedColor::White),
|
||||
);
|
||||
|
||||
let mc_version_translation = get_translation_text(
|
||||
"pumpkin:commands.pumpkin.minecraft_version",
|
||||
locale,
|
||||
vec![
|
||||
TextComponent::text(CURRENT_MC_VERSION.to_string()).0,
|
||||
TextComponent::text(CURRENT_MC_VERSION.protocol_version().to_string()).0,
|
||||
],
|
||||
);
|
||||
let mc_version_hover_translation = get_translation_text(
|
||||
"pumpkin:commands.pumpkin.minecraft_version.hover",
|
||||
locale,
|
||||
vec![],
|
||||
);
|
||||
msg = msg.add_child(
|
||||
TextComponent::text(mc_version_translation.clone())
|
||||
.click_event(ClickEvent::CopyToClipboard {
|
||||
value: Cow::from(mc_version_translation.replace('\n', "")),
|
||||
})
|
||||
.hover_event(HoverEvent::show_text(TextComponent::text(
|
||||
mc_version_hover_translation,
|
||||
)))
|
||||
.color_named(NamedColor::Gold),
|
||||
);
|
||||
|
||||
let github_translation =
|
||||
get_translation_text("pumpkin:commands.pumpkin.github", locale, vec![]);
|
||||
let github_hover_translation =
|
||||
get_translation_text("pumpkin:commands.pumpkin.github.hover", locale, vec![]);
|
||||
msg = msg.add_child(
|
||||
TextComponent::text(github_translation)
|
||||
.click_event(ClickEvent::OpenUrl {
|
||||
url: Cow::from("https://github.com/Pumpkin-MC/Pumpkin"),
|
||||
})
|
||||
.hover_event(HoverEvent::show_text(TextComponent::text(
|
||||
github_hover_translation,
|
||||
)))
|
||||
.color_named(NamedColor::Blue)
|
||||
.bold()
|
||||
.underlined(),
|
||||
);
|
||||
|
||||
msg = msg.add_child(TextComponent::text(" "));
|
||||
|
||||
let donators_hover = fetch_donators_hover();
|
||||
msg = msg.add_child(
|
||||
TextComponent::text("[Donate]")
|
||||
.click_event(ClickEvent::OpenUrl {
|
||||
url: Cow::from("https://pumpkinmc.org/donate/"),
|
||||
})
|
||||
.hover_event(HoverEvent::show_text(donators_hover))
|
||||
.rainbow()
|
||||
.bold()
|
||||
.underlined(),
|
||||
);
|
||||
|
||||
msg = msg.add_child(TextComponent::text(" "));
|
||||
|
||||
let website_translation =
|
||||
get_translation_text("pumpkin:commands.pumpkin.website", locale, vec![]);
|
||||
let website_hover_translation =
|
||||
get_translation_text("pumpkin:commands.pumpkin.website.hover", locale, vec![]);
|
||||
msg = msg.add_child(
|
||||
TextComponent::text(website_translation)
|
||||
.click_event(ClickEvent::OpenUrl {
|
||||
url: Cow::from("https://pumpkinmc.org/"),
|
||||
})
|
||||
.hover_event(HoverEvent::show_text(TextComponent::text(
|
||||
website_hover_translation,
|
||||
)))
|
||||
.color_named(NamedColor::Blue)
|
||||
.bold()
|
||||
.underlined(),
|
||||
);
|
||||
|
||||
sender.send_message(msg).await;
|
||||
|
||||
// It makes total sense to return the number of
|
||||
// contributors as the i32 result for this command.
|
||||
Ok(contributors.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).execute(Executor)
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command, literal};
|
||||
use crate::command::argument_types::range::IntRangeArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
|
||||
const DESCRIPTION: &str = "Draws a random value.";
|
||||
|
||||
const PERMISSION: &str = "minecraft:command.random";
|
||||
|
||||
const ARG_RANGE: &str = "range";
|
||||
|
||||
/// The largest allowed range span, matching Vanilla (`i32::MAX - 1`).
|
||||
const MAX_RANGE_SPAN: i64 = (i32::MAX - 1) as i64;
|
||||
|
||||
const RANGE_TOO_LARGE_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_RANDOM_ERROR_RANGE_TOO_LARGE,
|
||||
translation::java::COMMANDS_RANDOM_ERROR_RANGE_TOO_LARGE,
|
||||
);
|
||||
|
||||
const RANGE_TOO_SMALL_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_RANDOM_ERROR_RANGE_TOO_SMALL,
|
||||
translation::java::COMMANDS_RANDOM_ERROR_RANGE_TOO_SMALL,
|
||||
);
|
||||
|
||||
struct RandomExecutor {
|
||||
/// Whether the result is announced to every player (`roll`) instead of
|
||||
/// only the command source (`value`).
|
||||
roll: bool,
|
||||
}
|
||||
|
||||
impl CommandExecutor for RandomExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let bounds = IntRangeArgumentType::get(context, ARG_RANGE)?;
|
||||
let min = bounds.min().unwrap_or(i32::MIN);
|
||||
let max = bounds.max().unwrap_or(i32::MAX);
|
||||
|
||||
let span = i64::from(max) - i64::from(min);
|
||||
if span == 0 {
|
||||
return Err(RANGE_TOO_SMALL_ERROR_TYPE.create_without_context());
|
||||
}
|
||||
if span >= MAX_RANGE_SPAN {
|
||||
return Err(RANGE_TOO_LARGE_ERROR_TYPE.create_without_context());
|
||||
}
|
||||
|
||||
let result = rand::random_range(min..=max);
|
||||
|
||||
if self.roll {
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_RANDOM_ROLL,
|
||||
translation::java::COMMANDS_RANDOM_ROLL,
|
||||
[
|
||||
context.source.display_name.clone(),
|
||||
TextComponent::text(result.to_string()),
|
||||
TextComponent::text(min.to_string()),
|
||||
TextComponent::text(max.to_string()),
|
||||
],
|
||||
);
|
||||
for player in context.server().get_all_players() {
|
||||
player.send_system_message(&msg).await;
|
||||
}
|
||||
// Also show the roll on the console (or another non-player source).
|
||||
if context.source.player_or_none().is_none() {
|
||||
context.source.send_message(msg).await;
|
||||
}
|
||||
} else {
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_RANDOM_SAMPLE_SUCCESS,
|
||||
translation::java::COMMANDS_RANDOM_SAMPLE_SUCCESS,
|
||||
[TextComponent::text(result.to_string())],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
// Vanilla allows every player to use `/random value` and `/random roll`.
|
||||
PermissionDefault::Allow,
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("random", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.then(literal("value").then(
|
||||
argument(ARG_RANGE, IntRangeArgumentType).executes(RandomExecutor { roll: false }),
|
||||
))
|
||||
.then(literal("roll").then(
|
||||
argument(ARG_RANGE, IntRangeArgumentType).executes(RandomExecutor { roll: true }),
|
||||
)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command, literal};
|
||||
use crate::command::argument_types::core::string::StringArgumentType;
|
||||
use crate::command::argument_types::entity::EntityArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use crate::command::suggestion::provider::SuggestionProvider;
|
||||
use crate::command::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use crate::entity::EntityBase;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_protocol::codec::recipe::DynamicRecipe;
|
||||
use pumpkin_protocol::java::client::play::CRecipeBookAdd;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
|
||||
const DESCRIPTION: &str = "Gives or takes player recipes.";
|
||||
const PERMISSION: &str = "minecraft:command.recipe";
|
||||
|
||||
static ERROR_RECIPE_NOT_FOUND: CommandErrorType<1> =
|
||||
CommandErrorType::new(translation::java::RECIPE_NOTFOUND, "Unknown recipe: %s");
|
||||
|
||||
fn get_recipe_id(recipe: &DynamicRecipe) -> String {
|
||||
match recipe {
|
||||
DynamicRecipe::Crafting(crafting) => match crafting {
|
||||
pumpkin_protocol::codec::recipe::OwnedCraftingRecipe::Shaped { result, .. }
|
||||
| pumpkin_protocol::codec::recipe::OwnedCraftingRecipe::Shapeless { result, .. } => {
|
||||
result.item_id.clone()
|
||||
}
|
||||
},
|
||||
DynamicRecipe::Cooking(cooking) => match cooking {
|
||||
pumpkin_protocol::codec::recipe::OwnedCookingRecipeType::Smelting(r)
|
||||
| pumpkin_protocol::codec::recipe::OwnedCookingRecipeType::Blasting(r)
|
||||
| pumpkin_protocol::codec::recipe::OwnedCookingRecipeType::Smoking(r)
|
||||
| pumpkin_protocol::codec::recipe::OwnedCookingRecipeType::CampfireCooking(r) => {
|
||||
r.recipe_id.clone()
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
struct RecipeSuggestionProvider;
|
||||
|
||||
impl SuggestionProvider for RecipeSuggestionProvider {
|
||||
fn suggest(
|
||||
&self,
|
||||
context: &CommandContext,
|
||||
mut builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send>> {
|
||||
let server = context.source.server.clone();
|
||||
|
||||
Box::pin(async move {
|
||||
builder = builder.suggest("*");
|
||||
if let Some(server) = server {
|
||||
let recipes = server.recipe_manager.get_dynamic_recipes_internal().await;
|
||||
for recipe in recipes {
|
||||
let id = get_recipe_id(&recipe);
|
||||
builder = builder.suggest(id);
|
||||
}
|
||||
}
|
||||
builder.build()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct RecipeGiveExecutor;
|
||||
|
||||
impl CommandExecutor for RecipeGiveExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_players(context, "targets").await?;
|
||||
let recipe_str = StringArgumentType::get(context, "recipe")?;
|
||||
|
||||
let server = context.source.server.as_ref().ok_or_else(|| {
|
||||
ERROR_RECIPE_NOT_FOUND
|
||||
.create_without_context(TextComponent::text(recipe_str.to_string()))
|
||||
})?;
|
||||
|
||||
let all_recipes = server.recipe_manager.get_dynamic_recipes_internal().await;
|
||||
|
||||
let is_all = recipe_str == "*";
|
||||
let matching_recipes = if is_all {
|
||||
all_recipes.clone()
|
||||
} else {
|
||||
all_recipes
|
||||
.iter()
|
||||
.filter(|r| {
|
||||
let id = get_recipe_id(r);
|
||||
id == recipe_str
|
||||
|| id.strip_prefix("minecraft:").unwrap_or(&id) == recipe_str
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
if !is_all && matching_recipes.is_empty() {
|
||||
return Err(ERROR_RECIPE_NOT_FOUND
|
||||
.create_without_context(TextComponent::text(recipe_str.to_string())));
|
||||
}
|
||||
|
||||
let recipe_count = matching_recipes.len();
|
||||
|
||||
for player in &targets {
|
||||
if let crate::net::ClientPlatform::Java(java_client) = player.client.as_ref() {
|
||||
java_client
|
||||
.send_packet_now(&CRecipeBookAdd::new(false, &matching_recipes))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
let recipe_count_str = recipe_count.to_string();
|
||||
if targets.len() == 1 {
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_RECIPE_GIVE_SUCCESS_SINGLE,
|
||||
translation::java::COMMANDS_RECIPE_GIVE_SUCCESS_SINGLE,
|
||||
[
|
||||
TextComponent::text(recipe_count_str),
|
||||
targets[0].get_display_name().await,
|
||||
],
|
||||
);
|
||||
context.source.send_feedback(msg, true).await;
|
||||
} else {
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_RECIPE_GIVE_SUCCESS_MULTIPLE,
|
||||
translation::java::COMMANDS_RECIPE_GIVE_SUCCESS_MULTIPLE,
|
||||
[
|
||||
TextComponent::text(recipe_count_str),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
);
|
||||
context.source.send_feedback(msg, true).await;
|
||||
}
|
||||
|
||||
Ok((targets.len() * recipe_count) as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct RecipeTakeExecutor;
|
||||
|
||||
impl CommandExecutor for RecipeTakeExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_players(context, "targets").await?;
|
||||
let recipe_str = StringArgumentType::get(context, "recipe")?;
|
||||
|
||||
let server = context.source.server.as_ref().ok_or_else(|| {
|
||||
ERROR_RECIPE_NOT_FOUND
|
||||
.create_without_context(TextComponent::text(recipe_str.to_string()))
|
||||
})?;
|
||||
|
||||
let all_recipes = server.recipe_manager.get_dynamic_recipes_internal().await;
|
||||
|
||||
let is_all = recipe_str == "*";
|
||||
|
||||
let mut matched = false;
|
||||
let remaining_recipes = if is_all {
|
||||
matched = true;
|
||||
Vec::new()
|
||||
} else {
|
||||
all_recipes
|
||||
.iter()
|
||||
.filter(|r| {
|
||||
let id = get_recipe_id(r);
|
||||
let is_match = id == recipe_str
|
||||
|| id.strip_prefix("minecraft:").unwrap_or(&id) == recipe_str;
|
||||
if is_match {
|
||||
matched = true;
|
||||
}
|
||||
!is_match
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
if !matched {
|
||||
return Err(ERROR_RECIPE_NOT_FOUND
|
||||
.create_without_context(TextComponent::text(recipe_str.to_string())));
|
||||
}
|
||||
|
||||
let taken_count = if is_all {
|
||||
all_recipes.len()
|
||||
} else {
|
||||
all_recipes.len() - remaining_recipes.len()
|
||||
};
|
||||
|
||||
for player in &targets {
|
||||
if let crate::net::ClientPlatform::Java(java_client) = player.client.as_ref() {
|
||||
java_client
|
||||
.send_packet_now(&CRecipeBookAdd::new(true, &remaining_recipes))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
let taken_count_str = taken_count.to_string();
|
||||
if targets.len() == 1 {
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_RECIPE_TAKE_SUCCESS_SINGLE,
|
||||
translation::java::COMMANDS_RECIPE_TAKE_SUCCESS_SINGLE,
|
||||
[
|
||||
TextComponent::text(taken_count_str),
|
||||
targets[0].get_display_name().await,
|
||||
],
|
||||
);
|
||||
context.source.send_feedback(msg, true).await;
|
||||
} else {
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_RECIPE_TAKE_SUCCESS_MULTIPLE,
|
||||
translation::java::COMMANDS_RECIPE_TAKE_SUCCESS_MULTIPLE,
|
||||
[
|
||||
TextComponent::text(taken_count_str),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
);
|
||||
context.source.send_feedback(msg, true).await;
|
||||
}
|
||||
|
||||
Ok((targets.len() * taken_count) as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
));
|
||||
|
||||
let builder = command("recipe", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.then(
|
||||
literal("give").then(
|
||||
argument("targets", EntityArgumentType::Players).then(
|
||||
argument("recipe", StringArgumentType::SingleWord)
|
||||
.suggests(RecipeSuggestionProvider)
|
||||
.executes(RecipeGiveExecutor),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("take").then(
|
||||
argument("targets", EntityArgumentType::Players).then(
|
||||
argument("recipe", StringArgumentType::SingleWord)
|
||||
.suggests(RecipeSuggestionProvider)
|
||||
.executes(RecipeTakeExecutor),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
dispatcher.register(builder);
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command, literal};
|
||||
use crate::command::argument_types::entity::EntityArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use crate::entity::EntityBase;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const DESCRIPTION: &str = "Mounts or dismounts target entities.";
|
||||
const PERMISSION: &str = "minecraft:command.ride";
|
||||
|
||||
static ERROR_CANT_RIDE_PLAYERS: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_RIDE_MOUNT_FAILURE_CANT_RIDE_PLAYERS,
|
||||
"Cannot ride players",
|
||||
);
|
||||
static ERROR_WRONG_DIMENSION: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_RIDE_MOUNT_FAILURE_WRONG_DIMENSION,
|
||||
"Cannot ride across dimensions",
|
||||
);
|
||||
static ERROR_LOOP: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_RIDE_MOUNT_FAILURE_LOOP,
|
||||
"Cannot ride recursively",
|
||||
);
|
||||
static ERROR_ALREADY_RIDING: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_RIDE_ALREADY_RIDING,
|
||||
"Already riding",
|
||||
);
|
||||
static ERROR_NOT_RIDING: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_RIDE_NOT_RIDING,
|
||||
"Not riding anything",
|
||||
);
|
||||
static ERROR_GENERIC: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_RIDE_MOUNT_FAILURE_GENERIC,
|
||||
"Failed to mount",
|
||||
);
|
||||
|
||||
#[allow(clippy::assigning_clones)]
|
||||
async fn is_riding_recursive(entity: &dyn EntityBase, possible_vehicle: &dyn EntityBase) -> bool {
|
||||
let mut current = possible_vehicle.get_entity().vehicle.lock().await.clone();
|
||||
while let Some(vehicle) = current {
|
||||
if vehicle.get_entity().entity_id == entity.get_entity().entity_id {
|
||||
return true;
|
||||
}
|
||||
current = vehicle.get_entity().vehicle.lock().await.clone();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
struct RideMountExecutor;
|
||||
|
||||
impl CommandExecutor for RideMountExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_entities(context, "target").await?;
|
||||
let vehicle = EntityArgumentType::get_entity(context, "vehicle").await?;
|
||||
|
||||
if vehicle.get_player().is_some() {
|
||||
return Err(ERROR_CANT_RIDE_PLAYERS.create_without_context());
|
||||
}
|
||||
|
||||
let vehicle_world = vehicle.get_entity().world.load();
|
||||
|
||||
let mut success_count = 0;
|
||||
let mut last_error = None;
|
||||
|
||||
for target in &targets {
|
||||
let target_world = target.get_entity().world.load();
|
||||
if target_world.dimension.minecraft_name != vehicle_world.dimension.minecraft_name {
|
||||
last_error = Some(ERROR_WRONG_DIMENSION.create_without_context());
|
||||
continue;
|
||||
}
|
||||
|
||||
if target.get_entity().entity_id == vehicle.get_entity().entity_id {
|
||||
last_error = Some(ERROR_LOOP.create_without_context());
|
||||
continue;
|
||||
}
|
||||
|
||||
if is_riding_recursive(target.as_ref(), vehicle.as_ref()).await {
|
||||
last_error = Some(ERROR_LOOP.create_without_context());
|
||||
continue;
|
||||
}
|
||||
|
||||
let current_vehicle = target.get_entity().vehicle.lock().await.clone();
|
||||
if let Some(ref curr_veh) = current_vehicle {
|
||||
if curr_veh.get_entity().entity_id == vehicle.get_entity().entity_id {
|
||||
last_error = Some(ERROR_ALREADY_RIDING.create_without_context(
|
||||
target.get_display_name().await,
|
||||
vehicle.get_display_name().await,
|
||||
));
|
||||
continue;
|
||||
}
|
||||
// Dismount first
|
||||
curr_veh
|
||||
.get_entity()
|
||||
.remove_passenger(target.get_entity().entity_id)
|
||||
.await;
|
||||
}
|
||||
|
||||
vehicle
|
||||
.get_entity()
|
||||
.add_passenger(vehicle.clone(), target.clone())
|
||||
.await;
|
||||
success_count += 1;
|
||||
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_RIDE_MOUNT_SUCCESS,
|
||||
translation::java::COMMANDS_RIDE_MOUNT_SUCCESS,
|
||||
[
|
||||
target.get_display_name().await,
|
||||
vehicle.get_display_name().await,
|
||||
],
|
||||
);
|
||||
context.source.send_feedback(msg, true).await;
|
||||
}
|
||||
|
||||
if success_count == 0 {
|
||||
if let Some(err) = last_error {
|
||||
return Err(err);
|
||||
}
|
||||
return Err(ERROR_GENERIC.create_without_context(
|
||||
targets[0].get_display_name().await,
|
||||
vehicle.get_display_name().await,
|
||||
));
|
||||
}
|
||||
|
||||
Ok(success_count)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct RideDismountExecutor;
|
||||
|
||||
impl CommandExecutor for RideDismountExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_entities(context, "target").await?;
|
||||
|
||||
let mut success_count = 0;
|
||||
let mut last_error = None;
|
||||
|
||||
for target in &targets {
|
||||
let current_vehicle = target.get_entity().vehicle.lock().await.clone();
|
||||
if let Some(vehicle) = current_vehicle {
|
||||
vehicle
|
||||
.get_entity()
|
||||
.remove_passenger(target.get_entity().entity_id)
|
||||
.await;
|
||||
success_count += 1;
|
||||
|
||||
let msg = TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_RIDE_DISMOUNT_SUCCESS,
|
||||
translation::java::COMMANDS_RIDE_DISMOUNT_SUCCESS,
|
||||
[target.get_display_name().await],
|
||||
);
|
||||
context.source.send_feedback(msg, true).await;
|
||||
} else {
|
||||
last_error = Some(
|
||||
ERROR_NOT_RIDING.create_without_context(target.get_display_name().await),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if success_count == 0 {
|
||||
if let Some(err) = last_error {
|
||||
return Err(err);
|
||||
}
|
||||
return Err(
|
||||
ERROR_NOT_RIDING.create_without_context(targets[0].get_display_name().await)
|
||||
);
|
||||
}
|
||||
|
||||
Ok(success_count)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
));
|
||||
|
||||
let builder =
|
||||
command("ride", DESCRIPTION).requires(PERMISSION).then(
|
||||
argument("target", EntityArgumentType::Entities)
|
||||
.then(literal("mount").then(
|
||||
argument("vehicle", EntityArgumentType::Entity).executes(RideMountExecutor),
|
||||
))
|
||||
.then(literal("dismount").executes(RideDismountExecutor)),
|
||||
);
|
||||
|
||||
dispatcher.register(builder);
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::command::args::entity::EntityArgumentConsumer;
|
||||
use crate::command::args::entity_anchor::{EntityAnchor, EntityAnchorArgumentConsumer};
|
||||
use crate::command::args::position_3d::Position3DArgumentConsumer;
|
||||
use crate::command::args::rotation::RotationArgumentConsumer;
|
||||
use crate::command::args::{ConsumedArgs, FindArg};
|
||||
use crate::command::tree::CommandTree;
|
||||
use crate::command::tree::builder::{argument, literal};
|
||||
use crate::command::{CommandExecutor, CommandResult, CommandSender};
|
||||
|
||||
const NAMES: [&str; 1] = ["rotate"];
|
||||
const DESCRIPTION: &str = "Changes the rotation of an entity.";
|
||||
|
||||
const ARG_TARGET: &str = "target";
|
||||
const ARG_ROTATION: &str = "rotation";
|
||||
const ARG_FACING_LOCATION: &str = "facingLocation";
|
||||
const ARG_FACING_ENTITY: &str = "facingEntity";
|
||||
const ARG_FACING_ANCHOR: &str = "facingAnchor";
|
||||
|
||||
/// Calculates yaw and pitch to look from one position towards another.
|
||||
fn yaw_pitch_facing_position(
|
||||
looking_from: &Vector3<f64>,
|
||||
looking_towards: &Vector3<f64>,
|
||||
) -> (f32, f32) {
|
||||
let direction_vector = looking_towards.sub(looking_from).normalize();
|
||||
|
||||
let yaw_radians = -direction_vector.x.atan2(direction_vector.z);
|
||||
let pitch_radians = (-direction_vector.y).asin();
|
||||
|
||||
let yaw_degrees = yaw_radians.to_degrees();
|
||||
let pitch_degrees = pitch_radians.to_degrees();
|
||||
|
||||
(yaw_degrees as f32, pitch_degrees as f32)
|
||||
}
|
||||
|
||||
/// Gets the position to look at for an entity, considering the anchor point.
|
||||
/// Matches vanilla's `EntityAnchorArgumentType.EntityAnchor.positionAt()`.
|
||||
fn get_anchor_position(entity: &crate::entity::Entity, anchor: EntityAnchor) -> Vector3<f64> {
|
||||
let pos = entity.pos.load();
|
||||
match anchor {
|
||||
EntityAnchor::Eyes => {
|
||||
let eye_height = entity.get_eye_height();
|
||||
Vector3::new(pos.x, pos.y + eye_height, pos.z)
|
||||
}
|
||||
EntityAnchor::Feet => pos,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rotates an entity using vanilla-style rotation logic.
|
||||
/// If relative flags are true, the values are added to current rotation.
|
||||
/// If relative flags are false, the values are absolute.
|
||||
async fn rotate_entity(
|
||||
target: std::sync::Arc<dyn crate::entity::EntityBase>,
|
||||
yaw: f32,
|
||||
is_yaw_relative: bool,
|
||||
pitch: f32,
|
||||
is_pitch_relative: bool,
|
||||
) {
|
||||
let entity = target.get_entity();
|
||||
|
||||
// Calculate final rotation values like vanilla's Entity.rotate()
|
||||
// If relative, add to current rotation; if absolute, use directly
|
||||
let final_yaw = if is_yaw_relative {
|
||||
entity.yaw.load() + yaw
|
||||
} else {
|
||||
yaw
|
||||
};
|
||||
|
||||
let final_pitch = if is_pitch_relative {
|
||||
// Clamp pitch to valid range [-90, 90]
|
||||
(entity.pitch.load() + pitch).clamp(-90.0, 90.0)
|
||||
} else {
|
||||
pitch.clamp(-90.0, 90.0)
|
||||
};
|
||||
|
||||
// Use teleport with same position to update rotation
|
||||
// This properly handles both players (sends CPlayerPosition) and other entities
|
||||
let pos = entity.pos.load();
|
||||
let world = entity.world.load_full();
|
||||
target
|
||||
.teleport(pos, Some(final_yaw), Some(final_pitch), world)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Sends success message for the rotate command.
|
||||
async fn send_success_message(sender: &CommandSender, target: &dyn crate::entity::EntityBase) {
|
||||
let target_name = target.get_display_name().await;
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_ROTATE_SUCCESS,
|
||||
translation::java::COMMANDS_ROTATE_SUCCESS,
|
||||
[target_name],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
// /rotate <target> <rotation>
|
||||
struct RotateToRotationExecutor;
|
||||
|
||||
impl CommandExecutor for RotateToRotationExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentConsumer::find_arg(args, ARG_TARGET)?;
|
||||
let (yaw, yaw_rel, pitch, pitch_rel) =
|
||||
RotationArgumentConsumer::find_arg(args, ARG_ROTATION)?;
|
||||
|
||||
rotate_entity(target.clone(), yaw, yaw_rel, pitch, pitch_rel).await;
|
||||
send_success_message(sender, target.as_ref()).await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// /rotate <target> facing <x> <y> <z>
|
||||
struct RotateFacingLocationExecutor;
|
||||
|
||||
impl CommandExecutor for RotateFacingLocationExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentConsumer::find_arg(args, ARG_TARGET)?;
|
||||
let facing_pos = Position3DArgumentConsumer::find_arg(args, ARG_FACING_LOCATION)?;
|
||||
|
||||
let entity = target.get_entity();
|
||||
let eye_height = entity.get_eye_height();
|
||||
let pos = entity.pos.load();
|
||||
let looking_from = Vector3::new(pos.x, pos.y + eye_height, pos.z);
|
||||
|
||||
let (yaw, pitch) = yaw_pitch_facing_position(&looking_from, &facing_pos);
|
||||
|
||||
// Facing uses absolute rotation
|
||||
rotate_entity(target.clone(), yaw, false, pitch, false).await;
|
||||
send_success_message(sender, target.as_ref()).await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// /rotate <target> facing entity <entity> [eyes|feet]
|
||||
struct RotateFacingEntityExecutor;
|
||||
|
||||
impl CommandExecutor for RotateFacingEntityExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentConsumer::find_arg(args, ARG_TARGET)?;
|
||||
let facing_entity = EntityArgumentConsumer::find_arg(args, ARG_FACING_ENTITY)?;
|
||||
let anchor = EntityAnchorArgumentConsumer::find_arg(args, ARG_FACING_ANCHOR)?;
|
||||
let target_entity = target.get_entity();
|
||||
let eye_height = target_entity.get_eye_height();
|
||||
let pos = target_entity.pos.load();
|
||||
let looking_from = Vector3::new(pos.x, pos.y + eye_height, pos.z);
|
||||
|
||||
let looking_towards = get_anchor_position(facing_entity.get_entity(), anchor);
|
||||
|
||||
let (yaw, pitch) = yaw_pitch_facing_position(&looking_from, &looking_towards);
|
||||
|
||||
// Facing uses absolute rotation
|
||||
rotate_entity(target.clone(), yaw, false, pitch, false).await;
|
||||
send_success_message(sender, target.as_ref()).await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// /rotate <target> facing entity <entity> (no anchor - defaults to feet)
|
||||
struct RotateFacingEntityNoAnchorExecutor;
|
||||
|
||||
impl CommandExecutor for RotateFacingEntityNoAnchorExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let target = EntityArgumentConsumer::find_arg(args, ARG_TARGET)?;
|
||||
let facing_entity = EntityArgumentConsumer::find_arg(args, ARG_FACING_ENTITY)?;
|
||||
|
||||
let target_entity = target.get_entity();
|
||||
let eye_height = target_entity.get_eye_height();
|
||||
let pos = target_entity.pos.load();
|
||||
let looking_from = Vector3::new(pos.x, pos.y + eye_height, pos.z);
|
||||
|
||||
// Default to feet (vanilla behavior)
|
||||
let looking_towards =
|
||||
get_anchor_position(facing_entity.get_entity(), EntityAnchor::Feet);
|
||||
|
||||
let (yaw, pitch) = yaw_pitch_facing_position(&looking_from, &looking_towards);
|
||||
|
||||
// Facing uses absolute rotation
|
||||
rotate_entity(target.clone(), yaw, false, pitch, false).await;
|
||||
send_success_message(sender, target.as_ref()).await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(ARG_TARGET, EntityArgumentConsumer)
|
||||
.then(
|
||||
argument(ARG_ROTATION, RotationArgumentConsumer).execute(RotateToRotationExecutor),
|
||||
)
|
||||
.then(
|
||||
literal("facing")
|
||||
.then(
|
||||
literal("entity").then(
|
||||
argument(ARG_FACING_ENTITY, EntityArgumentConsumer)
|
||||
.execute(RotateFacingEntityNoAnchorExecutor)
|
||||
.then(
|
||||
argument(ARG_FACING_ANCHOR, EntityAnchorArgumentConsumer)
|
||||
.execute(RotateFacingEntityExecutor),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
argument(ARG_FACING_LOCATION, Position3DArgumentConsumer)
|
||||
.execute(RotateFacingLocationExecutor),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use tracing::error;
|
||||
|
||||
use crate::command::argument_builder::{ArgumentBuilder, command};
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
|
||||
const DESCRIPTION: &str = "Saves the server to disk.";
|
||||
|
||||
const PERMISSION: &str = "minecraft:command.save-all";
|
||||
|
||||
const SAVE_FAILED_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_SAVE_FAILED,
|
||||
translation::bedrock::COMMANDS_SAVE_FAILED,
|
||||
);
|
||||
|
||||
struct SaveAllExecutor;
|
||||
|
||||
impl CommandExecutor for SaveAllExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SAVE_SAVING,
|
||||
translation::bedrock::COMMANDS_SAVE_START,
|
||||
[],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
|
||||
let server = context.server();
|
||||
|
||||
if let Err(err) = server.player_data_storage.save_all_players(server).await {
|
||||
error!("Failed to save player data: {err}");
|
||||
return Err(SAVE_FAILED_ERROR_TYPE.create_without_context());
|
||||
}
|
||||
|
||||
if let Err(err) = server
|
||||
.advancement_manager
|
||||
.save_all_players(&server.get_all_players())
|
||||
.await
|
||||
{
|
||||
error!("Failed to save player advancements: {err}");
|
||||
return Err(SAVE_FAILED_ERROR_TYPE.create_without_context());
|
||||
}
|
||||
|
||||
// Request a save from every world's chunk scheduler. This works even
|
||||
// while autosaving is disabled via /save-off, matching Vanilla.
|
||||
for world in server.worlds.load().iter() {
|
||||
world.level.should_save.store(true, Relaxed);
|
||||
world.level.level_channel.notify();
|
||||
}
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SAVE_SUCCESS,
|
||||
translation::bedrock::COMMANDS_SAVE_SUCCESS,
|
||||
[],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Four),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("save-all", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.executes(SaveAllExecutor),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::command::argument_builder::{ArgumentBuilder, command};
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
|
||||
const DESCRIPTION: &str = "Disables automatic server saves.";
|
||||
|
||||
const PERMISSION: &str = "minecraft:command.save-off";
|
||||
|
||||
const ALREADY_OFF_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_SAVE_ALREADYOFF,
|
||||
translation::bedrock::COMMANDS_SAVE_OFF_ALREADYOFF,
|
||||
);
|
||||
|
||||
struct SaveOffExecutor;
|
||||
|
||||
impl CommandExecutor for SaveOffExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let mut any_disabled = false;
|
||||
for world in context.server().worlds.load().iter() {
|
||||
if world.level.save_enabled.swap(false, Relaxed) {
|
||||
any_disabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
if !any_disabled {
|
||||
return Err(ALREADY_OFF_ERROR_TYPE.create_without_context());
|
||||
}
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SAVE_DISABLED,
|
||||
translation::bedrock::COMMANDS_SAVE_DISABLED,
|
||||
[],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Four),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("save-off", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.executes(SaveOffExecutor),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::command::argument_builder::{ArgumentBuilder, command};
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
|
||||
const DESCRIPTION: &str = "Enables automatic server saves.";
|
||||
|
||||
const PERMISSION: &str = "minecraft:command.save-on";
|
||||
|
||||
const ALREADY_ON_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_SAVE_ALREADYON,
|
||||
translation::bedrock::COMMANDS_SAVE_ON_ALREADYON,
|
||||
);
|
||||
|
||||
struct SaveOnExecutor;
|
||||
|
||||
impl CommandExecutor for SaveOnExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let mut any_enabled = false;
|
||||
for world in context.server().worlds.load().iter() {
|
||||
if !world.level.save_enabled.swap(true, Relaxed) {
|
||||
any_enabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
if !any_enabled {
|
||||
return Err(ALREADY_ON_ERROR_TYPE.create_without_context());
|
||||
}
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SAVE_ENABLED,
|
||||
translation::bedrock::COMMANDS_SAVE_ENABLED,
|
||||
[],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Four),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("save-on", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.executes(SaveOnExecutor),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
use pumpkin_data::world::SAY_COMMAND;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::command::{
|
||||
CommandError, CommandExecutor, CommandResult, CommandSender,
|
||||
args::{Arg, ConsumedArgs, message::MsgArgConsumer},
|
||||
tree::{CommandTree, builder::argument},
|
||||
};
|
||||
use CommandError::InvalidConsumption;
|
||||
|
||||
const NAMES: [&str; 1] = ["say"];
|
||||
|
||||
const DESCRIPTION: &str = "Broadcast a message to all Players.";
|
||||
|
||||
const ARG_MESSAGE: &str = "message";
|
||||
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Msg(msg)) = args.get(ARG_MESSAGE) else {
|
||||
return Err(InvalidConsumption(Some(ARG_MESSAGE.into())));
|
||||
};
|
||||
|
||||
let Some(server_arc) = sender
|
||||
.world_or_first(server)
|
||||
.and_then(|w| w.server.upgrade())
|
||||
else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(
|
||||
"Failed to get server instance",
|
||||
)));
|
||||
};
|
||||
|
||||
server_arc
|
||||
.broadcast_message(
|
||||
&TextComponent::text(msg.clone()),
|
||||
&TextComponent::text(format!("{sender}")),
|
||||
SAY_COMMAND,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION)
|
||||
.then(argument(ARG_MESSAGE, MsgArgConsumer).execute(Executor))
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command, literal};
|
||||
use crate::command::argument_types::core::string::StringArgumentType;
|
||||
use crate::command::argument_types::entity::EntityArgumentType;
|
||||
use crate::command::argument_types::objective::ObjectiveArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use crate::world::scoreboard::{ScoreboardObjective, ScoreboardScore};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_protocol::codec::var_int::VarInt;
|
||||
use pumpkin_protocol::java::client::play::RenderType;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const DESCRIPTION: &str = "Manages scoreboard objectives and players.";
|
||||
const PERMISSION: &str = "minecraft:command.scoreboard";
|
||||
|
||||
const ARG_OBJECTIVE: &str = "objective";
|
||||
const ARG_CRITERION: &str = "criterion";
|
||||
const ARG_DISPLAY_NAME: &str = "display_name";
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
|
||||
const DUPLICATE_OBJECTIVE_ERROR: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_SCOREBOARD_OBJECTIVES_ADD_DUPLICATE,
|
||||
translation::java::COMMANDS_SCOREBOARD_OBJECTIVES_ADD_DUPLICATE,
|
||||
);
|
||||
|
||||
const INVALID_ENABLE_ERROR: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_SCOREBOARD_PLAYERS_ENABLE_INVALID,
|
||||
translation::java::COMMANDS_SCOREBOARD_PLAYERS_ENABLE_INVALID,
|
||||
);
|
||||
|
||||
const FAILED_ENABLE_ERROR: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_SCOREBOARD_PLAYERS_ENABLE_FAILED,
|
||||
translation::java::COMMANDS_SCOREBOARD_PLAYERS_ENABLE_FAILED,
|
||||
);
|
||||
|
||||
struct ObjectivesAddExecutor {
|
||||
has_display_name: bool,
|
||||
}
|
||||
|
||||
impl CommandExecutor for ObjectivesAddExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let objective_name = StringArgumentType::get(context, ARG_OBJECTIVE)?;
|
||||
let criterion = StringArgumentType::get(context, ARG_CRITERION)?;
|
||||
|
||||
let display_name = if self.has_display_name {
|
||||
TextComponent::text(StringArgumentType::get(context, ARG_DISPLAY_NAME)?.to_string())
|
||||
} else {
|
||||
TextComponent::text(objective_name.to_string())
|
||||
};
|
||||
|
||||
let world = context.world();
|
||||
let mut scoreboard = world.scoreboard.lock().await;
|
||||
|
||||
if scoreboard.get_objectives().contains_key(objective_name) {
|
||||
return Err(DUPLICATE_OBJECTIVE_ERROR.create_without_context());
|
||||
}
|
||||
|
||||
let obj_name_static = Box::leak(objective_name.to_string().into_boxed_str());
|
||||
let criterion_static = Box::leak(criterion.to_string().into_boxed_str());
|
||||
|
||||
let new_objective = ScoreboardObjective::new(
|
||||
obj_name_static,
|
||||
display_name.clone(),
|
||||
RenderType::Integer,
|
||||
None,
|
||||
criterion_static,
|
||||
);
|
||||
|
||||
scoreboard.add_objective(world, new_objective).await;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SCOREBOARD_OBJECTIVES_ADD_SUCCESS,
|
||||
translation::java::COMMANDS_SCOREBOARD_OBJECTIVES_ADD_SUCCESS,
|
||||
[display_name],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayersEnableExecutor;
|
||||
|
||||
impl CommandExecutor for PlayersEnableExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_players(context, ARG_TARGETS).await?;
|
||||
let objective_name = ObjectiveArgumentType::get(context, ARG_OBJECTIVE)?;
|
||||
|
||||
let world = context.world();
|
||||
let mut scoreboard = world.scoreboard.lock().await;
|
||||
|
||||
let objective = scoreboard
|
||||
.get_objectives()
|
||||
.get(objective_name)
|
||||
.ok_or_else(|| INVALID_ENABLE_ERROR.create_without_context())?;
|
||||
|
||||
if objective.criterion != "trigger" {
|
||||
return Err(INVALID_ENABLE_ERROR.create_without_context());
|
||||
}
|
||||
|
||||
let objective_display_name = objective.display_name.clone();
|
||||
|
||||
let mut enabled_count = 0;
|
||||
for player in &targets {
|
||||
let player_name = &player.gameprofile.name;
|
||||
let current_score = scoreboard
|
||||
.get_scores()
|
||||
.get(objective_name)
|
||||
.and_then(|m| m.get(player_name));
|
||||
|
||||
let is_already_enabled = current_score.is_some_and(|s| !s.locked);
|
||||
|
||||
if !is_already_enabled {
|
||||
let value = current_score.map_or(0, |s| s.value.0);
|
||||
let display_name = current_score.and_then(|s| s.display_name.clone());
|
||||
let number_format = current_score.and_then(|s| s.number_format.clone());
|
||||
|
||||
let updated_score = ScoreboardScore {
|
||||
entity_name: Box::leak(player_name.clone().into_boxed_str()),
|
||||
objective_name: Box::leak(objective_name.to_string().into_boxed_str()),
|
||||
value: VarInt(value),
|
||||
display_name,
|
||||
number_format,
|
||||
locked: false,
|
||||
};
|
||||
|
||||
scoreboard.update_score(world, updated_score).await;
|
||||
enabled_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if enabled_count == 0 {
|
||||
return Err(FAILED_ENABLE_ERROR.create_without_context());
|
||||
}
|
||||
|
||||
let msg = if targets.len() == 1 {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SCOREBOARD_PLAYERS_ENABLE_SUCCESS_SINGLE,
|
||||
translation::java::COMMANDS_SCOREBOARD_PLAYERS_ENABLE_SUCCESS_SINGLE,
|
||||
[
|
||||
objective_display_name,
|
||||
TextComponent::text(targets[0].gameprofile.name.clone()),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SCOREBOARD_PLAYERS_ENABLE_SUCCESS_MULTIPLE,
|
||||
translation::java::COMMANDS_SCOREBOARD_PLAYERS_ENABLE_SUCCESS_MULTIPLE,
|
||||
[
|
||||
objective_display_name,
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
)
|
||||
};
|
||||
|
||||
context.source.send_feedback(msg, true).await;
|
||||
|
||||
Ok(enabled_count)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("scoreboard", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.then(
|
||||
literal("objectives").then(
|
||||
literal("add").then(
|
||||
argument(ARG_OBJECTIVE, StringArgumentType::SingleWord).then(
|
||||
argument(ARG_CRITERION, StringArgumentType::SingleWord)
|
||||
.executes(ObjectivesAddExecutor {
|
||||
has_display_name: false,
|
||||
})
|
||||
.then(
|
||||
argument(ARG_DISPLAY_NAME, StringArgumentType::GreedyPhrase)
|
||||
.executes(ObjectivesAddExecutor {
|
||||
has_display_name: true,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(literal("players").then(literal("enable").then(
|
||||
argument(ARG_TARGETS, EntityArgumentType::Players).then(
|
||||
argument(ARG_OBJECTIVE, ObjectiveArgumentType).executes(PlayersEnableExecutor),
|
||||
),
|
||||
))),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, command};
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::click::ClickEvent;
|
||||
use pumpkin_util::text::hover::HoverEvent;
|
||||
use pumpkin_util::text::{TextComponent, color::NamedColor};
|
||||
use std::borrow::Cow;
|
||||
|
||||
const DESCRIPTION: &str = "Displays the world seed.";
|
||||
const PERMISSION: &str = "minecraft:command.seed";
|
||||
|
||||
struct SeedCommandExecutor;
|
||||
|
||||
fn create_copy_on_click_text(content: String) -> TextComponent {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SEED_SUCCESS,
|
||||
translation::bedrock::COMMANDS_SEED_SUCCESS,
|
||||
[TextComponent::wrap_in_square_brackets(
|
||||
TextComponent::text(content.clone())
|
||||
.hover_event(HoverEvent::show_text(TextComponent::translate_cross(
|
||||
translation::java::CHAT_COPY_CLICK,
|
||||
translation::java::CHAT_COPY_CLICK,
|
||||
[],
|
||||
)))
|
||||
.click_event(ClickEvent::CopyToClipboard {
|
||||
value: Cow::from(content),
|
||||
})
|
||||
.color_named(NamedColor::Green),
|
||||
)],
|
||||
)
|
||||
}
|
||||
|
||||
impl CommandExecutor for SeedCommandExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let seed = context.world().level.seed.0;
|
||||
let seed_string = seed.to_string();
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(create_copy_on_click_text(seed_string), false)
|
||||
.await;
|
||||
|
||||
Ok(seed as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
// For integrated servers, the permission level is 0,
|
||||
// but Pumpkin is always a dedicated server. For dedicated servers,
|
||||
// /seed is limited to level 2.
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("seed", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.executes(SeedCommandExecutor),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_world::world::BlockFlags;
|
||||
|
||||
use crate::command::args::block::BlockArgumentConsumer;
|
||||
use crate::command::args::position_block::BlockPosArgumentConsumer;
|
||||
use crate::command::args::{ConsumedArgs, FindArg};
|
||||
use crate::command::tree::CommandTree;
|
||||
use crate::command::tree::builder::{argument, literal};
|
||||
use crate::command::{CommandError, CommandExecutor, CommandResult, CommandSender};
|
||||
|
||||
const NAMES: [&str; 1] = ["setblock"];
|
||||
|
||||
const DESCRIPTION: &str = "Place a block.";
|
||||
|
||||
const ARG_BLOCK: &str = "block";
|
||||
const ARG_BLOCK_POS: &str = "pos";
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Mode {
|
||||
/// with particles + item drops
|
||||
Destroy,
|
||||
|
||||
/// only replaces air
|
||||
Keep,
|
||||
|
||||
/// default; without particles
|
||||
Replace,
|
||||
|
||||
/// places block without triggering updates around it
|
||||
Strict,
|
||||
}
|
||||
|
||||
struct Executor(Mode);
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let block = BlockArgumentConsumer::find_arg(args, ARG_BLOCK)?;
|
||||
let block_state_id = block.default_state.id;
|
||||
let mode = self.0;
|
||||
let world = sender
|
||||
.world_or_first(server)
|
||||
.ok_or(CommandError::InvalidRequirement)?;
|
||||
let pos = BlockPosArgumentConsumer::find_loaded_arg(args, ARG_BLOCK_POS, &world)?;
|
||||
|
||||
let success = match mode {
|
||||
Mode::Destroy => {
|
||||
world
|
||||
.clone()
|
||||
.break_block(&pos, None, BlockFlags::SKIP_DROPS | BlockFlags::FORCE_STATE)
|
||||
.await;
|
||||
world
|
||||
.set_block_state(
|
||||
&pos,
|
||||
block_state_id,
|
||||
BlockFlags::FORCE_STATE | BlockFlags::NOTIFY_NEIGHBORS,
|
||||
)
|
||||
.await;
|
||||
true
|
||||
}
|
||||
Mode::Replace => {
|
||||
world
|
||||
.set_block_state(
|
||||
&pos,
|
||||
block_state_id,
|
||||
BlockFlags::FORCE_STATE | BlockFlags::NOTIFY_NEIGHBORS,
|
||||
)
|
||||
.await;
|
||||
true
|
||||
}
|
||||
Mode::Keep => {
|
||||
let old_state = world.get_block_state(&pos);
|
||||
if old_state.is_air() {
|
||||
world
|
||||
.set_block_state(
|
||||
&pos,
|
||||
block_state_id,
|
||||
BlockFlags::FORCE_STATE | BlockFlags::NOTIFY_NEIGHBORS,
|
||||
)
|
||||
.await;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
Mode::Strict => {
|
||||
world
|
||||
.set_block_state(
|
||||
&pos,
|
||||
block_state_id,
|
||||
BlockFlags::SKIP_BLOCK_ADDED_CALLBACK,
|
||||
)
|
||||
.await;
|
||||
true
|
||||
}
|
||||
};
|
||||
|
||||
if success {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_SETBLOCK_SUCCESS,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_SETBLOCK_SUCCESS,
|
||||
[
|
||||
TextComponent::text(pos.0.x.to_string()),
|
||||
TextComponent::text(pos.0.y.to_string()),
|
||||
TextComponent::text(pos.0.z.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
Ok(1)
|
||||
} else {
|
||||
Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
pumpkin_data::translation::java::COMMANDS_SETBLOCK_FAILED,
|
||||
pumpkin_data::translation::bedrock::COMMANDS_SETBLOCK_FAILED,
|
||||
[],
|
||||
)))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(ARG_BLOCK_POS, BlockPosArgumentConsumer).then(
|
||||
argument(ARG_BLOCK, BlockArgumentConsumer)
|
||||
.then(literal("replace").execute(Executor(Mode::Replace)))
|
||||
.then(literal("destroy").execute(Executor(Mode::Destroy)))
|
||||
.then(literal("keep").execute(Executor(Mode::Keep)))
|
||||
.then(literal("strict").execute(Executor(Mode::Strict)))
|
||||
.execute(Executor(Mode::Replace)),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use pumpkin_util::{
|
||||
PermissionLvl,
|
||||
permission::{Permission, PermissionDefault, PermissionRegistry},
|
||||
text::TextComponent,
|
||||
};
|
||||
|
||||
use crate::command::{
|
||||
argument_builder::{ArgumentBuilder, argument, command},
|
||||
argument_types::core::integer::IntegerArgumentType,
|
||||
context::command_context::CommandContext,
|
||||
node::{CommandExecutor, CommandExecutorResult, dispatcher::CommandDispatcher},
|
||||
};
|
||||
|
||||
const DESCRIPTION: &str = "Sets the time before idle players are kicked from the server.";
|
||||
const PERMISSION: &str = "minecraft:command.setidletimeout";
|
||||
|
||||
const ARG_MINUTES: &str = "minutes";
|
||||
|
||||
struct SetIdleTimeoutExecutor;
|
||||
|
||||
impl CommandExecutor for SetIdleTimeoutExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let minutes: i32 = IntegerArgumentType::get(context, ARG_MINUTES)?;
|
||||
|
||||
context
|
||||
.server()
|
||||
.player_idle_timeout
|
||||
.store(minutes, Ordering::Relaxed);
|
||||
|
||||
{
|
||||
if minutes == 0 {
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
"commands.setidletimeout.success.disabled",
|
||||
"commands.setidletimeout.success.disabled",
|
||||
[],
|
||||
),
|
||||
true,
|
||||
)
|
||||
} else {
|
||||
context.source.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
"commands.setidletimeout.success",
|
||||
"commands.setidletimeout.success",
|
||||
[TextComponent::text(minutes.to_string())],
|
||||
),
|
||||
true,
|
||||
)
|
||||
}
|
||||
}
|
||||
.await;
|
||||
|
||||
Ok(minutes)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Three),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("setidletimeout", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.then(
|
||||
argument(ARG_MINUTES, IntegerArgumentType::with_min(0))
|
||||
.executes(SetIdleTimeoutExecutor),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::command::CommandResult;
|
||||
use crate::command::dispatcher::CommandError::InvalidConsumption;
|
||||
use crate::command::{
|
||||
CommandExecutor, CommandSender,
|
||||
args::{
|
||||
Arg, ConsumedArgs, position_block::BlockPosArgumentConsumer,
|
||||
rotation::RotationArgumentConsumer,
|
||||
},
|
||||
dispatcher::CommandError,
|
||||
tree::{CommandTree, builder::argument},
|
||||
};
|
||||
use crate::plugin::world::spawn_change::SpawnChangeEvent;
|
||||
use crate::server::Server;
|
||||
use pumpkin_data::dimension::Dimension;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::{math::position::BlockPos, text::TextComponent};
|
||||
|
||||
const NAMES: [&str; 1] = ["setworldspawn"];
|
||||
|
||||
const DESCRIPTION: &str = "Sets the world spawn point.";
|
||||
|
||||
const ARG_BLOCK_POS: &str = "position";
|
||||
|
||||
const ARG_ANGLE: &str = "angle";
|
||||
|
||||
struct NoArgsWorldSpawnExecutor;
|
||||
|
||||
impl CommandExecutor for NoArgsWorldSpawnExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(player) = sender.as_player() else {
|
||||
if sender.is_console() {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(
|
||||
"You must specify a Position!",
|
||||
)));
|
||||
}
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(
|
||||
"Failed to get Sender as Player!",
|
||||
)));
|
||||
};
|
||||
let block_pos = player.position();
|
||||
setworldspawn(sender, server, block_pos.to_block_pos(), 0.0, 0.0).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct DefaultWorldSpawnExecutor;
|
||||
|
||||
impl CommandExecutor for DefaultWorldSpawnExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::BlockPos(block_pos)) = args.get(ARG_BLOCK_POS) else {
|
||||
return Err(InvalidConsumption(Some(ARG_BLOCK_POS.into())));
|
||||
};
|
||||
|
||||
setworldspawn(sender, server, *block_pos, 0.0, 0.0).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct AngleWorldSpawnExecutor;
|
||||
|
||||
impl CommandExecutor for AngleWorldSpawnExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::BlockPos(block_pos)) = args.get(ARG_BLOCK_POS) else {
|
||||
return Err(InvalidConsumption(Some(ARG_BLOCK_POS.into())));
|
||||
};
|
||||
|
||||
// Note: Rotation argument is (yaw, is_yaw_relative, pitch, is_pitch_relative)
|
||||
// For setworldspawn, we use absolute values only (ignore relative flags)
|
||||
let Some(Arg::Rotation(yaw, _, pitch, _)) = args.get(ARG_ANGLE) else {
|
||||
return Err(InvalidConsumption(Some(ARG_ANGLE.into())));
|
||||
};
|
||||
|
||||
setworldspawn(sender, server, *block_pos, *yaw, *pitch).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn setworldspawn(
|
||||
sender: &CommandSender,
|
||||
server: &Server,
|
||||
block_pos: BlockPos,
|
||||
yaw: f32,
|
||||
pitch: f32,
|
||||
) -> Result<i32, CommandError> {
|
||||
let Some(world) = sender.world_or_first(server) else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(
|
||||
"Failed to get world.",
|
||||
)));
|
||||
};
|
||||
if world.dimension != Dimension::OVERWORLD && world.dimension != Dimension::OVERWORLD_CAVES {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SETWORLDSPAWN_FAILURE_NOT_OVERWORLD,
|
||||
translation::java::COMMANDS_SETWORLDSPAWN_FAILURE_NOT_OVERWORLD,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
let current_info = server.level_info.load();
|
||||
let previous_position = BlockPos::new(
|
||||
current_info.spawn_x,
|
||||
current_info.spawn_y,
|
||||
current_info.spawn_z,
|
||||
);
|
||||
let mut new_position = block_pos;
|
||||
let previous_yaw = current_info.spawn_yaw;
|
||||
let previous_pitch = current_info.spawn_pitch;
|
||||
let mut new_yaw = yaw;
|
||||
let mut new_pitch = pitch;
|
||||
let mut event = SpawnChangeEvent::new(
|
||||
world.clone(),
|
||||
previous_position,
|
||||
previous_yaw,
|
||||
previous_pitch,
|
||||
new_position,
|
||||
new_yaw,
|
||||
new_pitch,
|
||||
);
|
||||
if let Some(server_arc) = world.server.upgrade() {
|
||||
server_arc
|
||||
.plugin_manager
|
||||
.fire(&server_arc, &mut event)
|
||||
.await;
|
||||
}
|
||||
new_position = event.new_position;
|
||||
new_yaw = event.new_yaw;
|
||||
new_pitch = event.new_pitch;
|
||||
|
||||
let mut new_info = (**current_info).clone();
|
||||
|
||||
new_info.spawn_x = new_position.0.x;
|
||||
new_info.spawn_y = new_position.0.y;
|
||||
new_info.spawn_z = new_position.0.z;
|
||||
new_info.spawn_yaw = new_yaw;
|
||||
new_info.spawn_pitch = new_pitch;
|
||||
|
||||
server.level_info.store(Arc::new(new_info));
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SETWORLDSPAWN_SUCCESS_NEW,
|
||||
translation::java::COMMANDS_SETWORLDSPAWN_SUCCESS_NEW,
|
||||
[
|
||||
TextComponent::text(new_position.0.x.to_string()),
|
||||
TextComponent::text(new_position.0.y.to_string()),
|
||||
TextComponent::text(new_position.0.z.to_string()),
|
||||
TextComponent::text(new_yaw.to_string()),
|
||||
TextComponent::text(new_pitch.to_string()),
|
||||
TextComponent::text(world.dimension.minecraft_name),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION)
|
||||
.execute(NoArgsWorldSpawnExecutor)
|
||||
.then(
|
||||
argument(ARG_BLOCK_POS, BlockPosArgumentConsumer)
|
||||
.execute(DefaultWorldSpawnExecutor)
|
||||
.then(
|
||||
argument(ARG_ANGLE, RotationArgumentConsumer).execute(AngleWorldSpawnExecutor),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::math::position::BlockPos;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::command::args::players::PlayersArgumentConsumer;
|
||||
use crate::command::args::position_block::BlockPosArgumentConsumer;
|
||||
use crate::command::args::rotation::RotationArgumentConsumer;
|
||||
use crate::command::args::{Arg, ConsumedArgs, FindArgDefaultName};
|
||||
use crate::command::dispatcher::CommandError;
|
||||
use crate::command::tree::CommandTree;
|
||||
use crate::command::tree::builder::argument;
|
||||
use crate::command::{CommandExecutor, CommandResult, CommandSender};
|
||||
use crate::entity::EntityBase;
|
||||
use crate::entity::player::Player;
|
||||
|
||||
const NAMES: [&str; 1] = ["spawnpoint"];
|
||||
|
||||
const DESCRIPTION: &str = "Sets the spawn point for a player.";
|
||||
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
const ARG_POS: &str = "pos";
|
||||
const ARG_ANGLE: &str = "angle";
|
||||
|
||||
/// `/spawnpoint` - set self at current position
|
||||
struct SelfExecutor;
|
||||
|
||||
impl CommandExecutor for SelfExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(player) = sender.as_player() else {
|
||||
return Err(CommandError::InvalidRequirement);
|
||||
};
|
||||
let pos = player.position().to_block_pos();
|
||||
let yaw = player.get_entity().yaw.load();
|
||||
set_spawnpoint(sender, &player, pos, yaw).await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `/spawnpoint <targets>` - set targets at their current positions
|
||||
struct TargetsExecutor;
|
||||
|
||||
impl CommandExecutor for TargetsExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = PlayersArgumentConsumer.find_arg_default_name(args)?;
|
||||
|
||||
for target in targets {
|
||||
let pos = target.position().to_block_pos();
|
||||
let yaw = target.living_entity.entity.yaw.load();
|
||||
set_spawnpoint(sender, target, pos, yaw).await;
|
||||
}
|
||||
|
||||
Ok(targets.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `/spawnpoint <targets> <pos>` - set targets at specified position
|
||||
struct TargetsPosExecutor;
|
||||
|
||||
impl CommandExecutor for TargetsPosExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = PlayersArgumentConsumer.find_arg_default_name(args)?;
|
||||
let Some(Arg::BlockPos(pos)) = args.get(ARG_POS) else {
|
||||
return Err(CommandError::InvalidConsumption(Some(ARG_POS.into())));
|
||||
};
|
||||
|
||||
for target in targets {
|
||||
let yaw = target.living_entity.entity.yaw.load();
|
||||
set_spawnpoint(sender, target, *pos, yaw).await;
|
||||
}
|
||||
|
||||
Ok(targets.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `/spawnpoint <targets> <pos> <angle>` - set targets at position with angle
|
||||
struct TargetsPosAngleExecutor;
|
||||
|
||||
impl CommandExecutor for TargetsPosAngleExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = PlayersArgumentConsumer.find_arg_default_name(args)?;
|
||||
let Some(Arg::BlockPos(pos)) = args.get(ARG_POS) else {
|
||||
return Err(CommandError::InvalidConsumption(Some(ARG_POS.into())));
|
||||
};
|
||||
let Some(Arg::Rotation(yaw, _, _, _)) = args.get(ARG_ANGLE) else {
|
||||
return Err(CommandError::InvalidConsumption(Some(ARG_ANGLE.into())));
|
||||
};
|
||||
|
||||
for target in targets {
|
||||
set_spawnpoint(sender, target, *pos, *yaw).await;
|
||||
}
|
||||
|
||||
Ok(targets.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn set_spawnpoint(sender: &CommandSender, target: &Arc<Player>, pos: BlockPos, yaw: f32) {
|
||||
let dimension = &target.world().dimension;
|
||||
|
||||
target
|
||||
.set_respawn_point(dimension.clone(), pos, yaw, 0.0, true)
|
||||
.await;
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SPAWNPOINT_SUCCESS_SINGLE,
|
||||
translation::bedrock::COMMANDS_SPAWNPOINT_SUCCESS_SINGLE,
|
||||
[
|
||||
TextComponent::text(target.gameprofile.name.clone()),
|
||||
TextComponent::text(pos.0.x.to_string()),
|
||||
TextComponent::text(pos.0.y.to_string()),
|
||||
TextComponent::text(pos.0.z.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION)
|
||||
.execute(SelfExecutor)
|
||||
.then(
|
||||
argument(ARG_TARGETS, PlayersArgumentConsumer)
|
||||
.execute(TargetsExecutor)
|
||||
.then(
|
||||
argument(ARG_POS, BlockPosArgumentConsumer)
|
||||
.execute(TargetsPosExecutor)
|
||||
.then(
|
||||
argument(ARG_ANGLE, RotationArgumentConsumer)
|
||||
.execute(TargetsPosAngleExecutor),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::command::args::entity::EntityArgumentConsumer;
|
||||
use crate::command::args::players::PlayersArgumentConsumer;
|
||||
use crate::command::args::{Arg, ConsumedArgs, FindArg};
|
||||
use crate::command::dispatcher::CommandError::{self, InvalidConsumption, InvalidRequirement};
|
||||
use crate::command::tree::CommandTree;
|
||||
use crate::command::tree::builder::{argument, require};
|
||||
use crate::command::{CommandExecutor, CommandResult, CommandSender};
|
||||
use crate::entity::EntityBase;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_protocol::java::client::play::CSetCamera;
|
||||
use pumpkin_util::GameMode;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const NAMES: [&str; 1] = ["spectate"];
|
||||
|
||||
const DESCRIPTION: &str = "Allows a player in spectator mode to spectate a given target entity.";
|
||||
|
||||
const ARG_TARGET: &str = "target";
|
||||
const ARG_PLAYER: &str = "player";
|
||||
|
||||
struct StopSpectateExecutor;
|
||||
|
||||
impl CommandExecutor for StopSpectateExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(player) = sender.as_player() else {
|
||||
return Err(InvalidRequirement);
|
||||
};
|
||||
|
||||
if player.gamemode.load() != GameMode::Spectator {
|
||||
let display_name = player.get_display_name().await;
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SPECTATE_NOT_SPECTATOR,
|
||||
translation::java::COMMANDS_SPECTATE_NOT_SPECTATOR,
|
||||
[display_name],
|
||||
)));
|
||||
}
|
||||
|
||||
player.camera_target_id.store(None);
|
||||
player
|
||||
.client
|
||||
.send_packet_now(&CSetCamera::new(player.entity_id().into()))
|
||||
.await;
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SPECTATE_SUCCESS_STOPPED,
|
||||
translation::java::COMMANDS_SPECTATE_SUCCESS_STOPPED,
|
||||
[],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct SpectateTargetSelfExecutor;
|
||||
|
||||
impl CommandExecutor for SpectateTargetSelfExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(player) = sender.as_player() else {
|
||||
return Err(InvalidRequirement);
|
||||
};
|
||||
|
||||
if player.gamemode.load() != GameMode::Spectator {
|
||||
let display_name = player.get_display_name().await;
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SPECTATE_NOT_SPECTATOR,
|
||||
translation::java::COMMANDS_SPECTATE_NOT_SPECTATOR,
|
||||
[display_name],
|
||||
)));
|
||||
}
|
||||
|
||||
let target = EntityArgumentConsumer::find_arg(args, ARG_TARGET)?;
|
||||
|
||||
let target_entity = target.get_entity();
|
||||
if target_entity.entity_id == player.entity_id() {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SPECTATE_SELF,
|
||||
translation::java::COMMANDS_SPECTATE_SELF,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
let target_world = target_entity.world.load_full();
|
||||
let player_world = player.world();
|
||||
if !Arc::ptr_eq(&target_world, &player_world) {
|
||||
let target_name = target.get_display_name().await;
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SPECTATE_CANNOT_SPECTATE,
|
||||
translation::java::COMMANDS_SPECTATE_CANNOT_SPECTATE,
|
||||
[target_name],
|
||||
)));
|
||||
}
|
||||
|
||||
let target_id = target_entity.entity_id;
|
||||
player.camera_target_id.store(Some(target_id));
|
||||
player
|
||||
.client
|
||||
.send_packet_now(&CSetCamera::new(target_id.into()))
|
||||
.await;
|
||||
|
||||
let pos = target_entity.pos.load();
|
||||
let yaw = target_entity.yaw.load();
|
||||
let pitch = target_entity.pitch.load();
|
||||
player
|
||||
.clone()
|
||||
.teleport(pos, Some(yaw), Some(pitch), player_world)
|
||||
.await;
|
||||
|
||||
let target_name = target.get_display_name().await;
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SPECTATE_SUCCESS_STARTED,
|
||||
translation::java::COMMANDS_SPECTATE_SUCCESS_STARTED,
|
||||
[target_name],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct SpectateTargetOtherExecutor;
|
||||
|
||||
impl CommandExecutor for SpectateTargetOtherExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Players(players)) = args.get(ARG_PLAYER) else {
|
||||
return Err(InvalidConsumption(Some(ARG_PLAYER.into())));
|
||||
};
|
||||
|
||||
let target = EntityArgumentConsumer::find_arg(args, ARG_TARGET)?;
|
||||
let target_entity = target.get_entity();
|
||||
let target_world = target_entity.world.load_full();
|
||||
|
||||
// First validate all players
|
||||
for player in players {
|
||||
if player.gamemode.load() != GameMode::Spectator {
|
||||
let display_name = player.get_display_name().await;
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SPECTATE_NOT_SPECTATOR,
|
||||
translation::java::COMMANDS_SPECTATE_NOT_SPECTATOR,
|
||||
[display_name],
|
||||
)));
|
||||
}
|
||||
|
||||
if target_entity.entity_id == player.entity_id() {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SPECTATE_SELF,
|
||||
translation::java::COMMANDS_SPECTATE_SELF,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
let player_world = player.world();
|
||||
if !Arc::ptr_eq(&target_world, &player_world) {
|
||||
let target_name = target.get_display_name().await;
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SPECTATE_CANNOT_SPECTATE,
|
||||
translation::java::COMMANDS_SPECTATE_CANNOT_SPECTATE,
|
||||
[target_name],
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
let mut succeeded = 0;
|
||||
for player in players {
|
||||
let target_id = target_entity.entity_id;
|
||||
player.camera_target_id.store(Some(target_id));
|
||||
player
|
||||
.client
|
||||
.send_packet_now(&CSetCamera::new(target_id.into()))
|
||||
.await;
|
||||
|
||||
let pos = target_entity.pos.load();
|
||||
let yaw = target_entity.yaw.load();
|
||||
let pitch = target_entity.pitch.load();
|
||||
let player_world = player.world();
|
||||
player
|
||||
.clone()
|
||||
.teleport(pos, Some(yaw), Some(pitch), player_world)
|
||||
.await;
|
||||
succeeded += 1;
|
||||
}
|
||||
|
||||
let target_name = target.get_display_name().await;
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SPECTATE_SUCCESS_STARTED,
|
||||
translation::java::COMMANDS_SPECTATE_SUCCESS_STARTED,
|
||||
[target_name],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(succeeded)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::redundant_closure_for_method_calls)]
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION)
|
||||
.then(
|
||||
argument(ARG_TARGET, EntityArgumentConsumer)
|
||||
.then(require(|sender| sender.is_player()).execute(SpectateTargetSelfExecutor))
|
||||
.then(
|
||||
argument(ARG_PLAYER, PlayersArgumentConsumer)
|
||||
.execute(SpectateTargetOtherExecutor),
|
||||
),
|
||||
)
|
||||
.then(require(|sender| sender.is_player()).execute(StopSpectateExecutor))
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_world::chunk::ChunkHeightmapType;
|
||||
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command};
|
||||
use crate::command::argument_types::coordinates::column_pos::ColumnPosArgumentType;
|
||||
use crate::command::argument_types::core::bool::BoolArgumentType;
|
||||
use crate::command::argument_types::core::float::FloatArgumentType;
|
||||
use crate::command::argument_types::entity::EntityArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use crate::world::World;
|
||||
|
||||
const DESCRIPTION: &str = "Teleports entities to random surface locations within an area.";
|
||||
|
||||
const PERMISSION: &str = "minecraft:command.spreadplayers";
|
||||
|
||||
const ARG_CENTER: &str = "center";
|
||||
const ARG_SPREAD_DISTANCE: &str = "spreadDistance";
|
||||
const ARG_MAX_RANGE: &str = "maxRange";
|
||||
const ARG_RESPECT_TEAMS: &str = "respectTeams";
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
|
||||
/// The maximum number of relaxation/retry iterations, matching Vanilla.
|
||||
const MAX_ITERATIONS: usize = 10000;
|
||||
|
||||
const FAILED_ENTITIES_ERROR_TYPE: CommandErrorType<4> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_SPREADPLAYERS_FAILED_ENTITIES,
|
||||
translation::bedrock::COMMANDS_SPREADPLAYERS_FAILURE_PLAYERS,
|
||||
);
|
||||
|
||||
const FAILED_TEAMS_ERROR_TYPE: CommandErrorType<4> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_SPREADPLAYERS_FAILED_TEAMS,
|
||||
translation::bedrock::COMMANDS_SPREADPLAYERS_FAILURE_TEAMS,
|
||||
);
|
||||
|
||||
/// A candidate spread location, equivalent to Vanilla's
|
||||
/// `SpreadPlayersCommand.Position`.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Pile {
|
||||
x: f64,
|
||||
z: f64,
|
||||
}
|
||||
|
||||
impl Pile {
|
||||
fn distance(&self, other: &Self) -> f64 {
|
||||
let dx = self.x - other.x;
|
||||
let dz = self.z - other.z;
|
||||
dx.hypot(dz)
|
||||
}
|
||||
|
||||
fn randomize(&mut self, min_x: f64, min_z: f64, max_x: f64, max_z: f64) {
|
||||
self.x = rand::random_range(min_x..=max_x);
|
||||
self.z = rand::random_range(min_z..=max_z);
|
||||
}
|
||||
|
||||
/// Clamps this pile into the spread area. Returns whether it moved.
|
||||
fn clamp(&mut self, min_x: f64, min_z: f64, max_x: f64, max_z: f64) -> bool {
|
||||
let mut moved = false;
|
||||
if self.x < min_x {
|
||||
self.x = min_x;
|
||||
moved = true;
|
||||
} else if self.x > max_x {
|
||||
self.x = max_x;
|
||||
moved = true;
|
||||
}
|
||||
if self.z < min_z {
|
||||
self.z = min_z;
|
||||
moved = true;
|
||||
} else if self.z > max_z {
|
||||
self.z = max_z;
|
||||
moved = true;
|
||||
}
|
||||
moved
|
||||
}
|
||||
|
||||
/// Returns the y coordinate an entity should stand at for this pile, or
|
||||
/// `None` if the location is unsafe (on top of a liquid).
|
||||
async fn surface_y(&self, world: &World) -> Option<i32> {
|
||||
let block_x = self.x.floor() as i32;
|
||||
let block_z = self.z.floor() as i32;
|
||||
let top = world
|
||||
.get_heightmap_height_async(ChunkHeightmapType::WorldSurface, block_x, block_z)
|
||||
.await;
|
||||
|
||||
let ground = pumpkin_util::math::position::BlockPos(Vector3::new(block_x, top, block_z));
|
||||
let state = world.get_block_state_async(&ground).await;
|
||||
if state.is_liquid() {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(top + 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Spreads `piles` apart until every pair is at least `spread_distance` apart
|
||||
/// and all piles are inside the spread area, mirroring Vanilla's algorithm.
|
||||
/// Returns whether the piles converged within [`MAX_ITERATIONS`].
|
||||
fn spread_piles(
|
||||
piles: &mut [Pile],
|
||||
spread_distance: f64,
|
||||
min_x: f64,
|
||||
min_z: f64,
|
||||
max_x: f64,
|
||||
max_z: f64,
|
||||
) -> bool {
|
||||
for _ in 0..MAX_ITERATIONS {
|
||||
let mut moved = false;
|
||||
for i in 0..piles.len() {
|
||||
let mut push = Pile::default();
|
||||
let mut collisions = 0;
|
||||
|
||||
for j in 0..piles.len() {
|
||||
if i == j {
|
||||
continue;
|
||||
}
|
||||
let distance = piles[i].distance(&piles[j]);
|
||||
if distance < spread_distance {
|
||||
collisions += 1;
|
||||
push.x += piles[j].x - piles[i].x;
|
||||
push.z += piles[j].z - piles[i].z;
|
||||
}
|
||||
}
|
||||
|
||||
if collisions > 0 {
|
||||
push.x /= f64::from(collisions);
|
||||
push.z /= f64::from(collisions);
|
||||
let length = push.x.hypot(push.z);
|
||||
if length > 0.0 {
|
||||
piles[i].x -= push.x / length;
|
||||
piles[i].z -= push.z / length;
|
||||
} else {
|
||||
piles[i].randomize(min_x, min_z, max_x, max_z);
|
||||
}
|
||||
moved = true;
|
||||
}
|
||||
|
||||
if piles[i].clamp(min_x, min_z, max_x, max_z) {
|
||||
moved = true;
|
||||
}
|
||||
}
|
||||
if !moved {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
struct SpreadArea {
|
||||
min_x: f64,
|
||||
min_z: f64,
|
||||
max_x: f64,
|
||||
max_z: f64,
|
||||
}
|
||||
|
||||
/// Randomizes, relaxes, and grounds `pile_count` piles inside `area`.
|
||||
/// Returns the piles and their standing y coordinates, or `None` if no safe
|
||||
/// arrangement was found.
|
||||
async fn find_spread_positions(
|
||||
world: &World,
|
||||
pile_count: usize,
|
||||
spread_distance: f64,
|
||||
area: &SpreadArea,
|
||||
) -> Option<(Vec<Pile>, Vec<i32>)> {
|
||||
let mut piles = vec![Pile::default(); pile_count];
|
||||
for pile in &mut piles {
|
||||
pile.randomize(area.min_x, area.min_z, area.max_x, area.max_z);
|
||||
}
|
||||
|
||||
let mut surface_ys = vec![0; pile_count];
|
||||
// A handful of surface retries is plenty; each retry re-runs the
|
||||
// full relaxation, so this loop must stay small.
|
||||
for _ in 0..16 {
|
||||
if !spread_piles(
|
||||
&mut piles,
|
||||
spread_distance,
|
||||
area.min_x,
|
||||
area.min_z,
|
||||
area.max_x,
|
||||
area.max_z,
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut all_safe = true;
|
||||
for (pile, y) in piles.iter_mut().zip(&mut surface_ys) {
|
||||
if let Some(surface) = pile.surface_y(world).await {
|
||||
*y = surface;
|
||||
} else {
|
||||
pile.randomize(area.min_x, area.min_z, area.max_x, area.max_z);
|
||||
all_safe = false;
|
||||
}
|
||||
}
|
||||
if all_safe {
|
||||
return Some((piles, surface_ys));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns the average distance from each pile to its closest neighbor.
|
||||
fn average_min_distance(piles: &[Pile]) -> f64 {
|
||||
if piles.len() < 2 {
|
||||
return 0.0;
|
||||
}
|
||||
let mut total = 0.0;
|
||||
for pile in piles {
|
||||
let mut closest = f64::MAX;
|
||||
for other in piles {
|
||||
if !std::ptr::eq(pile, other) {
|
||||
closest = closest.min(pile.distance(other));
|
||||
}
|
||||
}
|
||||
total += closest;
|
||||
}
|
||||
#[expect(clippy::cast_precision_loss)]
|
||||
let count = piles.len() as f64;
|
||||
total / count
|
||||
}
|
||||
|
||||
struct SpreadPlayersExecutor;
|
||||
|
||||
impl CommandExecutor for SpreadPlayersExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let center = ColumnPosArgumentType::get_column_pos(context, ARG_CENTER)?;
|
||||
let spread_distance = f64::from(FloatArgumentType::get(context, ARG_SPREAD_DISTANCE)?);
|
||||
let max_range = f64::from(FloatArgumentType::get(context, ARG_MAX_RANGE)?);
|
||||
let respect_teams = BoolArgumentType::get(context, ARG_RESPECT_TEAMS)?;
|
||||
let targets = EntityArgumentType::get_entities(context, ARG_TARGETS).await?;
|
||||
|
||||
// Vanilla center-corrects the vec2 argument to the middle of the block.
|
||||
let center_x = f64::from(center.0.x) + 0.5;
|
||||
let center_z = f64::from(center.0.y) + 0.5;
|
||||
let area = SpreadArea {
|
||||
min_x: center_x - max_range,
|
||||
min_z: center_z - max_range,
|
||||
max_x: center_x + max_range,
|
||||
max_z: center_z + max_range,
|
||||
};
|
||||
|
||||
// Teams are not implemented yet, so every target is teamless. With
|
||||
// respectTeams=true that matches Vanilla's behavior of gathering all
|
||||
// teamless entities onto a single position.
|
||||
let pile_count = if respect_teams { 1 } else { targets.len() };
|
||||
|
||||
let world = context.source.world().clone();
|
||||
|
||||
let Some((piles, surface_ys)) =
|
||||
find_spread_positions(&world, pile_count, spread_distance, &area).await
|
||||
else {
|
||||
let error_type = if respect_teams {
|
||||
&FAILED_TEAMS_ERROR_TYPE
|
||||
} else {
|
||||
&FAILED_ENTITIES_ERROR_TYPE
|
||||
};
|
||||
#[expect(clippy::cast_precision_loss)]
|
||||
let suggested = max_range / (pile_count as f64).sqrt();
|
||||
return Err(error_type.create_without_context(
|
||||
TextComponent::text(pile_count.to_string()),
|
||||
TextComponent::text(format!("{center_x:.2}")),
|
||||
TextComponent::text(format!("{center_z:.2}")),
|
||||
TextComponent::text(format!("{suggested:.2}")),
|
||||
));
|
||||
};
|
||||
|
||||
for (index, target) in targets.iter().enumerate() {
|
||||
let pile = piles[index % pile_count];
|
||||
let y = surface_ys[index % pile_count];
|
||||
target
|
||||
.clone()
|
||||
.teleport(
|
||||
Vector3::new(pile.x.floor() + 0.5, f64::from(y), pile.z.floor() + 0.5),
|
||||
None,
|
||||
None,
|
||||
world.clone(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
let average_distance = average_min_distance(&piles);
|
||||
|
||||
let success_key = if respect_teams {
|
||||
(
|
||||
translation::java::COMMANDS_SPREADPLAYERS_SUCCESS_TEAMS,
|
||||
translation::java::COMMANDS_SPREADPLAYERS_SUCCESS_TEAMS,
|
||||
)
|
||||
} else {
|
||||
(
|
||||
translation::java::COMMANDS_SPREADPLAYERS_SUCCESS_ENTITIES,
|
||||
translation::java::COMMANDS_SPREADPLAYERS_SUCCESS_ENTITIES,
|
||||
)
|
||||
};
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
success_key.0,
|
||||
success_key.1,
|
||||
[
|
||||
TextComponent::text(pile_count.to_string()),
|
||||
TextComponent::text(format!("{center_x:.2}")),
|
||||
TextComponent::text(format!("{center_z:.2}")),
|
||||
TextComponent::text(format!("{average_distance:.2}")),
|
||||
],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
#[expect(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
|
||||
Ok(pile_count as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("spreadplayers", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.then(
|
||||
argument(ARG_CENTER, ColumnPosArgumentType).then(
|
||||
argument(ARG_SPREAD_DISTANCE, FloatArgumentType::with_min(0.0)).then(
|
||||
argument(ARG_MAX_RANGE, FloatArgumentType::with_min(1.0)).then(
|
||||
argument(ARG_RESPECT_TEAMS, BoolArgumentType).then(
|
||||
argument(ARG_TARGETS, EntityArgumentType::Entities)
|
||||
.executes(SpreadPlayersExecutor),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_util::text::color::NamedColor;
|
||||
|
||||
use crate::command::argument_builder::{ArgumentBuilder, command};
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use crate::stop_server;
|
||||
|
||||
const DESCRIPTION: &str = "Stop the server.";
|
||||
|
||||
const PERMISSION: &str = "minecraft:command.stop";
|
||||
|
||||
struct StopCommandExecutor;
|
||||
|
||||
impl CommandExecutor for StopCommandExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_STOP_STOPPING,
|
||||
translation::bedrock::COMMANDS_STOP_START,
|
||||
[],
|
||||
)
|
||||
.color_named(NamedColor::Red),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
stop_server();
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Four),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("stop", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.executes(StopCommandExecutor),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
use crate::command::{
|
||||
CommandExecutor, CommandResult, CommandSender,
|
||||
args::{
|
||||
ConsumedArgs, FindArg, players::PlayersArgumentConsumer, sound::SoundArgumentConsumer,
|
||||
sound_category::SoundCategoryArgumentConsumer,
|
||||
},
|
||||
tree::{CommandTree, builder::argument},
|
||||
};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const NAMES: [&str; 1] = ["stopsound"];
|
||||
const DESCRIPTION: &str = "Stops a currently playing sound.";
|
||||
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
const ARG_SOURCE: &str = "source";
|
||||
const ARG_SOUND: &str = "sound";
|
||||
|
||||
pub struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = PlayersArgumentConsumer::find_arg(args, ARG_TARGETS)?;
|
||||
|
||||
let category = SoundCategoryArgumentConsumer::find_arg(args, ARG_SOURCE);
|
||||
let sound = SoundArgumentConsumer::find_arg(args, ARG_SOUND);
|
||||
|
||||
for target in targets {
|
||||
target
|
||||
.stop_sound(
|
||||
sound
|
||||
.as_ref()
|
||||
.cloned()
|
||||
.map(|s| format!("minecraft:{}", s.to_name()))
|
||||
.ok(),
|
||||
category.as_ref().map(|s| **s).ok(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
let text = match (category, sound) {
|
||||
(Ok(c), Ok(s)) => TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_STOPSOUND_SUCCESS_SOURCE_SOUND,
|
||||
translation::java::COMMANDS_STOPSOUND_SUCCESS_SOURCE_SOUND,
|
||||
[
|
||||
TextComponent::text(s.to_name()),
|
||||
TextComponent::text(c.to_name()),
|
||||
],
|
||||
),
|
||||
(Ok(c), Err(_)) => TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_STOPSOUND_SUCCESS_SOURCE_ANY,
|
||||
translation::java::COMMANDS_STOPSOUND_SUCCESS_SOURCE_ANY,
|
||||
[TextComponent::text(c.to_name())],
|
||||
),
|
||||
(Err(_), Ok(s)) => TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_STOPSOUND_SUCCESS_SOURCELESS_SOUND,
|
||||
translation::java::COMMANDS_STOPSOUND_SUCCESS_SOURCELESS_SOUND,
|
||||
[TextComponent::text(s.to_name())],
|
||||
),
|
||||
(Err(_), Err(_)) => TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_STOPSOUND_SUCCESS_SOURCELESS_ANY,
|
||||
translation::java::COMMANDS_STOPSOUND_SUCCESS_SOURCELESS_ANY,
|
||||
[],
|
||||
),
|
||||
};
|
||||
sender.send_message(text).await;
|
||||
|
||||
Ok(targets.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(ARG_TARGETS, PlayersArgumentConsumer)
|
||||
.execute(Executor)
|
||||
.then(
|
||||
argument(ARG_SOURCE, SoundCategoryArgumentConsumer)
|
||||
.execute(Executor)
|
||||
.then(argument(ARG_SOUND, SoundArgumentConsumer).execute(Executor)),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
use crate::entity::EntityBase;
|
||||
use crate::{
|
||||
command::{
|
||||
CommandError, CommandExecutor, CommandResult, CommandSender,
|
||||
args::{
|
||||
ConsumedArgs, FindArg, position_3d::Position3DArgumentConsumer,
|
||||
summonable_entities::SummonableEntitiesArgumentConsumer,
|
||||
},
|
||||
tree::{CommandTree, builder::argument},
|
||||
},
|
||||
entity::r#type::from_type,
|
||||
};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::{math::vector3::Vector3, text::TextComponent};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::block::entities::BlockEntity;
|
||||
|
||||
const NAMES: [&str; 1] = ["summon"];
|
||||
|
||||
const DESCRIPTION: &str = "Spawns a Entity at position.";
|
||||
|
||||
const ARG_ENTITY: &str = "entity";
|
||||
|
||||
const ARG_POS: &str = "pos";
|
||||
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let entity_type = SummonableEntitiesArgumentConsumer::find_arg(args, ARG_ENTITY)?;
|
||||
let pos = Position3DArgumentConsumer::find_arg(args, ARG_POS);
|
||||
let (world, pos) = match sender {
|
||||
CommandSender::Console | CommandSender::Rcon(_) | CommandSender::Dummy => {
|
||||
let guard = server.worlds.load();
|
||||
let world = guard
|
||||
.first()
|
||||
.cloned()
|
||||
.ok_or(CommandError::InvalidRequirement)?;
|
||||
let pos = {
|
||||
let info = &world.level_info.load();
|
||||
// default position for spawning a player, in this case for mob
|
||||
pos.unwrap_or(Vector3::new(
|
||||
f64::from(info.spawn_x) + 0.5,
|
||||
f64::from(info.spawn_y) + 1.0,
|
||||
f64::from(info.spawn_z) + 0.5,
|
||||
))
|
||||
};
|
||||
|
||||
(world, pos)
|
||||
}
|
||||
CommandSender::Player(player) => {
|
||||
let pos = pos.unwrap_or(player.get_entity().pos.load());
|
||||
|
||||
(player.world(), pos)
|
||||
}
|
||||
CommandSender::CommandBlock(c, w) => {
|
||||
let pos = pos.unwrap_or(c.get_position().to_centered_f64());
|
||||
(w.clone(), pos)
|
||||
}
|
||||
};
|
||||
let entity = from_type(entity_type, pos, &world, Uuid::new_v4());
|
||||
let name = entity.get_display_name().await;
|
||||
world.spawn_entity(entity).await;
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_SUMMON_SUCCESS,
|
||||
translation::bedrock::COMMANDS_SUMMON_SUCCESS,
|
||||
[name],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(ARG_ENTITY, SummonableEntitiesArgumentConsumer)
|
||||
.execute(Executor)
|
||||
.then(argument(ARG_POS, Position3DArgumentConsumer).execute(Executor)),
|
||||
// TODO: Add NBT
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command, literal};
|
||||
use crate::command::argument_types::core::string::StringArgumentType;
|
||||
use crate::command::argument_types::entity::EntityArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
|
||||
const DESCRIPTION: &str = "Manages the scoreboard tags of entities.";
|
||||
|
||||
const PERMISSION: &str = "minecraft:command.tag";
|
||||
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
const ARG_NAME: &str = "name";
|
||||
|
||||
const ADD_FAILED_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_TAG_ADD_FAILED,
|
||||
translation::bedrock::COMMANDS_TAG_ADD_FAILED,
|
||||
);
|
||||
|
||||
const REMOVE_FAILED_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_TAG_REMOVE_FAILED,
|
||||
translation::bedrock::COMMANDS_TAG_REMOVE_FAILED,
|
||||
);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Action {
|
||||
Add,
|
||||
Remove,
|
||||
}
|
||||
|
||||
struct ChangeExecutor(Action);
|
||||
|
||||
impl CommandExecutor for ChangeExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_entities(context, ARG_TARGETS).await?;
|
||||
let tag = StringArgumentType::get(context, ARG_NAME)?.to_owned();
|
||||
|
||||
let mut changed = 0;
|
||||
for target in &targets {
|
||||
let entity = target.get_entity();
|
||||
let success = match self.0 {
|
||||
Action::Add => entity.add_scoreboard_tag(&tag).await,
|
||||
Action::Remove => entity.remove_scoreboard_tag(&tag).await,
|
||||
};
|
||||
if success {
|
||||
changed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if changed == 0 {
|
||||
return Err(match self.0 {
|
||||
Action::Add => ADD_FAILED_ERROR_TYPE.create_without_context(),
|
||||
Action::Remove => REMOVE_FAILED_ERROR_TYPE.create_without_context(),
|
||||
});
|
||||
}
|
||||
|
||||
let (single_key, multiple_key) = match self.0 {
|
||||
Action::Add => (
|
||||
(
|
||||
translation::java::COMMANDS_TAG_ADD_SUCCESS_SINGLE,
|
||||
translation::bedrock::COMMANDS_TAG_ADD_SUCCESS_SINGLE,
|
||||
),
|
||||
(
|
||||
translation::java::COMMANDS_TAG_ADD_SUCCESS_MULTIPLE,
|
||||
translation::bedrock::COMMANDS_TAG_ADD_SUCCESS_MULTIPLE,
|
||||
),
|
||||
),
|
||||
Action::Remove => (
|
||||
(
|
||||
translation::java::COMMANDS_TAG_REMOVE_SUCCESS_SINGLE,
|
||||
translation::bedrock::COMMANDS_TAG_REMOVE_SUCCESS_SINGLE,
|
||||
),
|
||||
(
|
||||
translation::java::COMMANDS_TAG_REMOVE_SUCCESS_MULTIPLE,
|
||||
translation::bedrock::COMMANDS_TAG_REMOVE_SUCCESS_MULTIPLE,
|
||||
),
|
||||
),
|
||||
};
|
||||
|
||||
let msg = if targets.len() == 1 {
|
||||
TextComponent::translate_cross(
|
||||
single_key.0,
|
||||
single_key.1,
|
||||
[
|
||||
TextComponent::text(tag),
|
||||
targets[0].get_display_name().await,
|
||||
],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
multiple_key.0,
|
||||
multiple_key.1,
|
||||
[
|
||||
TextComponent::text(tag),
|
||||
TextComponent::text(targets.len().to_string()),
|
||||
],
|
||||
)
|
||||
};
|
||||
|
||||
context.source.send_feedback(msg, true).await;
|
||||
|
||||
Ok(changed)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ListExecutor;
|
||||
|
||||
impl CommandExecutor for ListExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntityArgumentType::get_entities(context, ARG_TARGETS).await?;
|
||||
|
||||
// BTreeSet keeps the output deterministic.
|
||||
let mut all_tags = BTreeSet::new();
|
||||
for target in &targets {
|
||||
let tags = target.get_entity().scoreboard_tags.lock().await;
|
||||
all_tags.extend(tags.iter().cloned());
|
||||
}
|
||||
|
||||
let tag_list =
|
||||
TextComponent::text(all_tags.iter().cloned().collect::<Vec<String>>().join(", "));
|
||||
|
||||
let msg = if targets.len() == 1 {
|
||||
let name = targets[0].get_display_name().await;
|
||||
if all_tags.is_empty() {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TAG_LIST_SINGLE_EMPTY,
|
||||
translation::bedrock::COMMANDS_TAG_LIST_SINGLE_EMPTY,
|
||||
[name],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TAG_LIST_SINGLE_SUCCESS,
|
||||
translation::bedrock::COMMANDS_TAG_LIST_SINGLE_SUCCESS,
|
||||
[
|
||||
name,
|
||||
TextComponent::text(all_tags.len().to_string()),
|
||||
tag_list,
|
||||
],
|
||||
)
|
||||
}
|
||||
} else {
|
||||
let count = TextComponent::text(targets.len().to_string());
|
||||
if all_tags.is_empty() {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TAG_LIST_MULTIPLE_EMPTY,
|
||||
translation::bedrock::COMMANDS_TAG_LIST_MULTIPLE_EMPTY,
|
||||
[count],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TAG_LIST_MULTIPLE_SUCCESS,
|
||||
translation::bedrock::COMMANDS_TAG_LIST_MULTIPLE_SUCCESS,
|
||||
[
|
||||
count,
|
||||
TextComponent::text(all_tags.len().to_string()),
|
||||
tag_list,
|
||||
],
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
context.source.send_feedback(msg, false).await;
|
||||
|
||||
Ok(all_tags.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Two),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("tag", DESCRIPTION).requires(PERMISSION).then(
|
||||
argument(ARG_TARGETS, EntityArgumentType::Entities)
|
||||
.then(
|
||||
literal("add").then(
|
||||
argument(ARG_NAME, StringArgumentType::SingleWord)
|
||||
.executes(ChangeExecutor(Action::Add)),
|
||||
),
|
||||
)
|
||||
.then(literal("list").executes(ListExecutor))
|
||||
.then(
|
||||
literal("remove").then(
|
||||
argument(ARG_NAME, StringArgumentType::SingleWord)
|
||||
.executes(ChangeExecutor(Action::Remove)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,100 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command};
|
||||
use crate::command::argument_types::core::string::StringArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const DESCRIPTION: &str = "Sends a message to your team.";
|
||||
const PERMISSION: &str = "minecraft:command.teammsg";
|
||||
const ARG_MESSAGE: &str = "message";
|
||||
|
||||
const NO_TEAM_ERROR: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_TEAMMSG_FAILED_NOTEAM,
|
||||
translation::java::COMMANDS_TEAMMSG_FAILED_NOTEAM,
|
||||
);
|
||||
|
||||
struct TeamMsgCommandExecutor;
|
||||
|
||||
impl CommandExecutor for TeamMsgCommandExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let player = context.source.player_or_err()?;
|
||||
let sender_name = &player.gameprofile.name;
|
||||
let world = context.world();
|
||||
let scoreboard = world.scoreboard.lock().await;
|
||||
|
||||
let mut sender_team = None;
|
||||
for team in scoreboard.get_teams().values() {
|
||||
if team.players.contains(sender_name) {
|
||||
sender_team = Some(team.clone());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let Some(team) = sender_team else {
|
||||
return Err(NO_TEAM_ERROR.create_without_context());
|
||||
};
|
||||
|
||||
let team_display_name = team.display_name.clone().color_named(team.color);
|
||||
let sender_display_name = context.source.display_name.clone();
|
||||
let message_text = StringArgumentType::get(context, ARG_MESSAGE)?;
|
||||
let message_component = TextComponent::text(message_text.to_string());
|
||||
|
||||
let online_players = world.players.load();
|
||||
let mut sent_count = 0;
|
||||
|
||||
for player in online_players.iter() {
|
||||
if team.players.contains(&player.gameprofile.name) {
|
||||
let msg = if player.gameprofile.name == *sender_name {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::CHAT_TYPE_TEAM_SENT,
|
||||
translation::java::CHAT_TYPE_TEAM_SENT,
|
||||
[
|
||||
team_display_name.clone(),
|
||||
sender_display_name.clone(),
|
||||
message_component.clone(),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
translation::java::CHAT_TYPE_TEAM_TEXT,
|
||||
translation::java::CHAT_TYPE_TEAM_TEXT,
|
||||
[
|
||||
team_display_name.clone(),
|
||||
sender_display_name.clone(),
|
||||
message_component.clone(),
|
||||
],
|
||||
)
|
||||
};
|
||||
|
||||
player.send_system_message(&msg).await;
|
||||
sent_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(sent_count)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Allow,
|
||||
));
|
||||
|
||||
// Register /teammsg <message>
|
||||
dispatcher.register(command("teammsg", DESCRIPTION).requires(PERMISSION).then(
|
||||
argument(ARG_MESSAGE, StringArgumentType::GreedyPhrase).executes(TeamMsgCommandExecutor),
|
||||
));
|
||||
|
||||
// Register alias /tm <message>
|
||||
dispatcher.register(command("tm", DESCRIPTION).requires(PERMISSION).then(
|
||||
argument(ARG_MESSAGE, StringArgumentType::GreedyPhrase).executes(TeamMsgCommandExecutor),
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::math::position::BlockPos;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::command::CommandError;
|
||||
use crate::command::CommandResult;
|
||||
use crate::command::args::ConsumedArgs;
|
||||
use crate::command::args::FindArg;
|
||||
use crate::command::args::entities::EntitiesArgumentConsumer;
|
||||
use crate::command::args::entity::EntityArgumentConsumer;
|
||||
use crate::command::args::position_3d::Position3DArgumentConsumer;
|
||||
use crate::command::args::rotation::RotationArgumentConsumer;
|
||||
use crate::command::tree::CommandTree;
|
||||
use crate::command::tree::builder::{argument, literal};
|
||||
use crate::command::{CommandExecutor, CommandSender};
|
||||
use crate::entity::EntityBase;
|
||||
use crate::world::World;
|
||||
|
||||
const NAMES: [&str; 2] = ["teleport", "tp"];
|
||||
const DESCRIPTION: &str = "Teleports entities, including players."; // todo
|
||||
|
||||
/// position
|
||||
const ARG_LOCATION: &str = "location";
|
||||
|
||||
/// single entity
|
||||
const ARG_DESTINATION: &str = "destination";
|
||||
|
||||
/// multiple entities
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
|
||||
/// rotation: yaw/pitch
|
||||
const ARG_ROTATION: &str = "rotation";
|
||||
|
||||
/// single entity
|
||||
const ARG_FACING_ENTITY: &str = "facingEntity";
|
||||
|
||||
/// position
|
||||
const ARG_FACING_LOCATION: &str = "facingLocation";
|
||||
|
||||
fn yaw_pitch_facing_position(
|
||||
looking_from: &Vector3<f64>,
|
||||
looking_towards: &Vector3<f64>,
|
||||
) -> (f32, f32) {
|
||||
let direction_vector = (looking_towards.sub(looking_from)).normalize();
|
||||
|
||||
let yaw_radians = -direction_vector.x.atan2(direction_vector.z);
|
||||
let pitch_radians = (-direction_vector.y).asin();
|
||||
|
||||
let yaw_degrees = yaw_radians.to_degrees();
|
||||
let pitch_degrees = pitch_radians.to_degrees();
|
||||
|
||||
(yaw_degrees as f32, pitch_degrees as f32)
|
||||
}
|
||||
|
||||
fn resolve_sender_world(
|
||||
sender: &CommandSender,
|
||||
server: &crate::server::Server,
|
||||
) -> std::sync::Arc<World> {
|
||||
sender
|
||||
.world_or_first(server)
|
||||
.expect("Server should have at least one world")
|
||||
}
|
||||
|
||||
struct EntitiesToEntityExecutor;
|
||||
|
||||
impl CommandExecutor for EntitiesToEntityExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntitiesArgumentConsumer::find_arg(args, ARG_TARGETS)?;
|
||||
|
||||
let destination = EntityArgumentConsumer::find_arg(args, ARG_DESTINATION)?;
|
||||
let destination = destination.get_entity();
|
||||
let pos = destination.pos.load();
|
||||
let yaw = destination.yaw.load();
|
||||
let pitch = destination.pitch.load();
|
||||
let world = destination.world.load_full();
|
||||
if !World::is_valid(BlockPos(pos.floor_to_i32())) {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TELEPORT_INVALIDPOSITION,
|
||||
translation::java::COMMANDS_TELEPORT_INVALIDPOSITION,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
for target in targets {
|
||||
target
|
||||
.clone()
|
||||
.teleport(pos, Some(yaw), Some(pitch), world.clone())
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(targets.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct EntitiesToPosFacingPosExecutor;
|
||||
|
||||
impl CommandExecutor for EntitiesToPosFacingPosExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntitiesArgumentConsumer::find_arg(args, ARG_TARGETS)?;
|
||||
|
||||
let pos = Position3DArgumentConsumer::find_arg(args, ARG_LOCATION)?;
|
||||
if !World::is_valid(BlockPos(pos.floor_to_i32())) {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TELEPORT_INVALIDPOSITION,
|
||||
translation::java::COMMANDS_TELEPORT_INVALIDPOSITION,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
let facing_pos = Position3DArgumentConsumer::find_arg(args, ARG_FACING_LOCATION)?;
|
||||
let (yaw, pitch) = yaw_pitch_facing_position(&pos, &facing_pos);
|
||||
let world = resolve_sender_world(sender, server);
|
||||
|
||||
for target in targets {
|
||||
target
|
||||
.clone()
|
||||
.teleport(pos, Some(yaw), Some(pitch), world.clone())
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(targets.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct EntitiesToPosFacingEntityExecutor;
|
||||
|
||||
impl CommandExecutor for EntitiesToPosFacingEntityExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntitiesArgumentConsumer::find_arg(args, ARG_TARGETS)?;
|
||||
|
||||
let pos = Position3DArgumentConsumer::find_arg(args, ARG_LOCATION)?;
|
||||
if !World::is_valid(BlockPos(pos.floor_to_i32())) {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TELEPORT_INVALIDPOSITION,
|
||||
translation::java::COMMANDS_TELEPORT_INVALIDPOSITION,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
let facing_entity = EntityArgumentConsumer::find_arg(args, ARG_FACING_ENTITY)?;
|
||||
let (yaw, pitch) =
|
||||
yaw_pitch_facing_position(&pos, &facing_entity.get_entity().pos.load());
|
||||
let world = resolve_sender_world(sender, server);
|
||||
|
||||
for target in targets {
|
||||
target
|
||||
.clone()
|
||||
.teleport(pos, Some(yaw), Some(pitch), world.clone())
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(targets.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct EntitiesToPosWithRotationExecutor;
|
||||
|
||||
impl CommandExecutor for EntitiesToPosWithRotationExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntitiesArgumentConsumer::find_arg(args, ARG_TARGETS)?;
|
||||
|
||||
let pos = Position3DArgumentConsumer::find_arg(args, ARG_LOCATION)?;
|
||||
if !World::is_valid(BlockPos(pos.floor_to_i32())) {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TELEPORT_INVALIDPOSITION,
|
||||
translation::java::COMMANDS_TELEPORT_INVALIDPOSITION,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
// Note: Rotation returns (yaw, is_yaw_relative, pitch, is_pitch_relative)
|
||||
// For teleport, we use absolute values only (ignore relative flags)
|
||||
let (yaw, _, pitch, _) = RotationArgumentConsumer::find_arg(args, ARG_ROTATION)?;
|
||||
let world = resolve_sender_world(sender, server);
|
||||
|
||||
for target in targets {
|
||||
target
|
||||
.clone()
|
||||
.teleport(pos, Some(yaw), Some(pitch), world.clone())
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(targets.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct EntitiesToPosExecutor;
|
||||
|
||||
impl CommandExecutor for EntitiesToPosExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let targets = EntitiesArgumentConsumer::find_arg(args, ARG_TARGETS)?;
|
||||
|
||||
let pos = Position3DArgumentConsumer::find_arg(args, ARG_LOCATION)?;
|
||||
if !World::is_valid(BlockPos(pos.floor_to_i32())) {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TELEPORT_INVALIDPOSITION,
|
||||
translation::java::COMMANDS_TELEPORT_INVALIDPOSITION,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
let world = resolve_sender_world(sender, server);
|
||||
for target in targets {
|
||||
let yaw = target.get_entity().yaw.load();
|
||||
let pitch = target.get_entity().pitch.load();
|
||||
target
|
||||
.clone()
|
||||
.teleport(pos, Some(yaw), Some(pitch), world.clone())
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(targets.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct SelfToEntityExecutor;
|
||||
|
||||
impl CommandExecutor for SelfToEntityExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let destination = EntityArgumentConsumer::find_arg(args, ARG_DESTINATION)?;
|
||||
let destination = destination.get_entity();
|
||||
let pos = destination.pos.load();
|
||||
let yaw = destination.yaw.load();
|
||||
let pitch = destination.pitch.load();
|
||||
let world = destination.world.load_full();
|
||||
|
||||
match sender {
|
||||
CommandSender::Player(player) => {
|
||||
if !World::is_valid(BlockPos(pos.floor_to_i32())) {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TELEPORT_INVALIDPOSITION,
|
||||
translation::java::COMMANDS_TELEPORT_INVALIDPOSITION,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
player
|
||||
.clone()
|
||||
.teleport(pos, Some(yaw), Some(pitch), world)
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
}
|
||||
_ => Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::PERMISSIONS_REQUIRES_PLAYER,
|
||||
translation::java::PERMISSIONS_REQUIRES_PLAYER,
|
||||
[],
|
||||
))),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
struct SelfToPosExecutor;
|
||||
|
||||
impl CommandExecutor for SelfToPosExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
match sender {
|
||||
CommandSender::Player(player) => {
|
||||
let pos = Position3DArgumentConsumer::find_arg(args, ARG_LOCATION)?;
|
||||
let yaw = player.get_entity().yaw.load();
|
||||
let pitch = player.get_entity().pitch.load();
|
||||
if !World::is_valid(BlockPos(pos.floor_to_i32())) {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TELEPORT_INVALIDPOSITION,
|
||||
translation::java::COMMANDS_TELEPORT_INVALIDPOSITION,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
player
|
||||
.clone()
|
||||
.teleport(pos, Some(yaw), Some(pitch), player.world().clone())
|
||||
.await;
|
||||
|
||||
Ok(1)
|
||||
}
|
||||
_ => Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::PERMISSIONS_REQUIRES_PLAYER,
|
||||
translation::java::PERMISSIONS_REQUIRES_PLAYER,
|
||||
[],
|
||||
))),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION)
|
||||
.then(argument(ARG_LOCATION, Position3DArgumentConsumer).execute(SelfToPosExecutor))
|
||||
.then(argument(ARG_DESTINATION, EntityArgumentConsumer).execute(SelfToEntityExecutor))
|
||||
.then(
|
||||
argument(ARG_TARGETS, EntitiesArgumentConsumer)
|
||||
.then(
|
||||
argument(ARG_LOCATION, Position3DArgumentConsumer)
|
||||
.execute(EntitiesToPosExecutor)
|
||||
.then(
|
||||
argument(ARG_ROTATION, RotationArgumentConsumer)
|
||||
.execute(EntitiesToPosWithRotationExecutor),
|
||||
)
|
||||
.then(
|
||||
literal("facing")
|
||||
.then(
|
||||
literal("entity").then(
|
||||
argument(ARG_FACING_ENTITY, EntityArgumentConsumer)
|
||||
.execute(EntitiesToPosFacingEntityExecutor),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
argument(ARG_FACING_LOCATION, Position3DArgumentConsumer)
|
||||
.execute(EntitiesToPosFacingPosExecutor),
|
||||
),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
argument(ARG_DESTINATION, EntityArgumentConsumer)
|
||||
.execute(EntitiesToEntityExecutor),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
use crate::command::{
|
||||
CommandError, CommandExecutor, CommandResult, CommandSender,
|
||||
args::{
|
||||
Arg, ConsumedArgs, FindArg, players::PlayersArgumentConsumer,
|
||||
textcomponent::TextComponentArgConsumer,
|
||||
},
|
||||
tree::{CommandTree, builder::argument},
|
||||
};
|
||||
|
||||
const NAMES: [&str; 1] = ["tellraw"];
|
||||
|
||||
const DESCRIPTION: &str = "Send raw message to players.";
|
||||
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
|
||||
const ARG_MESSAGE: &str = "message";
|
||||
|
||||
struct TellRawExecutor;
|
||||
|
||||
impl CommandExecutor for TellRawExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
_sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(CommandError::InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
|
||||
let text = TextComponentArgConsumer::find_arg(args, ARG_MESSAGE)?;
|
||||
for target in targets {
|
||||
target.send_system_message(&text).await;
|
||||
}
|
||||
Ok(targets.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(ARG_TARGETS, PlayersArgumentConsumer)
|
||||
.then(argument(ARG_MESSAGE, TextComponentArgConsumer).execute(TellRawExecutor)),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command, literal};
|
||||
use crate::command::argument_types::core::float::FloatArgumentType;
|
||||
use crate::command::argument_types::time::TimeArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::context::command_source::CommandSource;
|
||||
use crate::command::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use crate::command::suggestion::provider::SuggestionProvider;
|
||||
use crate::command::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::PermissionLvl;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::{
|
||||
TextComponent,
|
||||
color::{Color, NamedColor},
|
||||
};
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
const DESCRIPTION: &str = "Controls or queries the game's ticking state.";
|
||||
const PERMISSION: &str = "minecraft:command.tick";
|
||||
|
||||
// Helper function to format nanoseconds to milliseconds with 2 decimal places
|
||||
fn nanos_to_millis_string(nanos: i64) -> String {
|
||||
format!("{:.2}", nanos as f64 / 1_000_000.0)
|
||||
}
|
||||
|
||||
enum SubCommand {
|
||||
Query,
|
||||
Rate,
|
||||
Freeze(bool),
|
||||
StepDefault,
|
||||
StepTimed,
|
||||
StepStop,
|
||||
SprintTimed,
|
||||
SprintStop,
|
||||
}
|
||||
|
||||
struct TickExecutor(SubCommand);
|
||||
|
||||
impl TickExecutor {
|
||||
async fn handle_query(
|
||||
source: &CommandSource,
|
||||
manager: &crate::server::tick_rate_manager::ServerTickRateManager,
|
||||
) -> Result<i32, CommandSyntaxError> {
|
||||
let tick_rate = manager.tickrate();
|
||||
let avg_tick_nanos = source.server().get_average_tick_time_nanos();
|
||||
let avg_mspt_str = nanos_to_millis_string(avg_tick_nanos);
|
||||
|
||||
if manager.is_sprinting() {
|
||||
source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TICK_STATUS_SPRINTING,
|
||||
translation::java::COMMANDS_TICK_STATUS_SPRINTING,
|
||||
[],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TICK_QUERY_RATE_SPRINTING,
|
||||
translation::java::COMMANDS_TICK_QUERY_RATE_SPRINTING,
|
||||
[
|
||||
TextComponent::text(format!("{tick_rate:.1}")),
|
||||
TextComponent::text(avg_mspt_str),
|
||||
],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
} else {
|
||||
Self::handle_non_sprinting_status(source, manager, avg_tick_nanos).await;
|
||||
|
||||
let target_mspt_str = nanos_to_millis_string(manager.nanoseconds_per_tick());
|
||||
source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TICK_QUERY_RATE_RUNNING,
|
||||
translation::java::COMMANDS_TICK_QUERY_RATE_RUNNING,
|
||||
[
|
||||
TextComponent::text(format!("{tick_rate:.1}")),
|
||||
TextComponent::text(avg_mspt_str),
|
||||
TextComponent::text(target_mspt_str),
|
||||
],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
Self::send_percentiles(source, source.server()).await;
|
||||
Ok(tick_rate as i32)
|
||||
}
|
||||
async fn handle_non_sprinting_status(
|
||||
sender: &CommandSource,
|
||||
manager: &crate::server::tick_rate_manager::ServerTickRateManager,
|
||||
avg_tick_nanos: i64,
|
||||
) {
|
||||
if manager.is_frozen() {
|
||||
sender
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TICK_STATUS_FROZEN,
|
||||
translation::java::COMMANDS_TICK_STATUS_FROZEN,
|
||||
[],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
} else if avg_tick_nanos > manager.nanoseconds_per_tick() {
|
||||
sender
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TICK_STATUS_LAGGING,
|
||||
translation::java::COMMANDS_TICK_STATUS_LAGGING,
|
||||
[],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
} else {
|
||||
sender
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TICK_STATUS_RUNNING,
|
||||
translation::java::COMMANDS_TICK_STATUS_RUNNING,
|
||||
[],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_percentiles(sender: &CommandSource, server: &crate::server::Server) {
|
||||
let tick_count = server.tick_count.load(Ordering::Relaxed);
|
||||
let sample_size = (tick_count as usize).min(100);
|
||||
|
||||
if sample_size > 0 {
|
||||
let mut tick_times = server.get_tick_times_nanos_copy().await;
|
||||
let relevant_ticks = &mut tick_times[..sample_size];
|
||||
relevant_ticks.sort_unstable();
|
||||
|
||||
let p50_nanos = relevant_ticks[sample_size / 2];
|
||||
let p95_nanos = relevant_ticks[(sample_size as f32 * 0.95).floor() as usize];
|
||||
let p99_nanos = relevant_ticks[(sample_size as f32 * 0.99).floor() as usize];
|
||||
|
||||
sender
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TICK_QUERY_PERCENTILES,
|
||||
translation::java::COMMANDS_TICK_QUERY_PERCENTILES,
|
||||
[
|
||||
TextComponent::text(nanos_to_millis_string(p50_nanos)),
|
||||
TextComponent::text(nanos_to_millis_string(p95_nanos)),
|
||||
TextComponent::text(nanos_to_millis_string(p99_nanos)),
|
||||
TextComponent::text(sample_size.to_string()),
|
||||
],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
async fn handle_step_command(
|
||||
source: &CommandSource,
|
||||
manager: &crate::server::tick_rate_manager::ServerTickRateManager,
|
||||
ticks: i32,
|
||||
) {
|
||||
if manager.step_game_if_paused(source.server(), ticks) {
|
||||
source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TICK_STEP_SUCCESS,
|
||||
translation::java::COMMANDS_TICK_STEP_SUCCESS,
|
||||
[TextComponent::text(ticks.to_string())],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
} else {
|
||||
source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TICK_STEP_FAIL,
|
||||
translation::java::COMMANDS_TICK_STEP_FAIL,
|
||||
[],
|
||||
)
|
||||
.color_named(NamedColor::Red),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
async fn handle_sprint_command(
|
||||
source: &CommandSource,
|
||||
manager: &crate::server::tick_rate_manager::ServerTickRateManager,
|
||||
ticks: i32,
|
||||
) {
|
||||
if manager.request_game_to_sprint(source.server(), i64::from(ticks)) {
|
||||
source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TICK_SPRINT_STOP_SUCCESS,
|
||||
translation::java::COMMANDS_TICK_SPRINT_STOP_SUCCESS,
|
||||
[],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TICK_STATUS_SPRINTING,
|
||||
translation::java::COMMANDS_TICK_STATUS_SPRINTING,
|
||||
[],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn handle_set_tick_rate(
|
||||
source: &CommandSource,
|
||||
manager: &crate::server::tick_rate_manager::ServerTickRateManager,
|
||||
rate: f32,
|
||||
) -> Result<i32, CommandSyntaxError> {
|
||||
manager.set_tick_rate(source.server(), rate);
|
||||
source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TICK_RATE_SUCCESS,
|
||||
translation::java::COMMANDS_TICK_RATE_SUCCESS,
|
||||
[TextComponent::text(format!("{rate:.1}"))],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
Ok(rate as i32)
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandExecutor for TickExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let manager = &context.server().tick_rate_manager;
|
||||
let source = context.source.as_ref();
|
||||
let server = source.server();
|
||||
match self.0 {
|
||||
SubCommand::Query => Self::handle_query(source, manager).await,
|
||||
SubCommand::Rate => {
|
||||
let rate = FloatArgumentType::get(context, "rate")?;
|
||||
Self::handle_set_tick_rate(source, manager, rate).await
|
||||
}
|
||||
SubCommand::Freeze(freeze) => {
|
||||
manager.set_frozen(server, freeze);
|
||||
let message_key = if freeze {
|
||||
"commands.tick.status.frozen"
|
||||
} else {
|
||||
"commands.tick.status.running"
|
||||
};
|
||||
source
|
||||
.send_feedback(TextComponent::translate(message_key, []), true)
|
||||
.await;
|
||||
Ok(freeze as i32)
|
||||
}
|
||||
SubCommand::StepDefault => {
|
||||
Self::handle_step_command(source, manager, 1).await;
|
||||
Ok(1)
|
||||
}
|
||||
SubCommand::StepTimed => {
|
||||
let ticks = TimeArgumentType::get(context, "time")?;
|
||||
Self::handle_step_command(source, manager, ticks).await;
|
||||
Ok(1)
|
||||
}
|
||||
SubCommand::StepStop => {
|
||||
if manager.stop_stepping(server) {
|
||||
source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TICK_SPRINT_STOP_SUCCESS,
|
||||
translation::java::COMMANDS_TICK_SPRINT_STOP_SUCCESS,
|
||||
[],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
Ok(1)
|
||||
} else {
|
||||
source
|
||||
.send_error(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TICK_SPRINT_STOP_FAIL,
|
||||
translation::java::COMMANDS_TICK_SPRINT_STOP_FAIL,
|
||||
[],
|
||||
))
|
||||
.await;
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
SubCommand::SprintTimed => {
|
||||
Self::handle_sprint_command(
|
||||
source,
|
||||
manager,
|
||||
TimeArgumentType::get(context, "time")?,
|
||||
)
|
||||
.await;
|
||||
Ok(1)
|
||||
}
|
||||
SubCommand::SprintStop => {
|
||||
if manager.stop_sprinting(server) {
|
||||
source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TICK_SPRINT_STOP_SUCCESS,
|
||||
translation::java::COMMANDS_TICK_SPRINT_STOP_SUCCESS,
|
||||
[],
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
Ok(1)
|
||||
} else {
|
||||
source
|
||||
.send_error(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TICK_SPRINT_STOP_FAIL,
|
||||
translation::java::COMMANDS_TICK_SPRINT_STOP_FAIL,
|
||||
[],
|
||||
)
|
||||
.color(Color::Named(NamedColor::Red)),
|
||||
)
|
||||
.await;
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct TickSuggestionProvider(&'static [&'static str]);
|
||||
|
||||
impl SuggestionProvider for TickSuggestionProvider {
|
||||
fn suggest(
|
||||
&self,
|
||||
_context: &CommandContext,
|
||||
mut builder: SuggestionsBuilder,
|
||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send>> {
|
||||
let names = self.0;
|
||||
|
||||
Box::pin(async move {
|
||||
for suggestion in names {
|
||||
builder = builder.suggest(*suggestion);
|
||||
}
|
||||
builder.build()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const fn time_argument() -> TimeArgumentType {
|
||||
TimeArgumentType::new(1)
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Op(PermissionLvl::Three),
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("tick", DESCRIPTION)
|
||||
.requires(PERMISSION)
|
||||
.then(literal("query").executes(TickExecutor(SubCommand::Query)))
|
||||
.then(
|
||||
literal("rate").then(
|
||||
argument("rate", FloatArgumentType::new(1.0, 10000.0))
|
||||
.suggests(TickSuggestionProvider(&["20"]))
|
||||
.executes(TickExecutor(SubCommand::Rate)),
|
||||
),
|
||||
)
|
||||
.then(literal("freeze").executes(TickExecutor(SubCommand::Freeze(true))))
|
||||
.then(literal("unfreeze").executes(TickExecutor(SubCommand::Freeze(false))))
|
||||
.then(
|
||||
literal("step")
|
||||
.then(literal("stop").executes(TickExecutor(SubCommand::StepStop)))
|
||||
.then(
|
||||
argument("time", time_argument())
|
||||
.suggests(TickSuggestionProvider(&["1t", "1s"]))
|
||||
.executes(TickExecutor(SubCommand::StepTimed)),
|
||||
)
|
||||
.executes(TickExecutor(SubCommand::StepDefault)),
|
||||
)
|
||||
.then(
|
||||
literal("sprint")
|
||||
.then(literal("stop").executes(TickExecutor(SubCommand::SprintStop)))
|
||||
.then(
|
||||
argument("time", time_argument())
|
||||
.suggests(TickSuggestionProvider(&["60s", "1d", "3d"]))
|
||||
.executes(TickExecutor(SubCommand::SprintTimed)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::command::CommandResult;
|
||||
use crate::command::args::{FindArg, time::TimeArgumentConsumer};
|
||||
use crate::command::dispatcher::CommandError;
|
||||
use crate::command::tree::builder::{argument, literal};
|
||||
use crate::command::{CommandExecutor, CommandSender, ConsumedArgs, tree::CommandTree};
|
||||
|
||||
const NAMES: [&str; 1] = ["time"];
|
||||
const DESCRIPTION: &str = "Query the world time.";
|
||||
const ARG_TIME: &str = "time";
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum PresetTime {
|
||||
Day,
|
||||
Noon,
|
||||
Night,
|
||||
Midnight,
|
||||
}
|
||||
|
||||
impl PresetTime {
|
||||
const fn to_ticks(self) -> i32 {
|
||||
match self {
|
||||
Self::Day => 1000,
|
||||
Self::Noon => 6000,
|
||||
Self::Night => 13000,
|
||||
Self::Midnight => 18000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Mode {
|
||||
Add,
|
||||
Set(Option<PresetTime>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum QueryMode {
|
||||
DayTime,
|
||||
GameTime,
|
||||
Day,
|
||||
}
|
||||
|
||||
struct QueryExecutor(QueryMode);
|
||||
|
||||
impl CommandExecutor for QueryExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let mode = self.0;
|
||||
// TODO: Maybe ask player for world, or get the current world
|
||||
let worlds = server.worlds.load();
|
||||
let world = worlds
|
||||
.first()
|
||||
.expect("There should always be at least one world");
|
||||
let level_time = world.level_time.lock().await;
|
||||
|
||||
let curr_time = match mode {
|
||||
QueryMode::DayTime => level_time.query_daytime(),
|
||||
QueryMode::GameTime => level_time.query_gametime(),
|
||||
QueryMode::Day => level_time.query_day(),
|
||||
};
|
||||
let bedrock_key = match mode {
|
||||
QueryMode::DayTime => translation::bedrock::COMMANDS_TIME_QUERY_DAYTIME,
|
||||
QueryMode::GameTime => translation::bedrock::COMMANDS_TIME_QUERY_GAMETIME,
|
||||
QueryMode::Day => translation::bedrock::COMMANDS_TIME_QUERY_DAY,
|
||||
};
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TIME_QUERY,
|
||||
bedrock_key,
|
||||
[TextComponent::text(curr_time.to_string())],
|
||||
))
|
||||
.await;
|
||||
Ok(curr_time as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ChangeExecutor(Mode);
|
||||
|
||||
impl CommandExecutor for ChangeExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let time_count = if let Mode::Set(Some(preset)) = &self.0 {
|
||||
preset.to_ticks()
|
||||
} else if let Ok(ticks) = TimeArgumentConsumer::find_arg(args, ARG_TIME) {
|
||||
ticks
|
||||
} else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(
|
||||
"Invalid time specified.",
|
||||
)));
|
||||
};
|
||||
|
||||
let mode = self.0;
|
||||
// TODO: Maybe ask player for world, or get the current world
|
||||
let worlds = server.worlds.load();
|
||||
let world = worlds
|
||||
.first()
|
||||
.expect("There should always be at least one world");
|
||||
let mut level_time = world.level_time.lock().await;
|
||||
|
||||
match mode {
|
||||
Mode::Add => {
|
||||
// add
|
||||
level_time.add_time(time_count.into());
|
||||
level_time.send_time(world).await;
|
||||
let curr_time = level_time.query_daytime();
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TIME_SET,
|
||||
translation::bedrock::COMMANDS_TIME_SET,
|
||||
[TextComponent::text(curr_time.to_string())],
|
||||
))
|
||||
.await;
|
||||
Ok(curr_time as i32)
|
||||
}
|
||||
Mode::Set(_) => {
|
||||
// set
|
||||
level_time.set_time(time_count.into());
|
||||
level_time.send_time(world).await;
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TIME_SET,
|
||||
translation::bedrock::COMMANDS_TIME_SET,
|
||||
[TextComponent::text(time_count.to_string())],
|
||||
))
|
||||
.await;
|
||||
Ok(time_count)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION)
|
||||
.then(
|
||||
literal("add")
|
||||
.then(argument(ARG_TIME, TimeArgumentConsumer).execute(ChangeExecutor(Mode::Add))),
|
||||
)
|
||||
.then(
|
||||
literal("query")
|
||||
.then(literal("daytime").execute(QueryExecutor(QueryMode::DayTime)))
|
||||
.then(literal("gametime").execute(QueryExecutor(QueryMode::GameTime)))
|
||||
.then(literal("day").execute(QueryExecutor(QueryMode::Day))),
|
||||
)
|
||||
.then(
|
||||
literal("set")
|
||||
.then(literal("day").execute(ChangeExecutor(Mode::Set(Some(PresetTime::Day)))))
|
||||
.then(literal("noon").execute(ChangeExecutor(Mode::Set(Some(PresetTime::Noon)))))
|
||||
.then(literal("night").execute(ChangeExecutor(Mode::Set(Some(PresetTime::Night)))))
|
||||
.then(
|
||||
literal("midnight")
|
||||
.execute(ChangeExecutor(Mode::Set(Some(PresetTime::Midnight)))),
|
||||
)
|
||||
.then(
|
||||
argument(ARG_TIME, TimeArgumentConsumer)
|
||||
.execute(ChangeExecutor(Mode::Set(None))),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
use pumpkin_protocol::java::client::play::CClearTitle;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::command::CommandResult;
|
||||
use crate::command::args::time::TimeArgumentConsumer;
|
||||
use crate::entity::EntityBase;
|
||||
use crate::{
|
||||
command::{
|
||||
CommandError, CommandExecutor, CommandSender,
|
||||
args::{
|
||||
Arg, ConsumedArgs, FindArg, players::PlayersArgumentConsumer,
|
||||
textcomponent::TextComponentArgConsumer,
|
||||
},
|
||||
tree::CommandTree,
|
||||
tree::builder::{argument, literal},
|
||||
},
|
||||
entity::player::TitleMode,
|
||||
};
|
||||
|
||||
const NAMES: [&str; 1] = ["title"];
|
||||
|
||||
const DESCRIPTION: &str = "Displays a title.";
|
||||
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
|
||||
const ARG_TITLE: &str = "title";
|
||||
const ARG_FADE_IN: &str = "fadeIn";
|
||||
const ARG_STAY: &str = "stay";
|
||||
const ARG_FADE_OUT: &str = "fadeOut";
|
||||
/// bool: Whether to reset or not
|
||||
struct ClearOrResetExecutor(bool);
|
||||
|
||||
impl CommandExecutor for ClearOrResetExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(CommandError::InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
let reset = self.0;
|
||||
|
||||
for target in targets {
|
||||
target.client.enqueue_packet(&CClearTitle::new(reset)).await;
|
||||
}
|
||||
sender
|
||||
.send_message(if targets.len() == 1 {
|
||||
let text = if reset {
|
||||
"commands.title.reset.single"
|
||||
} else {
|
||||
"commands.title.cleared.single"
|
||||
};
|
||||
TextComponent::translate_cross(
|
||||
text,
|
||||
text,
|
||||
[targets[0].get_display_name().await],
|
||||
)
|
||||
} else {
|
||||
let text = if reset {
|
||||
"commands.title.reset.multiple"
|
||||
} else {
|
||||
"commands.title.cleared.multiple"
|
||||
};
|
||||
TextComponent::translate_cross(
|
||||
text,
|
||||
text,
|
||||
[TextComponent::text(targets.len().to_string())],
|
||||
)
|
||||
})
|
||||
.await;
|
||||
|
||||
Ok(targets.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct TitleExecutor(TitleMode);
|
||||
|
||||
impl CommandExecutor for TitleExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(CommandError::InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
|
||||
let text = TextComponentArgConsumer::find_arg(args, ARG_TITLE)?;
|
||||
|
||||
let mode = &self.0;
|
||||
|
||||
for target in targets {
|
||||
target.show_title(&text, mode).await;
|
||||
}
|
||||
|
||||
let mode_name = format!("{mode:?}").to_lowercase();
|
||||
sender
|
||||
.send_message(if targets.len() == 1 {
|
||||
TextComponent::translate_cross(
|
||||
format!("commands.title.show.{mode_name}.single").clone(),
|
||||
format!("commands.title.show.{mode_name}.single"),
|
||||
[targets[0].get_display_name().await],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
format!("commands.title.show.{mode_name}.multiple"),
|
||||
format!("commands.title.show.{mode_name}.multiple"),
|
||||
[TextComponent::text(targets.len().to_string())],
|
||||
)
|
||||
})
|
||||
.await;
|
||||
|
||||
Ok(targets.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct TimesTitleExecutor;
|
||||
|
||||
impl CommandExecutor for TimesTitleExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(CommandError::InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
|
||||
let fade_in = TimeArgumentConsumer::find_arg(args, ARG_FADE_IN)?;
|
||||
let stay = TimeArgumentConsumer::find_arg(args, ARG_STAY)?;
|
||||
let fade_out = TimeArgumentConsumer::find_arg(args, ARG_FADE_OUT)?;
|
||||
|
||||
for target in targets {
|
||||
target.send_title_animation(fade_in, stay, fade_out).await;
|
||||
}
|
||||
|
||||
sender
|
||||
.send_message(if targets.len() == 1 {
|
||||
TextComponent::translate_cross(
|
||||
"commands.title.times.single",
|
||||
"commands.title.times.single",
|
||||
[targets[0].get_display_name().await],
|
||||
)
|
||||
} else {
|
||||
TextComponent::translate_cross(
|
||||
"commands.title.times.multiple",
|
||||
"commands.title.times.multiple",
|
||||
[TextComponent::text(targets.len().to_string())],
|
||||
)
|
||||
})
|
||||
.await;
|
||||
|
||||
Ok(targets.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(ARG_TARGETS, PlayersArgumentConsumer)
|
||||
.then(literal("clear").execute(ClearOrResetExecutor(false)))
|
||||
.then(literal("reset").execute(ClearOrResetExecutor(true)))
|
||||
.then(
|
||||
literal("title").then(
|
||||
argument(ARG_TITLE, TextComponentArgConsumer)
|
||||
.execute(TitleExecutor(TitleMode::Title)),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("subtitle").then(
|
||||
argument(ARG_TITLE, TextComponentArgConsumer)
|
||||
.execute(TitleExecutor(TitleMode::SubTitle)),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("actionbar").then(
|
||||
argument(ARG_TITLE, TextComponentArgConsumer)
|
||||
.execute(TitleExecutor(TitleMode::ActionBar)),
|
||||
),
|
||||
)
|
||||
.then(literal("times").then(
|
||||
argument(ARG_FADE_IN, TimeArgumentConsumer).then(
|
||||
argument(ARG_STAY, TimeArgumentConsumer).then(
|
||||
argument(ARG_FADE_OUT, TimeArgumentConsumer).execute(TimesTitleExecutor),
|
||||
),
|
||||
),
|
||||
)),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use crate::command::CommandResult;
|
||||
use crate::command::{CommandExecutor, CommandSender, args::ConsumedArgs, tree::CommandTree};
|
||||
use pumpkin_util::text::{TextComponent, color::NamedColor};
|
||||
|
||||
const NAMES: [&str; 1] = ["tps"];
|
||||
|
||||
const DESCRIPTION: &str = "Displays the server TPS and MSPT.";
|
||||
|
||||
struct Executor;
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let tps = server.get_tps().min(server.basic_config.tps as f64);
|
||||
let mspt = server.get_mspt();
|
||||
|
||||
let max_tps = server.basic_config.tps as f64;
|
||||
let tps_color = if tps >= max_tps * 0.9 {
|
||||
NamedColor::Green
|
||||
} else if tps >= max_tps * 0.75 {
|
||||
NamedColor::Yellow
|
||||
} else {
|
||||
NamedColor::Red
|
||||
};
|
||||
|
||||
let message = TextComponent::text("TPS: ")
|
||||
.add_child(TextComponent::text(format!("{tps:.1}")).color_named(tps_color))
|
||||
.add_child(TextComponent::text(" MSPT: "))
|
||||
.add_child(TextComponent::text(format!("{mspt:.2}ms")).color_named(tps_color));
|
||||
|
||||
sender.send_message(message).await;
|
||||
|
||||
Ok(tps as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).execute(Executor)
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
use pumpkin_protocol::bedrock::client::transfer::CTransfer as BedrockCTransfer;
|
||||
use pumpkin_protocol::codec::var_int::VarInt;
|
||||
use pumpkin_protocol::java::client::play::CTransfer as JavaCTransfer;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use tracing::info;
|
||||
|
||||
use crate::command::CommandResult;
|
||||
use crate::command::args::bounded_num::BoundedNumArgumentConsumer;
|
||||
use crate::command::args::players::PlayersArgumentConsumer;
|
||||
use crate::command::args::simple::SimpleArgConsumer;
|
||||
use crate::command::args::{Arg, FindArgDefaultName};
|
||||
use crate::command::dispatcher::CommandError::{self, InvalidConsumption, InvalidRequirement};
|
||||
use crate::command::tree::builder::{argument, argument_default_name, require};
|
||||
use crate::command::{CommandExecutor, CommandSender, args::ConsumedArgs, tree::CommandTree};
|
||||
use crate::entity::EntityBase;
|
||||
use crate::net::ClientPlatform;
|
||||
|
||||
const NAMES: [&str; 1] = ["transfer"];
|
||||
|
||||
const DESCRIPTION: &str = "Triggers a transfer of a player to another server.";
|
||||
|
||||
const ARG_HOSTNAME: &str = "hostname";
|
||||
|
||||
const ARG_PLAYERS: &str = "players";
|
||||
|
||||
const fn port_consumer() -> BoundedNumArgumentConsumer<i32> {
|
||||
BoundedNumArgumentConsumer::new()
|
||||
.name("port")
|
||||
.min(1)
|
||||
.max(65535)
|
||||
}
|
||||
|
||||
struct TargetSelfExecutor;
|
||||
|
||||
impl CommandExecutor for TargetSelfExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Simple(hostname)) = args.get(ARG_HOSTNAME) else {
|
||||
return Err(InvalidConsumption(Some(ARG_HOSTNAME.into())));
|
||||
};
|
||||
|
||||
let port = match port_consumer().find_arg_default_name(args) {
|
||||
Err(_) => 25565,
|
||||
Ok(Ok(count)) => count,
|
||||
Ok(Err(_)) => {
|
||||
return Err(InvalidConsumption(Some(
|
||||
"Port must be between 1 and 65535.".into(),
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
if let CommandSender::Player(player) = sender {
|
||||
let name = &player.gameprofile.name;
|
||||
info!("[{name}: Transferring {name} to {hostname}:{port}]");
|
||||
|
||||
match player.client.as_ref() {
|
||||
ClientPlatform::Java(client) => {
|
||||
client
|
||||
.enqueue_packet(&JavaCTransfer::new(hostname, VarInt(port)))
|
||||
.await;
|
||||
}
|
||||
ClientPlatform::Bedrock(client) => {
|
||||
client
|
||||
.send_game_packet(&BedrockCTransfer::new(
|
||||
hostname.to_string(),
|
||||
port as u16,
|
||||
false,
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(1)
|
||||
} else {
|
||||
Err(InvalidRequirement)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct TargetPlayerExecutor;
|
||||
|
||||
impl CommandExecutor for TargetPlayerExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
_server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::Simple(hostname)) = args.get(ARG_HOSTNAME) else {
|
||||
return Err(InvalidConsumption(Some(ARG_HOSTNAME.into())));
|
||||
};
|
||||
let hostname = *hostname;
|
||||
|
||||
let port = match port_consumer().find_arg_default_name(args) {
|
||||
Err(_) => 25565,
|
||||
Ok(Ok(count)) => count,
|
||||
Ok(Err(_)) => {
|
||||
return Err(InvalidConsumption(Some(
|
||||
"Port must be between 1 and 65535.".into(),
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
let Some(Arg::Players(players)) = args.get(ARG_PLAYERS) else {
|
||||
return Err(InvalidConsumption(Some(ARG_PLAYERS.into())));
|
||||
};
|
||||
|
||||
if players.is_empty() {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.transfer.error.no_players",
|
||||
"commands.transfer.error.no_players",
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
for p in players {
|
||||
match p.client.as_ref() {
|
||||
ClientPlatform::Java(client) => {
|
||||
client
|
||||
.enqueue_packet(&JavaCTransfer::new(hostname, VarInt(port)))
|
||||
.await;
|
||||
}
|
||||
ClientPlatform::Bedrock(client) => {
|
||||
client
|
||||
.send_game_packet(&BedrockCTransfer::new(
|
||||
hostname.to_string(),
|
||||
port as u16,
|
||||
false,
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
info!(
|
||||
"[{sender}: Transferring {} to {hostname}:{port}]",
|
||||
p.gameprofile.name
|
||||
);
|
||||
}
|
||||
|
||||
if players.len() == 1 {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.transfer.success.single",
|
||||
"commands.transfer.success.single",
|
||||
[
|
||||
players[0].get_display_name().await,
|
||||
TextComponent::text(hostname.to_owned()),
|
||||
TextComponent::text(port.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
} else {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.transfer.success.multiple",
|
||||
"commands.transfer.success.multiple",
|
||||
[
|
||||
TextComponent::text(players.len().to_string()),
|
||||
TextComponent::text(hostname.to_owned()),
|
||||
TextComponent::text(port.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(players.len() as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::redundant_closure_for_method_calls)]
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION).then(
|
||||
argument(ARG_HOSTNAME, SimpleArgConsumer)
|
||||
.then(require(|sender| sender.is_player()).execute(TargetSelfExecutor))
|
||||
.then(
|
||||
argument_default_name(port_consumer())
|
||||
.then(require(|sender| sender.is_player()).execute(TargetSelfExecutor))
|
||||
.then(
|
||||
argument(ARG_PLAYERS, PlayersArgumentConsumer)
|
||||
.execute(TargetPlayerExecutor),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
use crate::command::argument_builder::{ArgumentBuilder, argument, command, literal};
|
||||
use crate::command::argument_types::core::integer::IntegerArgumentType;
|
||||
use crate::command::argument_types::objective::ObjectiveArgumentType;
|
||||
use crate::command::context::command_context::CommandContext;
|
||||
use crate::command::errors::error_types::CommandErrorType;
|
||||
use crate::command::node::dispatcher::CommandDispatcher;
|
||||
use crate::command::node::{CommandExecutor, CommandExecutorResult};
|
||||
use crate::world::scoreboard::ScoreboardScore;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_protocol::codec::var_int::VarInt;
|
||||
use pumpkin_util::permission::{Permission, PermissionDefault, PermissionRegistry};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const DESCRIPTION: &str = "Modifies a trigger scoreboard objective.";
|
||||
const PERMISSION: &str = "minecraft:command.trigger";
|
||||
|
||||
const ARG_OBJECTIVE: &str = "objective";
|
||||
const ARG_VALUE: &str = "value";
|
||||
|
||||
const INVALID_TRIGGER_ERROR: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_TRIGGER_FAILED_INVALID,
|
||||
translation::java::COMMANDS_TRIGGER_FAILED_INVALID,
|
||||
);
|
||||
|
||||
const UNPRIMED_TRIGGER_ERROR: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_TRIGGER_FAILED_UNPRIMED,
|
||||
translation::java::COMMANDS_TRIGGER_FAILED_UNPRIMED,
|
||||
);
|
||||
|
||||
struct SimpleTriggerExecutor;
|
||||
|
||||
impl CommandExecutor for SimpleTriggerExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let player = context.source.player_or_err()?;
|
||||
let player_name = &player.gameprofile.name;
|
||||
let objective_name = ObjectiveArgumentType::get(context, ARG_OBJECTIVE)?;
|
||||
|
||||
let world = context.world();
|
||||
let mut scoreboard = world.scoreboard.lock().await;
|
||||
|
||||
let objective = scoreboard
|
||||
.get_objectives()
|
||||
.get(objective_name)
|
||||
.ok_or_else(|| INVALID_TRIGGER_ERROR.create_without_context())?;
|
||||
|
||||
if objective.criterion != "trigger" {
|
||||
return Err(INVALID_TRIGGER_ERROR.create_without_context());
|
||||
}
|
||||
|
||||
let objective_display_name = objective.display_name.clone();
|
||||
|
||||
let is_locked = scoreboard
|
||||
.get_scores()
|
||||
.get(objective_name)
|
||||
.and_then(|m| m.get(player_name))
|
||||
.is_none_or(|s| s.locked);
|
||||
|
||||
if is_locked {
|
||||
return Err(UNPRIMED_TRIGGER_ERROR.create_without_context());
|
||||
}
|
||||
|
||||
let current_value = scoreboard
|
||||
.get_scores()
|
||||
.get(objective_name)
|
||||
.and_then(|m| m.get(player_name))
|
||||
.map_or(0, |s| s.value.0);
|
||||
|
||||
let new_value = current_value + 1;
|
||||
|
||||
let updated_score = ScoreboardScore {
|
||||
entity_name: Box::leak(player_name.clone().into_boxed_str()),
|
||||
objective_name: Box::leak(objective_name.to_string().into_boxed_str()),
|
||||
value: VarInt(new_value),
|
||||
display_name: None,
|
||||
number_format: None,
|
||||
locked: true,
|
||||
};
|
||||
|
||||
scoreboard.update_score(world, updated_score).await;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TRIGGER_SIMPLE_SUCCESS,
|
||||
translation::java::COMMANDS_TRIGGER_SIMPLE_SUCCESS,
|
||||
[objective_display_name],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(new_value)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct AddTriggerExecutor;
|
||||
|
||||
impl CommandExecutor for AddTriggerExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let player = context.source.player_or_err()?;
|
||||
let player_name = &player.gameprofile.name;
|
||||
let objective_name = ObjectiveArgumentType::get(context, ARG_OBJECTIVE)?;
|
||||
let value = IntegerArgumentType::get(context, ARG_VALUE)?;
|
||||
|
||||
let world = context.world();
|
||||
let mut scoreboard = world.scoreboard.lock().await;
|
||||
|
||||
let objective = scoreboard
|
||||
.get_objectives()
|
||||
.get(objective_name)
|
||||
.ok_or_else(|| INVALID_TRIGGER_ERROR.create_without_context())?;
|
||||
|
||||
if objective.criterion != "trigger" {
|
||||
return Err(INVALID_TRIGGER_ERROR.create_without_context());
|
||||
}
|
||||
|
||||
let objective_display_name = objective.display_name.clone();
|
||||
|
||||
let is_locked = scoreboard
|
||||
.get_scores()
|
||||
.get(objective_name)
|
||||
.and_then(|m| m.get(player_name))
|
||||
.is_none_or(|s| s.locked);
|
||||
|
||||
if is_locked {
|
||||
return Err(UNPRIMED_TRIGGER_ERROR.create_without_context());
|
||||
}
|
||||
|
||||
let current_value = scoreboard
|
||||
.get_scores()
|
||||
.get(objective_name)
|
||||
.and_then(|m| m.get(player_name))
|
||||
.map_or(0, |s| s.value.0);
|
||||
|
||||
let new_value = current_value + value;
|
||||
|
||||
let updated_score = ScoreboardScore {
|
||||
entity_name: Box::leak(player_name.clone().into_boxed_str()),
|
||||
objective_name: Box::leak(objective_name.to_string().into_boxed_str()),
|
||||
value: VarInt(new_value),
|
||||
display_name: None,
|
||||
number_format: None,
|
||||
locked: true,
|
||||
};
|
||||
|
||||
scoreboard.update_score(world, updated_score).await;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TRIGGER_ADD_SUCCESS,
|
||||
translation::java::COMMANDS_TRIGGER_ADD_SUCCESS,
|
||||
[
|
||||
objective_display_name,
|
||||
TextComponent::text(value.to_string()),
|
||||
],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(new_value)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct SetTriggerExecutor;
|
||||
|
||||
impl CommandExecutor for SetTriggerExecutor {
|
||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
||||
Box::pin(async move {
|
||||
let player = context.source.player_or_err()?;
|
||||
let player_name = &player.gameprofile.name;
|
||||
let objective_name = ObjectiveArgumentType::get(context, ARG_OBJECTIVE)?;
|
||||
let value = IntegerArgumentType::get(context, ARG_VALUE)?;
|
||||
|
||||
let world = context.world();
|
||||
let mut scoreboard = world.scoreboard.lock().await;
|
||||
|
||||
let objective = scoreboard
|
||||
.get_objectives()
|
||||
.get(objective_name)
|
||||
.ok_or_else(|| INVALID_TRIGGER_ERROR.create_without_context())?;
|
||||
|
||||
if objective.criterion != "trigger" {
|
||||
return Err(INVALID_TRIGGER_ERROR.create_without_context());
|
||||
}
|
||||
|
||||
let objective_display_name = objective.display_name.clone();
|
||||
|
||||
let is_locked = scoreboard
|
||||
.get_scores()
|
||||
.get(objective_name)
|
||||
.and_then(|m| m.get(player_name))
|
||||
.is_none_or(|s| s.locked);
|
||||
|
||||
if is_locked {
|
||||
return Err(UNPRIMED_TRIGGER_ERROR.create_without_context());
|
||||
}
|
||||
|
||||
let updated_score = ScoreboardScore {
|
||||
entity_name: Box::leak(player_name.clone().into_boxed_str()),
|
||||
objective_name: Box::leak(objective_name.to_string().into_boxed_str()),
|
||||
value: VarInt(value),
|
||||
display_name: None,
|
||||
number_format: None,
|
||||
locked: true,
|
||||
};
|
||||
|
||||
scoreboard.update_score(world, updated_score).await;
|
||||
|
||||
context
|
||||
.source
|
||||
.send_feedback(
|
||||
TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_TRIGGER_SET_SUCCESS,
|
||||
translation::java::COMMANDS_TRIGGER_SET_SUCCESS,
|
||||
[
|
||||
objective_display_name,
|
||||
TextComponent::text(value.to_string()),
|
||||
],
|
||||
),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(value)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(dispatcher: &mut CommandDispatcher, registry: &mut PermissionRegistry) {
|
||||
registry.register_permission_or_panic(Permission::new(
|
||||
PERMISSION,
|
||||
DESCRIPTION,
|
||||
PermissionDefault::Allow,
|
||||
));
|
||||
|
||||
dispatcher.register(
|
||||
command("trigger", DESCRIPTION).requires(PERMISSION).then(
|
||||
argument(ARG_OBJECTIVE, ObjectiveArgumentType)
|
||||
.executes(SimpleTriggerExecutor)
|
||||
.then(literal("add").then(
|
||||
argument(ARG_VALUE, IntegerArgumentType::any()).executes(AddTriggerExecutor),
|
||||
))
|
||||
.then(literal("set").then(
|
||||
argument(ARG_VALUE, IntegerArgumentType::any()).executes(SetTriggerExecutor),
|
||||
)),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::command::{
|
||||
CommandError, CommandExecutor, CommandResult, CommandSender,
|
||||
args::{ConsumedArgs, FindArg, time::TimeArgumentConsumer},
|
||||
tree::{
|
||||
CommandTree,
|
||||
builder::{argument, literal},
|
||||
},
|
||||
};
|
||||
|
||||
const NAMES: [&str; 1] = ["weather"];
|
||||
const DESCRIPTION: &str = "Changes the weather.";
|
||||
const ARG_DURATION: &str = "duration";
|
||||
|
||||
struct Executor {
|
||||
mode: WeatherMode,
|
||||
}
|
||||
|
||||
enum WeatherMode {
|
||||
Clear,
|
||||
Rain,
|
||||
Thunder,
|
||||
}
|
||||
|
||||
impl CommandExecutor for Executor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let duration = TimeArgumentConsumer::find_arg(args, ARG_DURATION).ok();
|
||||
let world = {
|
||||
let guard = server.worlds.load();
|
||||
|
||||
guard
|
||||
.first()
|
||||
.cloned()
|
||||
.ok_or(CommandError::InvalidRequirement)?
|
||||
};
|
||||
let mut weather = world.weather.lock().await;
|
||||
|
||||
match self.mode {
|
||||
WeatherMode::Clear => {
|
||||
let processed_duration =
|
||||
duration.unwrap_or_else(|| rand::random_range(12_000..=180_000));
|
||||
|
||||
weather.set_weather_parameters(&world, processed_duration, 0, false, false);
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_WEATHER_SET_CLEAR,
|
||||
translation::bedrock::COMMANDS_WEATHER_CLEAR,
|
||||
[],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
WeatherMode::Rain => {
|
||||
let processed_duration =
|
||||
duration.unwrap_or_else(|| rand::random_range(12_000..=24_000));
|
||||
|
||||
weather.set_weather_parameters(&world, 0, processed_duration, true, false);
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_WEATHER_SET_RAIN,
|
||||
translation::bedrock::COMMANDS_WEATHER_RAIN,
|
||||
[],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
WeatherMode::Thunder => {
|
||||
let processed_duration =
|
||||
duration.unwrap_or_else(|| rand::random_range(3_600..=15_600));
|
||||
|
||||
weather.set_weather_parameters(&world, 0, processed_duration, true, true);
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_WEATHER_SET_THUNDER,
|
||||
translation::bedrock::COMMANDS_WEATHER_THUNDER,
|
||||
[],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
// Vanilla returns -1 when duration is not specified
|
||||
Ok(duration.unwrap_or(-1))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION)
|
||||
.then(
|
||||
literal("clear")
|
||||
.then(
|
||||
argument(ARG_DURATION, TimeArgumentConsumer).execute(Executor {
|
||||
mode: WeatherMode::Clear,
|
||||
}),
|
||||
)
|
||||
.execute(Executor {
|
||||
mode: WeatherMode::Clear,
|
||||
}),
|
||||
)
|
||||
.then(
|
||||
literal("rain")
|
||||
.then(
|
||||
argument(ARG_DURATION, TimeArgumentConsumer).execute(Executor {
|
||||
mode: WeatherMode::Rain,
|
||||
}),
|
||||
)
|
||||
.execute(Executor {
|
||||
mode: WeatherMode::Rain,
|
||||
}),
|
||||
)
|
||||
.then(
|
||||
literal("thunder")
|
||||
.then(
|
||||
argument(ARG_DURATION, TimeArgumentConsumer).execute(Executor {
|
||||
mode: WeatherMode::Thunder,
|
||||
}),
|
||||
)
|
||||
.execute(Executor {
|
||||
mode: WeatherMode::Thunder,
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use pumpkin_config::whitelist::WhitelistEntry;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::command::CommandResult;
|
||||
use crate::{
|
||||
command::{
|
||||
CommandExecutor, CommandSender,
|
||||
args::{
|
||||
Arg, ConsumedArgs,
|
||||
gameprofile::{GameProfileSuggestionMode, GameProfilesArgumentConsumer},
|
||||
},
|
||||
dispatcher::CommandError,
|
||||
tree::{
|
||||
CommandTree,
|
||||
builder::{argument, literal},
|
||||
},
|
||||
},
|
||||
data::{LoadJSONConfiguration, SaveJSONConfiguration, whitelist::WhitelistConfig},
|
||||
net::DisconnectReason,
|
||||
server::Server,
|
||||
};
|
||||
|
||||
const NAMES: [&str; 1] = ["whitelist"];
|
||||
const DESCRIPTION: &str = "Manage server whitelists.";
|
||||
const ARG_TARGETS: &str = "targets";
|
||||
|
||||
async fn kick_non_whitelisted_players(server: &Server) {
|
||||
let whitelist = server.data.whitelist_config.read().await;
|
||||
if server.basic_config.enforce_whitelist && server.white_list.load(Ordering::Relaxed) {
|
||||
for player in server.get_all_players() {
|
||||
if whitelist.is_whitelisted(&player.gameprofile) {
|
||||
continue;
|
||||
}
|
||||
player
|
||||
.kick(
|
||||
DisconnectReason::Kicked,
|
||||
TextComponent::translate_cross(
|
||||
translation::java::MULTIPLAYER_DISCONNECT_NOT_WHITELISTED,
|
||||
translation::java::MULTIPLAYER_DISCONNECT_NOT_WHITELISTED,
|
||||
&[],
|
||||
),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct OnExecutor;
|
||||
|
||||
impl CommandExecutor for OnExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let previous = server.white_list.swap(true, Ordering::Relaxed);
|
||||
if previous {
|
||||
Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_WHITELIST_ALREADYON,
|
||||
translation::java::COMMANDS_WHITELIST_ALREADYON,
|
||||
&[],
|
||||
)))
|
||||
} else {
|
||||
kick_non_whitelisted_players(server).await;
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_WHITELIST_ENABLED,
|
||||
translation::java::COMMANDS_WHITELIST_ENABLED,
|
||||
&[],
|
||||
))
|
||||
.await;
|
||||
Ok(1)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct OffExecutor;
|
||||
|
||||
impl CommandExecutor for OffExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let previous = server.white_list.swap(false, Ordering::Relaxed);
|
||||
if previous {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_WHITELIST_DISABLED,
|
||||
translation::java::COMMANDS_WHITELIST_DISABLED,
|
||||
&[],
|
||||
))
|
||||
.await;
|
||||
Ok(1)
|
||||
} else {
|
||||
Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_WHITELIST_ALREADYOFF,
|
||||
translation::java::COMMANDS_WHITELIST_ALREADYOFF,
|
||||
&[],
|
||||
)))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ListExecutor;
|
||||
|
||||
impl CommandExecutor for ListExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let whitelist = &server.data.whitelist_config.read().await.whitelist;
|
||||
if whitelist.is_empty() {
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_WHITELIST_NONE,
|
||||
translation::java::COMMANDS_WHITELIST_NONE,
|
||||
[],
|
||||
))
|
||||
.await;
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let names = whitelist
|
||||
.iter()
|
||||
.map(|entry| entry.name.as_str())
|
||||
.collect::<Vec<&str>>()
|
||||
.join(", ");
|
||||
|
||||
let names_len = names.len() as i32;
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_WHITELIST_LIST,
|
||||
translation::java::COMMANDS_WHITELIST_LIST,
|
||||
[
|
||||
TextComponent::text(whitelist.len().to_string()),
|
||||
TextComponent::text(names),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(names_len)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ReloadExecutor;
|
||||
|
||||
impl CommandExecutor for ReloadExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
*server.data.whitelist_config.write().await = WhitelistConfig::load();
|
||||
kick_non_whitelisted_players(server).await;
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_WHITELIST_RELOADED,
|
||||
translation::java::COMMANDS_WHITELIST_RELOADED,
|
||||
&[],
|
||||
))
|
||||
.await;
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AddExecutor;
|
||||
|
||||
impl CommandExecutor for AddExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(CommandError::InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
|
||||
let mut whitelist = server.data.whitelist_config.write().await;
|
||||
let mut successes: i32 = 0;
|
||||
for profile in targets {
|
||||
if let Some(existing_entry) = whitelist
|
||||
.whitelist
|
||||
.iter_mut()
|
||||
.find(|entry| entry.uuid == profile.id)
|
||||
{
|
||||
if existing_entry.name != profile.name {
|
||||
existing_entry.name.clone_from(&profile.name);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
whitelist
|
||||
.whitelist
|
||||
.push(WhitelistEntry::new(profile.id, profile.name.clone()));
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_WHITELIST_ADD_SUCCESS,
|
||||
translation::java::COMMANDS_WHITELIST_ADD_SUCCESS,
|
||||
[TextComponent::text(profile.name.clone())],
|
||||
))
|
||||
.await;
|
||||
successes += 1;
|
||||
}
|
||||
|
||||
whitelist.save();
|
||||
|
||||
if successes == 0 {
|
||||
Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_WHITELIST_ADD_FAILED,
|
||||
translation::java::COMMANDS_WHITELIST_ADD_FAILED,
|
||||
&[],
|
||||
)))
|
||||
} else {
|
||||
Ok(successes)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RemoveExecutor;
|
||||
|
||||
impl CommandExecutor for RemoveExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGETS) else {
|
||||
return Err(CommandError::InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||
};
|
||||
|
||||
let mut whitelist = server.data.whitelist_config.write().await;
|
||||
let mut successes: i32 = 0;
|
||||
for player in targets {
|
||||
let i = whitelist
|
||||
.whitelist
|
||||
.iter()
|
||||
.position(|entry| entry.uuid == player.id);
|
||||
|
||||
if let Some(i) = i {
|
||||
whitelist.whitelist.remove(i);
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_WHITELIST_REMOVE_SUCCESS,
|
||||
translation::java::COMMANDS_WHITELIST_REMOVE_SUCCESS,
|
||||
[TextComponent::text(player.name.clone())],
|
||||
))
|
||||
.await;
|
||||
successes += 1;
|
||||
}
|
||||
}
|
||||
|
||||
whitelist.save();
|
||||
drop(whitelist);
|
||||
|
||||
kick_non_whitelisted_players(server).await;
|
||||
|
||||
if successes == 0 {
|
||||
Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
translation::java::COMMANDS_WHITELIST_REMOVE_FAILED,
|
||||
translation::java::COMMANDS_WHITELIST_REMOVE_FAILED,
|
||||
&[],
|
||||
)))
|
||||
} else {
|
||||
Ok(successes)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION)
|
||||
.then(literal("on").execute(OnExecutor))
|
||||
.then(literal("off").execute(OffExecutor))
|
||||
.then(literal("list").execute(ListExecutor))
|
||||
.then(literal("reload").execute(ReloadExecutor))
|
||||
.then(
|
||||
literal("add").then(
|
||||
argument(
|
||||
ARG_TARGETS,
|
||||
GameProfilesArgumentConsumer::new(
|
||||
GameProfileSuggestionMode::NonWhitelistedOnlinePlayers,
|
||||
false,
|
||||
),
|
||||
)
|
||||
.execute(AddExecutor),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("remove").then(
|
||||
argument(
|
||||
ARG_TARGETS,
|
||||
GameProfilesArgumentConsumer::new(
|
||||
GameProfileSuggestionMode::WhitelistedNames,
|
||||
false,
|
||||
),
|
||||
)
|
||||
.execute(RemoveExecutor),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,582 @@
|
||||
use pumpkin_util::{math::vector2::Vector2, text::TextComponent};
|
||||
|
||||
use crate::command::{
|
||||
CommandError, CommandExecutor, CommandResult, CommandSender,
|
||||
args::{
|
||||
ConsumedArgs, DefaultNameArgConsumer, FindArgDefaultName,
|
||||
bounded_num::BoundedNumArgumentConsumer, position_2d::Position2DArgumentConsumer,
|
||||
},
|
||||
tree::{
|
||||
CommandTree,
|
||||
builder::{argument_default_name, literal},
|
||||
},
|
||||
};
|
||||
|
||||
const NAMES: [&str; 1] = ["worldborder"];
|
||||
|
||||
const DESCRIPTION: &str = "Worldborder command.";
|
||||
|
||||
const NOTHING_CHANGED_EXCEPTION: &str = "commands.worldborder.set.failed.nochange";
|
||||
|
||||
const fn distance_consumer() -> BoundedNumArgumentConsumer<f64> {
|
||||
BoundedNumArgumentConsumer::new().min(0.0).name("distance")
|
||||
}
|
||||
|
||||
const fn time_consumer() -> BoundedNumArgumentConsumer<i32> {
|
||||
BoundedNumArgumentConsumer::new().min(0).name("time")
|
||||
}
|
||||
|
||||
const fn damage_per_block_consumer() -> BoundedNumArgumentConsumer<f32> {
|
||||
BoundedNumArgumentConsumer::new()
|
||||
.min(0.0)
|
||||
.name("damage_per_block")
|
||||
}
|
||||
|
||||
const fn damage_buffer_consumer() -> BoundedNumArgumentConsumer<f32> {
|
||||
BoundedNumArgumentConsumer::new().min(0.0).name("buffer")
|
||||
}
|
||||
|
||||
const fn warning_distance_consumer() -> BoundedNumArgumentConsumer<i32> {
|
||||
BoundedNumArgumentConsumer::new().min(0).name("distance")
|
||||
}
|
||||
|
||||
struct GetExecutor;
|
||||
|
||||
impl CommandExecutor for GetExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
_args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
// TODO: Maybe ask player for world, or get the current world
|
||||
let worlds = server.worlds.load();
|
||||
let world = worlds
|
||||
.first()
|
||||
.expect("There should always be at least one world");
|
||||
let border = world.worldborder.lock().await;
|
||||
|
||||
let diameter = border.new_diameter.round() as i32;
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.worldborder.get",
|
||||
"commands.worldborder.get",
|
||||
[TextComponent::text(diameter.to_string())],
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(diameter)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct SetExecutor;
|
||||
|
||||
impl CommandExecutor for SetExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
// TODO: Maybe ask player for world, or get the current world
|
||||
let worlds = server.worlds.load();
|
||||
let world = worlds
|
||||
.first()
|
||||
.expect("There should always be at least one world");
|
||||
let mut border = world.worldborder.lock().await;
|
||||
|
||||
let Ok(distance) = distance_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(format!(
|
||||
"{} is out of bounds.",
|
||||
distance_consumer().default_name()
|
||||
))));
|
||||
};
|
||||
|
||||
if (distance - border.new_diameter).abs() < f64::EPSILON {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
NOTHING_CHANGED_EXCEPTION,
|
||||
NOTHING_CHANGED_EXCEPTION,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.worldborder.set.immediate",
|
||||
"commands.worldborder.set.immediate",
|
||||
[TextComponent::text(format!("{distance:.1}"))],
|
||||
))
|
||||
.await;
|
||||
|
||||
let d = border.new_diameter;
|
||||
border.set_diameter(world, distance, None);
|
||||
|
||||
Ok((distance - d) as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct SetTimeExecutor;
|
||||
|
||||
impl CommandExecutor for SetTimeExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
// TODO: Maybe ask player for world, or get the current world
|
||||
let worlds = server.worlds.load();
|
||||
let world = worlds
|
||||
.first()
|
||||
.expect("There should always be at least one world");
|
||||
let mut border = world.worldborder.lock().await;
|
||||
|
||||
let Ok(distance) = distance_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(format!(
|
||||
"{} is out of bounds.",
|
||||
distance_consumer().default_name()
|
||||
))));
|
||||
};
|
||||
let Ok(time) = time_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(format!(
|
||||
"{} is out of bounds.",
|
||||
distance_consumer().default_name()
|
||||
))));
|
||||
};
|
||||
|
||||
match distance.total_cmp(&border.new_diameter) {
|
||||
std::cmp::Ordering::Equal => {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
NOTHING_CHANGED_EXCEPTION,
|
||||
NOTHING_CHANGED_EXCEPTION,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
std::cmp::Ordering::Less => {
|
||||
let dist = format!("{distance:.1}");
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.worldborder.set.shrink",
|
||||
"commands.worldborder.set.shrink",
|
||||
[
|
||||
TextComponent::text(dist),
|
||||
TextComponent::text(time.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
std::cmp::Ordering::Greater => {
|
||||
let dist = format!("{distance:.1}");
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.worldborder.set.grow",
|
||||
"commands.worldborder.set.grow",
|
||||
[
|
||||
TextComponent::text(dist),
|
||||
TextComponent::text(time.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
let d = border.new_diameter;
|
||||
border.set_diameter(world, distance, Some(i64::from(time) * 1000));
|
||||
|
||||
Ok((distance - d) as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct AddExecutor;
|
||||
|
||||
impl CommandExecutor for AddExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
// TODO: Maybe ask player for world, or get the current world
|
||||
let worlds = server.worlds.load();
|
||||
let world = worlds
|
||||
.first()
|
||||
.expect("There should always be at least one world");
|
||||
let mut border = world.worldborder.lock().await;
|
||||
|
||||
let Ok(distance_add) = distance_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(format!(
|
||||
"{} is out of bounds.",
|
||||
distance_consumer().default_name()
|
||||
))));
|
||||
};
|
||||
|
||||
if distance_add == 0.0 {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
NOTHING_CHANGED_EXCEPTION,
|
||||
NOTHING_CHANGED_EXCEPTION,
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
let distance = border.new_diameter + distance_add;
|
||||
|
||||
let dist = format!("{distance:.1}");
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.worldborder.set.immediate",
|
||||
"commands.worldborder.set.immediate",
|
||||
[TextComponent::text(dist)],
|
||||
))
|
||||
.await;
|
||||
border.set_diameter(world, distance, None);
|
||||
Ok(distance_add as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct AddTimeExecutor;
|
||||
|
||||
impl CommandExecutor for AddTimeExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
// TODO: Maybe ask player for world, or get the current world
|
||||
let worlds = server.worlds.load();
|
||||
let world = worlds
|
||||
.first()
|
||||
.expect("There should always be at least one world");
|
||||
let mut border = world.worldborder.lock().await;
|
||||
|
||||
let Ok(distance_add) = distance_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(format!(
|
||||
"{} is out of bounds.",
|
||||
distance_consumer().default_name()
|
||||
))));
|
||||
};
|
||||
let Ok(time) = time_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(format!(
|
||||
"{} is out of bounds.",
|
||||
distance_consumer().default_name()
|
||||
))));
|
||||
};
|
||||
|
||||
let distance = distance_add + border.new_diameter;
|
||||
|
||||
match distance.total_cmp(&border.new_diameter) {
|
||||
std::cmp::Ordering::Equal => {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(format!(
|
||||
"{} is out of bounds.",
|
||||
distance_consumer().default_name()
|
||||
))));
|
||||
}
|
||||
std::cmp::Ordering::Less => {
|
||||
let dist = format!("{distance:.1}");
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.worldborder.set.shrink",
|
||||
"commands.worldborder.set.shrink",
|
||||
[
|
||||
TextComponent::text(dist),
|
||||
TextComponent::text(time.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
std::cmp::Ordering::Greater => {
|
||||
let dist = format!("{distance:.1}");
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.worldborder.set.grow",
|
||||
"commands.worldborder.set.grow",
|
||||
[
|
||||
TextComponent::text(dist),
|
||||
TextComponent::text(time.to_string()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
border.set_diameter(world, distance, Some(i64::from(time) * 1000));
|
||||
|
||||
Ok(distance_add as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct CenterExecutor;
|
||||
|
||||
impl CommandExecutor for CenterExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
// TODO: Maybe ask player for world, or get the current world
|
||||
let worlds = server.worlds.load();
|
||||
let world = worlds
|
||||
.first()
|
||||
.expect("There should always be at least one world");
|
||||
let mut border = world.worldborder.lock().await;
|
||||
|
||||
let Vector2 { x, y } = Position2DArgumentConsumer.find_arg_default_name(args)?;
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.worldborder.center.success",
|
||||
"commands.worldborder.center.success",
|
||||
[
|
||||
TextComponent::text(format!("{x:.2}")),
|
||||
TextComponent::text(format!("{y:.2}")),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
border.set_center(world, x, y);
|
||||
Ok(0)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct DamageAmountExecutor;
|
||||
|
||||
impl CommandExecutor for DamageAmountExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
// TODO: Maybe ask player for world, or get the current world
|
||||
let worlds = server.worlds.load();
|
||||
let world = worlds
|
||||
.first()
|
||||
.expect("There should always be at least one world");
|
||||
let mut border = world.worldborder.lock().await;
|
||||
|
||||
let Ok(damage_per_block) = damage_per_block_consumer().find_arg_default_name(args)?
|
||||
else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(format!(
|
||||
"{} is out of bounds.",
|
||||
distance_consumer().default_name()
|
||||
))));
|
||||
};
|
||||
|
||||
if (damage_per_block - border.damage_per_block).abs() < f32::EPSILON {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.worldborder.damage.amount.failed",
|
||||
"commands.worldborder.damage.amount.failed",
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
let damage = format!("{damage_per_block:.2}");
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.worldborder.damage.amount.success",
|
||||
"commands.worldborder.damage.amount.success",
|
||||
[TextComponent::text(damage)],
|
||||
))
|
||||
.await;
|
||||
border.damage_per_block = damage_per_block;
|
||||
Ok(damage_per_block as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct DamageBufferExecutor;
|
||||
|
||||
impl CommandExecutor for DamageBufferExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
// TODO: Maybe ask player for world, or get the current world
|
||||
let worlds = server.worlds.load();
|
||||
let world = worlds
|
||||
.first()
|
||||
.expect("There should always be at least one world");
|
||||
let mut border = world.worldborder.lock().await;
|
||||
|
||||
let Ok(buffer) = damage_buffer_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(format!(
|
||||
"{} is out of bounds.",
|
||||
distance_consumer().default_name()
|
||||
))));
|
||||
};
|
||||
|
||||
if (buffer - border.buffer).abs() < f32::EPSILON {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.worldborder.damage.amount.failed",
|
||||
"commands.worldborder.damage.amount.failed",
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
let buf = format!("{buffer:.2}");
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.worldborder.damage.buffer.success",
|
||||
"commands.worldborder.damage.buffer.success",
|
||||
[TextComponent::text(buf)],
|
||||
))
|
||||
.await;
|
||||
border.buffer = buffer;
|
||||
Ok(buffer as i32)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct WarningDistanceExecutor;
|
||||
|
||||
impl CommandExecutor for WarningDistanceExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
// TODO: Maybe ask player for world, or get the current world
|
||||
let worlds = server.worlds.load();
|
||||
let world = worlds
|
||||
.first()
|
||||
.expect("There should always be at least one world");
|
||||
let mut border = world.worldborder.lock().await;
|
||||
|
||||
let Ok(distance) = warning_distance_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(format!(
|
||||
"{} is out of bounds.",
|
||||
distance_consumer().default_name()
|
||||
))));
|
||||
};
|
||||
|
||||
if distance == border.warning_blocks {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.worldborder.warning.distance.failed",
|
||||
"commands.worldborder.warning.distance.failed",
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.worldborder.warning.distance.success",
|
||||
"commands.worldborder.warning.distance.success",
|
||||
[TextComponent::text(distance.to_string())],
|
||||
))
|
||||
.await;
|
||||
border.set_warning_distance(world, distance);
|
||||
Ok(distance)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct WarningTimeExecutor;
|
||||
|
||||
impl CommandExecutor for WarningTimeExecutor {
|
||||
fn execute<'a>(
|
||||
&'a self,
|
||||
sender: &'a CommandSender,
|
||||
server: &'a crate::server::Server,
|
||||
args: &'a ConsumedArgs<'a>,
|
||||
) -> CommandResult<'a> {
|
||||
Box::pin(async move {
|
||||
// TODO: Maybe ask player for world, or get the current world
|
||||
let worlds = server.worlds.load();
|
||||
let world = worlds
|
||||
.first()
|
||||
.expect("There should always be at least one world");
|
||||
let mut border = world.worldborder.lock().await;
|
||||
|
||||
let Ok(time) = time_consumer().find_arg_default_name(args)? else {
|
||||
return Err(CommandError::CommandFailed(TextComponent::text(format!(
|
||||
"{} is out of bounds.",
|
||||
distance_consumer().default_name()
|
||||
))));
|
||||
};
|
||||
|
||||
if time == border.warning_time {
|
||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||
"commands.worldborder.warning.time.failed",
|
||||
"commands.worldborder.warning.time.failed",
|
||||
[],
|
||||
)));
|
||||
}
|
||||
|
||||
sender
|
||||
.send_message(TextComponent::translate_cross(
|
||||
"commands.worldborder.warning.time.success",
|
||||
"commands.worldborder.warning.time.success",
|
||||
[TextComponent::text(time.to_string())],
|
||||
))
|
||||
.await;
|
||||
border.set_warning_delay(world, time);
|
||||
Ok(time)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_command_tree() -> CommandTree {
|
||||
CommandTree::new(NAMES, DESCRIPTION)
|
||||
.then(
|
||||
literal("add").then(
|
||||
argument_default_name(distance_consumer())
|
||||
.execute(AddExecutor)
|
||||
.then(argument_default_name(time_consumer()).execute(AddTimeExecutor)),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("center")
|
||||
.then(argument_default_name(Position2DArgumentConsumer).execute(CenterExecutor)),
|
||||
)
|
||||
.then(
|
||||
literal("damage")
|
||||
.then(
|
||||
literal("amount").then(
|
||||
argument_default_name(damage_per_block_consumer())
|
||||
.execute(DamageAmountExecutor),
|
||||
),
|
||||
)
|
||||
.then(literal("buffer").then(
|
||||
argument_default_name(damage_buffer_consumer()).execute(DamageBufferExecutor),
|
||||
)),
|
||||
)
|
||||
.then(literal("get").execute(GetExecutor))
|
||||
.then(
|
||||
literal("set").then(
|
||||
argument_default_name(distance_consumer())
|
||||
.execute(SetExecutor)
|
||||
.then(argument_default_name(time_consumer()).execute(SetTimeExecutor)),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("warning")
|
||||
.then(
|
||||
literal("distance").then(
|
||||
argument_default_name(warning_distance_consumer())
|
||||
.execute(WarningDistanceExecutor),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
literal("time")
|
||||
.then(argument_default_name(time_consumer()).execute(WarningTimeExecutor)),
|
||||
),
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user