refactor(commands): from async to sync Part 3
This commit is contained in:
1 parent
5d841d6d3b
commit
66a5f53408
222 files changed
+11699
-12920
No files matched your search
@@ -211,7 +211,7 @@ mod tests {
|
|||||||
let ec = EnderChestInventory::new();
|
let ec = EnderChestInventory::new();
|
||||||
assert_eq!(ec.size(), 27);
|
assert_eq!(ec.size(), 27);
|
||||||
assert!(ec.is_empty().await);
|
assert!(ec.is_empty().await);
|
||||||
assert!(!ec.has_tracker().await);
|
assert!(!ec.has_tracker());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
@@ -323,13 +323,9 @@ impl AnvilChunkData {
|
|||||||
|
|
||||||
let compression = compression.unwrap_or_else(|| chunk_config.compression.algorithm.into());
|
let compression = compression.unwrap_or_else(|| chunk_config.compression.algorithm.into());
|
||||||
let level = chunk_config.compression.level;
|
let level = chunk_config.compression.level;
|
||||||
|
let compressed_data = compression
|
||||||
// Offload CPU-heavy compression to blocking thread pool
|
.compress_data(&raw_bytes, level)
|
||||||
let compressed_data =
|
.map_err(ChunkWritingError::Compression)?;
|
||||||
tokio::task::spawn_blocking(move || compression.compress_data(&raw_bytes, level))
|
|
||||||
.await
|
|
||||||
.map_err(|err| ChunkWritingError::IoError(std::io::Error::other(err)))?
|
|
||||||
.map_err(ChunkWritingError::Compression)?;
|
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
compression: Some(compression),
|
compression: Some(compression),
|
||||||
@@ -793,17 +789,10 @@ impl<S: SingleChunkDataSerializer + 'static> ChunkSerializer for AnvilChunkFile<
|
|||||||
let is_ok = match &self.chunks_data[index] {
|
let is_ok = match &self.chunks_data[index] {
|
||||||
None => stream.send(LoadedData::Missing(chunk)).await.is_ok(),
|
None => stream.send(LoadedData::Missing(chunk)).await.is_ok(),
|
||||||
Some(chunk_metadata) => {
|
Some(chunk_metadata) => {
|
||||||
let chunk_data = chunk_metadata.serialized_data.clone();
|
let result = match chunk_metadata.serialized_data.to_chunk(chunk) {
|
||||||
let result =
|
Ok(chunk_res) => LoadedData::Loaded(chunk_res),
|
||||||
match tokio::task::spawn_blocking(move || chunk_data.to_chunk(chunk)).await
|
Err(err) => LoadedData::Error((chunk, err)),
|
||||||
{
|
};
|
||||||
Ok(Ok(chunk_res)) => LoadedData::Loaded(chunk_res),
|
|
||||||
Ok(Err(err)) => LoadedData::Error((chunk, err)),
|
|
||||||
Err(err) => LoadedData::Error((
|
|
||||||
chunk,
|
|
||||||
ChunkReadingError::IoError(std::io::Error::other(err)),
|
|
||||||
)),
|
|
||||||
};
|
|
||||||
|
|
||||||
stream.send(result).await.is_ok()
|
stream.send(result).await.is_ok()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -407,26 +407,21 @@ impl<S: SingleChunkDataSerializer + 'static> ChunkSerializer for LinearV2File<S>
|
|||||||
let chunks_data = self.chunks_data.clone();
|
let chunks_data = self.chunks_data.clone();
|
||||||
let timestamps = self.timestamps;
|
let timestamps = self.timestamps;
|
||||||
|
|
||||||
let (bucket_entries, compressed_buckets) = tokio::task::spawn_blocking(move || {
|
let mut compressed_buckets: Vec<Box<[u8]>> = Vec::with_capacity(bucket_count);
|
||||||
let mut compressed_buckets: Vec<Box<[u8]>> = Vec::with_capacity(bucket_count);
|
let mut bucket_entries: Vec<BucketSizeEntry> = Vec::with_capacity(bucket_count);
|
||||||
let mut bucket_entries: Vec<BucketSizeEntry> = Vec::with_capacity(bucket_count);
|
|
||||||
|
|
||||||
for bucket_idx in 0..bucket_count {
|
for bucket_idx in 0..bucket_count {
|
||||||
let raw = Self::serialise_bucket(&chunks_data, ×tamps, bucket_idx, grid_size);
|
let raw = Self::serialise_bucket(&chunks_data, ×tamps, bucket_idx, grid_size);
|
||||||
let compressed =
|
let compressed =
|
||||||
compress_to_vec(raw.as_slice(), CompressionLevel::Fastest).into_boxed_slice();
|
compress_to_vec(raw.as_slice(), CompressionLevel::Fastest).into_boxed_slice();
|
||||||
let hash = xxh64(&compressed, 0);
|
let hash = xxh64(&compressed, 0);
|
||||||
bucket_entries.push(BucketSizeEntry {
|
bucket_entries.push(BucketSizeEntry {
|
||||||
size: compressed.len() as u32,
|
size: compressed.len() as u32,
|
||||||
compression_level: 1,
|
compression_level: 1,
|
||||||
xxhash: hash,
|
xxhash: hash,
|
||||||
});
|
});
|
||||||
compressed_buckets.push(compressed);
|
compressed_buckets.push(compressed);
|
||||||
}
|
}
|
||||||
(bucket_entries, compressed_buckets)
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.map_err(std::io::Error::other)?;
|
|
||||||
|
|
||||||
let newest_timestamp = self.timestamps.iter().copied().max().unwrap_or(0);
|
let newest_timestamp = self.timestamps.iter().copied().max().unwrap_or(0);
|
||||||
|
|
||||||
@@ -598,18 +593,9 @@ impl<S: SingleChunkDataSerializer + 'static> ChunkSerializer for LinearV2File<S>
|
|||||||
let is_ok = match &self.chunks_data[index] {
|
let is_ok = match &self.chunks_data[index] {
|
||||||
None => stream.send(LoadedData::Missing(chunk)).await.is_ok(),
|
None => stream.send(LoadedData::Missing(chunk)).await.is_ok(),
|
||||||
Some(data) => {
|
Some(data) => {
|
||||||
let data = data.clone();
|
let result = match S::from_bytes(data, chunk) {
|
||||||
let result = match tokio::task::spawn_blocking(move || {
|
Ok(c) => LoadedData::Loaded(c),
|
||||||
S::from_bytes(&data, chunk)
|
Err(err) => LoadedData::Error((chunk, err)),
|
||||||
})
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(Ok(c)) => LoadedData::Loaded(c),
|
|
||||||
Ok(Err(err)) => LoadedData::Error((chunk, err)),
|
|
||||||
Err(err) => LoadedData::Error((
|
|
||||||
chunk,
|
|
||||||
ChunkReadingError::IoError(std::io::Error::other(err)),
|
|
||||||
)),
|
|
||||||
};
|
};
|
||||||
stream.send(result).await.is_ok()
|
stream.send(result).await.is_ok()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -129,8 +129,7 @@ where
|
|||||||
let index = (rel_x + rel_z * 32) as usize;
|
let index = (rel_x + rel_z * 32) as usize;
|
||||||
|
|
||||||
if let Some(chunk_bytes) = self.data.chunks.get(&index.to_string()) {
|
if let Some(chunk_bytes) = self.data.chunks.get(&index.to_string()) {
|
||||||
let chunk_bytes = chunk_bytes.clone();
|
let res = (|| {
|
||||||
let res = tokio::task::spawn_blocking(move || {
|
|
||||||
let mut decoder = StreamingDecoder::new(&chunk_bytes[..]).map_err(|e| {
|
let mut decoder = StreamingDecoder::new(&chunk_bytes[..]).map_err(|e| {
|
||||||
ChunkReadingError::IoError(std::io::Error::other(e.to_string()))
|
ChunkReadingError::IoError(std::io::Error::other(e.to_string()))
|
||||||
})?;
|
})?;
|
||||||
@@ -139,16 +138,11 @@ where
|
|||||||
.map_err(ChunkReadingError::IoError)?;
|
.map_err(ChunkReadingError::IoError)?;
|
||||||
let bytes = Bytes::from(decompressed);
|
let bytes = Bytes::from(decompressed);
|
||||||
D::from_bytes(&bytes, pos)
|
D::from_bytes(&bytes, pos)
|
||||||
})
|
})();
|
||||||
.await;
|
|
||||||
|
|
||||||
let data_res = match res {
|
let data_res = match res {
|
||||||
Ok(Ok(data)) => LoadedData::Loaded(data),
|
Ok(data) => LoadedData::Loaded(data),
|
||||||
Ok(Err(e)) => LoadedData::Error((pos, e)),
|
Err(e) => LoadedData::Error((pos, e)),
|
||||||
Err(e) => LoadedData::Error((
|
|
||||||
pos,
|
|
||||||
ChunkReadingError::IoError(std::io::Error::other(e)),
|
|
||||||
)),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if stream.send(data_res).await.is_err() {
|
if stream.send(data_res).await.is_err() {
|
||||||
|
|||||||
@@ -108,9 +108,7 @@ impl<S: ChunkSerializer<WriteBackend = PathBuf> + 'static> ChunkSerializerLazyLo
|
|||||||
);
|
);
|
||||||
return Ok(S::default());
|
return Ok(S::default());
|
||||||
}
|
}
|
||||||
let value = tokio::task::spawn_blocking(move || S::read(bytes.into()))
|
let value = S::read(bytes.into())?;
|
||||||
.await
|
|
||||||
.map_err(|e| ChunkReadingError::IoError(std::io::Error::other(e)))??;
|
|
||||||
trace!("Successfully read file from disk: {}", self.path.display());
|
trace!("Successfully read file from disk: {}", self.path.display());
|
||||||
Ok(value)
|
Ok(value)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,6 +56,55 @@ fn needs_relighting(chunk: &crate::chunk::ChunkData, config: LightingEngineConfi
|
|||||||
!has_complex_light
|
!has_complex_light
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn load_proto_chunk(chunk: &Arc<crate::chunk::ChunkData>, level: &Level) -> ProtoChunk {
|
||||||
|
if let Some(pool) = &level.gen_pool {
|
||||||
|
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||||
|
let world_gen = level.world_gen.load();
|
||||||
|
let chunk_clone = chunk.clone();
|
||||||
|
pool.spawn(move || {
|
||||||
|
let p = ProtoChunk::from_chunk_data(&chunk_clone, &world_gen);
|
||||||
|
let _ = tx.send(p);
|
||||||
|
});
|
||||||
|
rx.await
|
||||||
|
.unwrap_or_else(|_| ProtoChunk::from_chunk_data(chunk, &level.world_gen.load()))
|
||||||
|
} else {
|
||||||
|
ProtoChunk::from_chunk_data(chunk, &level.world_gen.load())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn process_loaded_chunk(chunk: Arc<crate::chunk::ChunkData>, level: &Level) -> Chunk {
|
||||||
|
let pos = ChunkPos::new(chunk.x, chunk.z);
|
||||||
|
if chunk.status == ChunkStatus::Full {
|
||||||
|
let needs_relight = needs_relighting(&chunk, level.lighting_config);
|
||||||
|
if needs_relight {
|
||||||
|
debug!(
|
||||||
|
"Chunk {pos:?} has uniform lighting, downgrading to Features stage for relighting"
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut proto = load_proto_chunk(&chunk, level).await;
|
||||||
|
|
||||||
|
// Clear all lighting data
|
||||||
|
let section_count = proto.light.sky_light.len();
|
||||||
|
proto.light.sky_light = (0..section_count)
|
||||||
|
.map(|_| LightContainer::new_empty(15))
|
||||||
|
.collect();
|
||||||
|
proto.light.block_light = (0..section_count)
|
||||||
|
.map(|_| LightContainer::new_empty(0))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// Set stage to Features
|
||||||
|
proto.stage = StagedChunkEnum::Features;
|
||||||
|
|
||||||
|
Chunk::Proto(Box::new(proto))
|
||||||
|
} else {
|
||||||
|
Chunk::Level(chunk)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let proto = load_proto_chunk(&chunk, level).await;
|
||||||
|
Chunk::Proto(Box::new(proto))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn io_read_work(
|
pub async fn io_read_work(
|
||||||
recv: crossfire::compat::MAsyncRx<Vec<ChunkPos>>,
|
recv: crossfire::compat::MAsyncRx<Vec<ChunkPos>>,
|
||||||
send: crossfire::compat::MTx<(ChunkPos, RecvChunk)>,
|
send: crossfire::compat::MTx<(ChunkPos, RecvChunk)>,
|
||||||
@@ -102,54 +151,9 @@ pub async fn io_read_work(
|
|||||||
match data {
|
match data {
|
||||||
Loaded(chunk) => {
|
Loaded(chunk) => {
|
||||||
let pos = ChunkPos::new(chunk.x, chunk.z);
|
let pos = ChunkPos::new(chunk.x, chunk.z);
|
||||||
if chunk.status == ChunkStatus::Full {
|
let processed = process_loaded_chunk(chunk, &level).await;
|
||||||
// Relighting check
|
if send.send((pos, RecvChunk::IO(processed))).is_err() {
|
||||||
let needs_relight = needs_relighting(&chunk, level.lighting_config);
|
break;
|
||||||
|
|
||||||
if needs_relight {
|
|
||||||
debug!(
|
|
||||||
"Chunk {pos:?} has uniform lighting, downgrading to Features stage for relighting"
|
|
||||||
);
|
|
||||||
|
|
||||||
// Create ProtoChunk using the async method
|
|
||||||
let mut proto =
|
|
||||||
ProtoChunk::from_chunk_data(&chunk, &level.world_gen.load());
|
|
||||||
|
|
||||||
// Clear all lighting data
|
|
||||||
let section_count = proto.light.sky_light.len();
|
|
||||||
proto.light.sky_light = (0..section_count)
|
|
||||||
.map(|_| LightContainer::new_empty(15))
|
|
||||||
.collect();
|
|
||||||
proto.light.block_light = (0..section_count)
|
|
||||||
.map(|_| LightContainer::new_empty(0))
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
// Set stage to Features
|
|
||||||
proto.stage = StagedChunkEnum::Features;
|
|
||||||
|
|
||||||
if send
|
|
||||||
.send((pos, RecvChunk::IO(Chunk::Proto(Box::new(proto)))))
|
|
||||||
.is_err()
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Send fully valid chunk
|
|
||||||
if send
|
|
||||||
.send((pos, RecvChunk::IO(Chunk::Level(chunk))))
|
|
||||||
.is_err()
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Standard ProtoChunk handling for non-full chunks
|
|
||||||
let val = RecvChunk::IO(Chunk::Proto(Box::new(
|
|
||||||
ProtoChunk::from_chunk_data(&chunk, &level.world_gen.load()),
|
|
||||||
)));
|
|
||||||
if send.send((pos, val)).is_err() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
LoadedData::Missing(pos) | LoadedData::Error((pos, _)) => {
|
LoadedData::Missing(pos) | LoadedData::Error((pos, _)) => {
|
||||||
|
|||||||
@@ -246,15 +246,13 @@ impl BedBlock {
|
|||||||
if world.get_block_state(&bed_head_pos.up()).is_solid()
|
if world.get_block_state(&bed_head_pos.up()).is_solid()
|
||||||
|| world.get_block_state(&bed_foot_pos.up()).is_solid()
|
|| world.get_block_state(&bed_foot_pos.up()).is_solid()
|
||||||
{
|
{
|
||||||
player
|
player.send_system_message_raw(
|
||||||
.send_system_message_raw(
|
&pumpkin_macros::translate_cross!(
|
||||||
&pumpkin_macros::translate_cross!(
|
translation::java::BLOCK_MINECRAFT_BED_OBSTRUCTED,
|
||||||
translation::java::BLOCK_MINECRAFT_BED_OBSTRUCTED,
|
translation::bedrock::TILE_BED_OBSTRUCTED
|
||||||
translation::bedrock::TILE_BED_OBSTRUCTED
|
),
|
||||||
),
|
true,
|
||||||
true,
|
);
|
||||||
)
|
|
||||||
.await;
|
|
||||||
return BlockActionResult::SuccessServer;
|
return BlockActionResult::SuccessServer;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -262,15 +260,13 @@ impl BedBlock {
|
|||||||
if bed_props.occupied {
|
if bed_props.occupied {
|
||||||
// TODO: Wake up villager
|
// TODO: Wake up villager
|
||||||
|
|
||||||
player
|
player.send_system_message_raw(
|
||||||
.send_system_message_raw(
|
&pumpkin_macros::translate_cross!(
|
||||||
&pumpkin_macros::translate_cross!(
|
translation::java::BLOCK_MINECRAFT_BED_OCCUPIED,
|
||||||
translation::java::BLOCK_MINECRAFT_BED_OCCUPIED,
|
translation::bedrock::TILE_BED_OCCUPIED
|
||||||
translation::bedrock::TILE_BED_OCCUPIED
|
),
|
||||||
),
|
true,
|
||||||
true,
|
);
|
||||||
)
|
|
||||||
.await;
|
|
||||||
return BlockActionResult::SuccessServer;
|
return BlockActionResult::SuccessServer;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -282,48 +278,39 @@ impl BedBlock {
|
|||||||
.position()
|
.position()
|
||||||
.is_within_bounds(bed_foot_pos.to_f64(), 3.0, 3.0, 3.0)
|
.is_within_bounds(bed_foot_pos.to_f64(), 3.0, 3.0, 3.0)
|
||||||
{
|
{
|
||||||
player
|
player.send_system_message_raw(
|
||||||
.send_system_message_raw(
|
&pumpkin_macros::translate_cross!(
|
||||||
&pumpkin_macros::translate_cross!(
|
translation::java::BLOCK_MINECRAFT_BED_TOO_FAR_AWAY,
|
||||||
translation::java::BLOCK_MINECRAFT_BED_TOO_FAR_AWAY,
|
translation::bedrock::TILE_BED_TOOFAR
|
||||||
translation::bedrock::TILE_BED_TOOFAR
|
),
|
||||||
),
|
true,
|
||||||
true,
|
);
|
||||||
)
|
|
||||||
.await;
|
|
||||||
return BlockActionResult::SuccessServer;
|
return BlockActionResult::SuccessServer;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set respawn point
|
// Set respawn point
|
||||||
if player
|
if player.set_respawn_point(
|
||||||
.set_respawn_point(
|
world.dimension.clone(),
|
||||||
world.dimension.clone(),
|
bed_head_pos,
|
||||||
bed_head_pos,
|
player.get_entity().yaw.load(),
|
||||||
player.get_entity().yaw.load(),
|
player.get_entity().pitch.load(),
|
||||||
player.get_entity().pitch.load(),
|
false,
|
||||||
false,
|
) {
|
||||||
)
|
player.send_system_message(&pumpkin_macros::translate_cross!(
|
||||||
.await
|
translation::java::BLOCK_MINECRAFT_SET_SPAWN,
|
||||||
{
|
translation::bedrock::TILE_BED_RESPAWNSET
|
||||||
player
|
));
|
||||||
.send_system_message(&pumpkin_macros::translate_cross!(
|
|
||||||
translation::java::BLOCK_MINECRAFT_SET_SPAWN,
|
|
||||||
translation::bedrock::TILE_BED_RESPAWNSET
|
|
||||||
))
|
|
||||||
.await;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Make sure the time and weather allows sleep
|
// Make sure the time and weather allows sleep
|
||||||
if !can_sleep(world) {
|
if !can_sleep(world) {
|
||||||
player
|
player.send_system_message_raw(
|
||||||
.send_system_message_raw(
|
&pumpkin_macros::translate_cross!(
|
||||||
&pumpkin_macros::translate_cross!(
|
translation::java::BLOCK_MINECRAFT_BED_NO_SLEEP,
|
||||||
translation::java::BLOCK_MINECRAFT_BED_NO_SLEEP,
|
translation::bedrock::TILE_BED_NOSLEEP
|
||||||
translation::bedrock::TILE_BED_NOSLEEP
|
),
|
||||||
),
|
true,
|
||||||
true,
|
);
|
||||||
)
|
|
||||||
.await;
|
|
||||||
return BlockActionResult::SuccessServer;
|
return BlockActionResult::SuccessServer;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -337,15 +324,13 @@ impl BedBlock {
|
|||||||
if pos.is_within_bounds(bed_head_pos.to_f64(), 8.0, 5.0, 8.0)
|
if pos.is_within_bounds(bed_head_pos.to_f64(), 8.0, 5.0, 8.0)
|
||||||
|| pos.is_within_bounds(bed_foot_pos.to_f64(), 8.0, 5.0, 8.0)
|
|| pos.is_within_bounds(bed_foot_pos.to_f64(), 8.0, 5.0, 8.0)
|
||||||
{
|
{
|
||||||
player
|
player.send_system_message_raw(
|
||||||
.send_system_message_raw(
|
&pumpkin_macros::translate_cross!(
|
||||||
&pumpkin_macros::translate_cross!(
|
translation::java::BLOCK_MINECRAFT_BED_NOT_SAFE,
|
||||||
translation::java::BLOCK_MINECRAFT_BED_NOT_SAFE,
|
translation::bedrock::TILE_BED_NOTSAFE
|
||||||
translation::bedrock::TILE_BED_NOTSAFE
|
),
|
||||||
),
|
true,
|
||||||
true,
|
);
|
||||||
)
|
|
||||||
.await;
|
|
||||||
return BlockActionResult::SuccessServer;
|
return BlockActionResult::SuccessServer;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ impl CommandBlock {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn execute(
|
fn execute(
|
||||||
server: &Arc<Server>,
|
server: &Arc<Server>,
|
||||||
world: Arc<World>,
|
world: Arc<World>,
|
||||||
block_entity: Arc<dyn BlockEntity>,
|
block_entity: Arc<dyn BlockEntity>,
|
||||||
@@ -133,24 +133,16 @@ impl CommandBlock {
|
|||||||
if command.is_empty() {
|
if command.is_empty() {
|
||||||
command_entity.success_count.store(0, Ordering::Release);
|
command_entity.success_count.store(0, Ordering::Release);
|
||||||
} else {
|
} else {
|
||||||
let source = CommandSender::CommandBlock(command_entity, world.clone())
|
let source = CommandSender::CommandBlock(command_entity, world).into_source(server);
|
||||||
.into_source(server)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
server
|
server
|
||||||
.command_dispatcher
|
.command_dispatcher
|
||||||
.load()
|
.load()
|
||||||
.handle_command(&source, command)
|
.handle_command(&source, command);
|
||||||
.await;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn chain_execute(
|
fn chain_execute(server: &Arc<Server>, world: &Arc<World>, start: BlockPos, direction: Facing) {
|
||||||
server: &Arc<Server>,
|
|
||||||
world: Arc<World>,
|
|
||||||
start: BlockPos,
|
|
||||||
direction: Facing,
|
|
||||||
) {
|
|
||||||
let mut i = u16::MAX;
|
let mut i = u16::MAX;
|
||||||
let mut pos = start;
|
let mut pos = start;
|
||||||
|
|
||||||
@@ -179,7 +171,7 @@ impl CommandBlock {
|
|||||||
let props = CommandBlockLikeProperties::from_state_id(state_id, block);
|
let props = CommandBlockLikeProperties::from_state_id(state_id, block);
|
||||||
|
|
||||||
if powered || auto {
|
if powered || auto {
|
||||||
let conditions_met = Self::conditions_met(&world, &pos, direction);
|
let conditions_met = Self::conditions_met(world, &pos, direction);
|
||||||
if conditions_met {
|
if conditions_met {
|
||||||
let command = command_entity
|
let command = command_entity
|
||||||
.command
|
.command
|
||||||
@@ -190,7 +182,7 @@ impl CommandBlock {
|
|||||||
warn!("Command block entity disappeared during execution");
|
warn!("Command block entity disappeared during execution");
|
||||||
break;
|
break;
|
||||||
};
|
};
|
||||||
Self::execute(server, world.clone(), entity, &command).await;
|
Self::execute(server, world.clone(), entity, &command);
|
||||||
} else if props.conditional {
|
} else if props.conditional {
|
||||||
command_entity.success_count.store(0, Ordering::Release);
|
command_entity.success_count.store(0, Ordering::Release);
|
||||||
}
|
}
|
||||||
@@ -298,25 +290,20 @@ impl BlockBehaviour for CommandBlock {
|
|||||||
let entity_clone = block_entity.clone();
|
let entity_clone = block_entity.clone();
|
||||||
let position = *args.position;
|
let position = *args.position;
|
||||||
let facing = props.facing;
|
let facing = props.facing;
|
||||||
tokio::spawn(async move {
|
if let Some(command_entity) = entity_clone.as_any().downcast_ref::<CommandBlockEntity>() {
|
||||||
let Some(command_entity) = entity_clone.as_any().downcast_ref::<CommandBlockEntity>()
|
|
||||||
else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let command = command_entity
|
let command = command_entity
|
||||||
.command
|
.command
|
||||||
.lock()
|
.lock()
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
.clone();
|
.clone();
|
||||||
Self::execute(&server, world.clone(), entity_clone, &command).await;
|
Self::execute(&server, world.clone(), entity_clone, &command);
|
||||||
Self::chain_execute(
|
Self::chain_execute(
|
||||||
&server,
|
&server,
|
||||||
world,
|
&world,
|
||||||
position.offset(facing.to_block_direction().to_offset()),
|
position.offset(facing.to_block_direction().to_offset()),
|
||||||
facing,
|
facing,
|
||||||
)
|
);
|
||||||
.await;
|
}
|
||||||
});
|
|
||||||
|
|
||||||
let block = args.world.get_block(args.position);
|
let block = args.world.get_block(args.position);
|
||||||
let is_auto = command_entity.auto.load(Ordering::Relaxed);
|
let is_auto = command_entity.auto.load(Ordering::Relaxed);
|
||||||
|
|||||||
@@ -294,13 +294,13 @@ impl DispenserBlock {
|
|||||||
Self::dispense_empty_bucket(ctx, dispenser, item).await;
|
Self::dispense_empty_bucket(ctx, dispenser, item).await;
|
||||||
} else if FilledBucketItem::ids().contains(&item.item.id) {
|
} else if FilledBucketItem::ids().contains(&item.item.id) {
|
||||||
// Filled buckets place their fluid in front of the dispenser
|
// Filled buckets place their fluid in front of the dispenser
|
||||||
Self::dispense_filled_bucket(ctx, item).await;
|
Self::dispense_filled_bucket(ctx, item);
|
||||||
} else if item.item.id == Item::FLINT_AND_STEEL.id {
|
} else if item.item.id == Item::FLINT_AND_STEEL.id {
|
||||||
// Flint and steel light fires and prime TNT
|
// Flint and steel light fires and prime TNT
|
||||||
Self::dispense_flint_and_steel(ctx, item).await;
|
Self::dispense_flint_and_steel(ctx, item);
|
||||||
} else if item.item.id == Item::HONEYCOMB.id {
|
} else if item.item.id == Item::HONEYCOMB.id {
|
||||||
// Honeycombs wax copper blocks
|
// Honeycombs wax copper blocks
|
||||||
Self::dispense_honeycomb(ctx, item).await;
|
Self::dispense_honeycomb(ctx, item);
|
||||||
} else if entity_from_egg(item.item.id).is_some() {
|
} else if entity_from_egg(item.item.id).is_some() {
|
||||||
// Spawn eggs
|
// Spawn eggs
|
||||||
Self::dispense_spawn_egg(ctx, item);
|
Self::dispense_spawn_egg(ctx, item);
|
||||||
@@ -703,7 +703,7 @@ impl DispenserBlock {
|
|||||||
Some(stack)
|
Some(stack)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn dispense_filled_bucket(ctx: &DispenseContext<'_>, item: &mut ItemStack) {
|
fn dispense_filled_bucket(ctx: &DispenseContext<'_>, item: &mut ItemStack) {
|
||||||
let front = Self::target_position(ctx);
|
let front = Self::target_position(ctx);
|
||||||
|
|
||||||
// TODO: Spawn the stored entity for axolotl/fish/tadpole buckets, like the player path.
|
// TODO: Spawn the stored entity for axolotl/fish/tadpole buckets, like the player path.
|
||||||
@@ -727,7 +727,7 @@ impl DispenserBlock {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn dispense_flint_and_steel(ctx: &DispenseContext<'_>, item: &mut ItemStack) {
|
fn dispense_flint_and_steel(ctx: &DispenseContext<'_>, item: &mut ItemStack) {
|
||||||
let front = Self::target_position(ctx);
|
let front = Self::target_position(ctx);
|
||||||
let front_block = ctx.world.get_block(&front);
|
let front_block = ctx.world.get_block(&front);
|
||||||
|
|
||||||
@@ -755,7 +755,7 @@ impl DispenserBlock {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn dispense_honeycomb(ctx: &DispenseContext<'_>, item: &mut ItemStack) {
|
fn dispense_honeycomb(ctx: &DispenseContext<'_>, item: &mut ItemStack) {
|
||||||
let front = Self::target_position(ctx);
|
let front = Self::target_position(ctx);
|
||||||
let front_block = ctx.world.get_block(&front);
|
let front_block = ctx.world.get_block(&front);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use pumpkin_data::block_properties::{BlockProperties, RespawnAnchorLikeProperties};
|
use pumpkin_data::block_properties::{BlockProperties, RespawnAnchorLikeProperties};
|
||||||
use pumpkin_data::dimension::Dimension;
|
use pumpkin_data::dimension::Dimension;
|
||||||
use pumpkin_data::item::Item;
|
use pumpkin_data::item::Item;
|
||||||
@@ -61,46 +59,35 @@ impl BlockBehaviour for RespawnAnchorBlock {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if props.charges == 0 {
|
if props.charges == 0 {
|
||||||
let player = Arc::clone(args.player);
|
args.player
|
||||||
tokio::spawn(async move {
|
.send_system_message(&pumpkin_macros::translate_cross!(
|
||||||
player
|
translation::java::BLOCK_MINECRAFT_BED_NO_SLEEP,
|
||||||
.send_system_message(&pumpkin_macros::translate_cross!(
|
translation::bedrock::TILE_BED_NOSLEEP
|
||||||
translation::java::BLOCK_MINECRAFT_BED_NO_SLEEP,
|
));
|
||||||
translation::bedrock::TILE_BED_NOSLEEP
|
|
||||||
))
|
|
||||||
.await;
|
|
||||||
});
|
|
||||||
return BlockActionResult::SuccessServer;
|
return BlockActionResult::SuccessServer;
|
||||||
}
|
}
|
||||||
|
|
||||||
let player = Arc::clone(args.player);
|
let player = args.player;
|
||||||
let world = Arc::clone(args.world);
|
let world = args.world;
|
||||||
let pos = *args.position;
|
let pos = *args.position;
|
||||||
tokio::spawn(async move {
|
if player.set_respawn_point(
|
||||||
if player
|
world.dimension.clone(),
|
||||||
.set_respawn_point(
|
pos,
|
||||||
world.dimension.clone(),
|
player.get_entity().yaw.load(),
|
||||||
pos,
|
player.get_entity().pitch.load(),
|
||||||
player.get_entity().yaw.load(),
|
false,
|
||||||
player.get_entity().pitch.load(),
|
) {
|
||||||
false,
|
world.play_sound(
|
||||||
)
|
Sound::BlockRespawnAnchorSetSpawn,
|
||||||
.await
|
SoundCategory::Blocks,
|
||||||
{
|
&pos.to_f64(),
|
||||||
world.play_sound(
|
);
|
||||||
Sound::BlockRespawnAnchorSetSpawn,
|
|
||||||
SoundCategory::Blocks,
|
|
||||||
&pos.to_f64(),
|
|
||||||
);
|
|
||||||
|
|
||||||
player
|
player.send_system_message(&pumpkin_macros::translate_cross!(
|
||||||
.send_system_message(&pumpkin_macros::translate_cross!(
|
translation::java::BLOCK_MINECRAFT_SET_SPAWN,
|
||||||
translation::java::BLOCK_MINECRAFT_SET_SPAWN,
|
translation::bedrock::TILE_BED_RESPAWNSET
|
||||||
translation::bedrock::TILE_BED_RESPAWNSET
|
));
|
||||||
))
|
}
|
||||||
.await;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
BlockActionResult::SuccessServer
|
BlockActionResult::SuccessServer
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ impl SculkShriekerBlock {
|
|||||||
show_icon: true,
|
show_icon: true,
|
||||||
blend: true,
|
blend: true,
|
||||||
};
|
};
|
||||||
player.send_effect(darkness.clone()).await;
|
player.send_effect(&darkness);
|
||||||
player.living_entity.add_effect(darkness);
|
player.living_entity.add_effect(darkness);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -566,19 +566,17 @@ impl BlockRegistry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if location.0.y + face.to_offset().y > world.get_top_y() {
|
if location.0.y + face.to_offset().y > world.get_top_y() {
|
||||||
player
|
player.send_system_message_raw(
|
||||||
.send_system_message_raw(
|
&pumpkin_util::text::TextComponent::translate_cross(
|
||||||
&pumpkin_util::text::TextComponent::translate_cross(
|
pumpkin_data::translation::java::BUILD_TOOHIGH,
|
||||||
pumpkin_data::translation::java::BUILD_TOOHIGH,
|
pumpkin_data::translation::bedrock::BUILD_TOOHIGH,
|
||||||
pumpkin_data::translation::bedrock::BUILD_TOOHIGH,
|
vec![pumpkin_util::text::TextComponent::text(
|
||||||
vec![pumpkin_util::text::TextComponent::text(
|
(world.get_top_y()).to_string(),
|
||||||
(world.get_top_y()).to_string(),
|
)],
|
||||||
)],
|
|
||||||
)
|
|
||||||
.color_named(pumpkin_util::text::color::NamedColor::Red),
|
|
||||||
true,
|
|
||||||
)
|
)
|
||||||
.await;
|
.color_named(pumpkin_util::text::color::NamedColor::Red),
|
||||||
|
true,
|
||||||
|
);
|
||||||
return Err(BlockPlacingError::BlockOutOfWorld);
|
return Err(BlockPlacingError::BlockOutOfWorld);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -33,11 +33,7 @@ impl ArgumentConsumer for BlockArgumentConsumer {
|
|||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let block = args.pop().map(|arg| arg.value);
|
args.pop().map(|arg| Arg::Block(arg.value))
|
||||||
match block {
|
|
||||||
Some(s) => Box::pin(async move { Some(Arg::Block(s)) }),
|
|
||||||
None => Box::pin(async move { None }),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,11 +95,7 @@ impl ArgumentConsumer for BlockPredicateArgumentConsumer {
|
|||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let block = args.pop().map(|arg| arg.value);
|
args.pop().map(|arg| Arg::BlockPredicate(arg.value))
|
||||||
match block {
|
|
||||||
Some(s) => Box::pin(async move { Some(Arg::BlockPredicate(s)) }),
|
|
||||||
None => Box::pin(async move { None }),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,24 +18,19 @@ impl GetClientSideArgParser for BoolArgConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for BoolArgConsumer {
|
impl ArgumentConsumer for BoolArgConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||||
|
|
||||||
let result: Option<Arg<'a>> = s_opt.map_or_else(
|
s_opt.and_then(|s| match s {
|
||||||
|| None,
|
"false" => Some(Arg::Bool(false)),
|
||||||
|s| match s {
|
"true" => Some(Arg::Bool(true)),
|
||||||
"false" => Some(Arg::Bool(false)),
|
_ => None,
|
||||||
"true" => Some(Arg::Bool(true)),
|
})
|
||||||
_ => None,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,49 +23,35 @@ impl GetClientSideArgParser for BossbarColorArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for BossbarColorArgumentConsumer {
|
impl ArgumentConsumer for BossbarColorArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||||
|
|
||||||
let result: Option<Arg<'a>> = s_opt.map_or_else(
|
let color = match s_opt? {
|
||||||
|| None,
|
"blue" => Some(BossbarColor::Blue),
|
||||||
|s| {
|
"green" => Some(BossbarColor::Green),
|
||||||
let color = match s {
|
"pink" => Some(BossbarColor::Pink),
|
||||||
"blue" => Some(BossbarColor::Blue),
|
"purple" => Some(BossbarColor::Purple),
|
||||||
"green" => Some(BossbarColor::Green),
|
"red" => Some(BossbarColor::Red),
|
||||||
"pink" => Some(BossbarColor::Pink),
|
"white" => Some(BossbarColor::White),
|
||||||
"purple" => Some(BossbarColor::Purple),
|
"yellow" => Some(BossbarColor::Yellow),
|
||||||
"red" => Some(BossbarColor::Red),
|
_ => None,
|
||||||
"white" => Some(BossbarColor::White),
|
};
|
||||||
"yellow" => Some(BossbarColor::Yellow),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
color.map(Arg::BossbarColor)
|
color.map(Arg::BossbarColor)
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn suggest<'a>(
|
fn suggest(&self, _sender: &CommandSender, _server: &Server, _input: &str) -> SuggestResult {
|
||||||
&'a self,
|
let colors = ["blue", "green", "pink", "purple", "red", "white", "yellow"];
|
||||||
_sender: &CommandSender,
|
let suggestions: Vec<CommandSuggestion> = colors
|
||||||
_server: &'a Server,
|
.iter()
|
||||||
_input: &'a str,
|
.map(|color| CommandSuggestion::new((*color).to_string(), None))
|
||||||
) -> SuggestResult<'a> {
|
.collect();
|
||||||
Box::pin(async move {
|
Ok(Some(suggestions))
|
||||||
let colors = ["blue", "green", "pink", "purple", "red", "white", "yellow"];
|
|
||||||
let suggestions: Vec<CommandSuggestion> = colors
|
|
||||||
.iter()
|
|
||||||
.map(|color| CommandSuggestion::new((*color).to_string(), None))
|
|
||||||
.collect();
|
|
||||||
Ok(Some(suggestions))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,53 +23,39 @@ impl GetClientSideArgParser for BossbarStyleArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for BossbarStyleArgumentConsumer {
|
impl ArgumentConsumer for BossbarStyleArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||||
|
|
||||||
let result: Option<Arg<'a>> = s_opt.map_or_else(
|
let style = match s_opt? {
|
||||||
|| None,
|
"notched_10" => Some(BossbarDivisions::Notches10),
|
||||||
|s| {
|
"notched_12" => Some(BossbarDivisions::Notches12),
|
||||||
let style = match s {
|
"notched_20" => Some(BossbarDivisions::Notches20),
|
||||||
"notched_10" => Some(BossbarDivisions::Notches10),
|
"notched_6" => Some(BossbarDivisions::Notches6),
|
||||||
"notched_12" => Some(BossbarDivisions::Notches12),
|
"progress" => Some(BossbarDivisions::NoDivision),
|
||||||
"notched_20" => Some(BossbarDivisions::Notches20),
|
_ => None,
|
||||||
"notched_6" => Some(BossbarDivisions::Notches6),
|
};
|
||||||
"progress" => Some(BossbarDivisions::NoDivision),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
style.map(Arg::BossbarStyle)
|
style.map(Arg::BossbarStyle)
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn suggest<'a>(
|
fn suggest(&self, _sender: &CommandSender, _server: &Server, _input: &str) -> SuggestResult {
|
||||||
&'a self,
|
let styles = [
|
||||||
_sender: &CommandSender,
|
"notched_10",
|
||||||
_server: &'a Server,
|
"notched_12",
|
||||||
_input: &'a str,
|
"notched_20",
|
||||||
) -> SuggestResult<'a> {
|
"notched_6",
|
||||||
Box::pin(async move {
|
"progress",
|
||||||
let styles = [
|
];
|
||||||
"notched_10",
|
let suggestions: Vec<CommandSuggestion> = styles
|
||||||
"notched_12",
|
.iter()
|
||||||
"notched_20",
|
.map(|style| CommandSuggestion::new((*style).to_string(), None))
|
||||||
"notched_6",
|
.collect();
|
||||||
"progress",
|
Ok(Some(suggestions))
|
||||||
];
|
|
||||||
let suggestions: Vec<CommandSuggestion> = styles
|
|
||||||
.iter()
|
|
||||||
.map(|style| CommandSuggestion::new((*style).to_string(), None))
|
|
||||||
.collect();
|
|
||||||
Ok(Some(suggestions))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -25,15 +25,15 @@ impl<T: ToFromNumber> ArgumentConsumer for BoundedNumArgumentConsumer<T>
|
|||||||
where
|
where
|
||||||
Self: GetClientSideArgParser,
|
Self: GetClientSideArgParser,
|
||||||
{
|
{
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||||
|
|
||||||
let result: Option<Arg<'a>> = s_opt
|
s_opt
|
||||||
// Replace args.pop()?.parse::<T>().ok()?
|
// Replace args.pop()?.parse::<T>().ok()?
|
||||||
.and_then(|s| s.parse::<T>().ok())
|
.and_then(|s| s.parse::<T>().ok())
|
||||||
.map(|x| {
|
.map(|x| {
|
||||||
@@ -53,9 +53,7 @@ where
|
|||||||
|
|
||||||
// Success case
|
// Success case
|
||||||
Arg::Num(Ok(x.to_number()))
|
Arg::Num(Ok(x.to_number()))
|
||||||
});
|
})
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,50 +27,37 @@ impl GetClientSideArgParser for CommandTreeArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for CommandTreeArgumentConsumer {
|
impl ArgumentConsumer for CommandTreeArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
server: &'a Server,
|
server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let s = args.pop().map(|arg| arg.value)?;
|
||||||
|
|
||||||
let Some(s) = s_opt else {
|
let dispatcher = server.command_dispatcher.load();
|
||||||
return Box::pin(async move { None });
|
|
||||||
};
|
|
||||||
|
|
||||||
Box::pin(async move {
|
dispatcher
|
||||||
let dispatcher = server.command_dispatcher.load();
|
.fallback_dispatcher
|
||||||
|
.get_tree(s)
|
||||||
dispatcher
|
.ok()
|
||||||
.fallback_dispatcher
|
.map(|tree| Arg::CommandTree(tree.clone()))
|
||||||
.get_tree(s)
|
|
||||||
.ok()
|
|
||||||
.map(|tree| Arg::CommandTree(tree.clone()))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn suggest<'a>(
|
fn suggest(&self, _sender: &CommandSender, server: &Server, input: &str) -> SuggestResult {
|
||||||
&'a self,
|
let Some(input) = input.split_single_whitespace_including_empty_parts().last() else {
|
||||||
_sender: &CommandSender,
|
return Ok(None);
|
||||||
server: &'a Server,
|
};
|
||||||
input: &'a str,
|
|
||||||
) -> SuggestResult<'a> {
|
|
||||||
Box::pin(async move {
|
|
||||||
let Some(input) = input.split_single_whitespace_including_empty_parts().last() else {
|
|
||||||
return Ok(None);
|
|
||||||
};
|
|
||||||
|
|
||||||
let dispatcher = server.command_dispatcher.load();
|
let dispatcher = server.command_dispatcher.load();
|
||||||
let suggestions = dispatcher
|
let suggestions = dispatcher
|
||||||
.fallback_dispatcher
|
.fallback_dispatcher
|
||||||
.commands
|
.commands
|
||||||
.keys()
|
.keys()
|
||||||
.filter(|suggestion| suggestion.starts_with(input))
|
.filter(|suggestion| suggestion.starts_with(input))
|
||||||
.map(|suggestion| CommandSuggestion::new(suggestion.clone(), None))
|
.map(|suggestion| CommandSuggestion::new(suggestion.clone(), None))
|
||||||
.collect();
|
.collect();
|
||||||
Ok(Some(suggestions))
|
Ok(Some(suggestions))
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,26 +38,16 @@ impl ArgumentConsumer for DifficultyArgumentConsumer {
|
|||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||||
|
|
||||||
let result: Option<Arg<'a>> =
|
s_opt.and_then(|s| Difficulty::from_str(s).map(Arg::Difficulty).ok())
|
||||||
s_opt.and_then(|s| Difficulty::from_str(s).map(Arg::Difficulty).ok());
|
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn suggest<'a>(
|
fn suggest(&self, _sender: &CommandSender, _server: &Server, _input: &str) -> SuggestResult {
|
||||||
&'a self,
|
let difficulties = ["easy", "normal", "hard", "peaceful"];
|
||||||
_sender: &CommandSender,
|
let suggestions: Vec<CommandSuggestion> = difficulties
|
||||||
_server: &'a Server,
|
.iter()
|
||||||
_input: &'a str,
|
.map(|difficulty| CommandSuggestion::new((*difficulty).to_string(), None))
|
||||||
) -> SuggestResult<'a> {
|
.collect();
|
||||||
Box::pin(async move {
|
Ok(Some(suggestions))
|
||||||
let difficulties = ["easy", "normal", "hard", "peaceful"];
|
|
||||||
let suggestions: Vec<CommandSuggestion> = difficulties
|
|
||||||
.iter()
|
|
||||||
.map(|difficulty| CommandSuggestion::new((*difficulty).to_string(), None))
|
|
||||||
.collect();
|
|
||||||
Ok(Some(suggestions))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -352,33 +352,26 @@ impl GetClientSideArgParser for EntitiesArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for EntitiesArgumentConsumer {
|
impl ArgumentConsumer for EntitiesArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
sender: &'a CommandSender,
|
sender: &'a CommandSender,
|
||||||
server: &'a Server,
|
server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let s = args.pop().map(|arg| arg.value)?;
|
||||||
|
|
||||||
let Some(s) = s_opt else {
|
|
||||||
return Box::pin(async move { None });
|
|
||||||
};
|
|
||||||
|
|
||||||
let entity_selector = match s.parse::<TargetSelector>() {
|
let entity_selector = match s.parse::<TargetSelector>() {
|
||||||
Ok(selector) => selector,
|
Ok(selector) => selector,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
debug!("Failed to parse target selector '{s}': {e}");
|
debug!("Failed to parse target selector '{s}': {e}");
|
||||||
return Box::pin(async move { None }); // Return a Future resolving to None
|
return None;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
Box::pin(async move {
|
// todo: command context
|
||||||
// todo: command context
|
let entities = server.select_entities(&entity_selector, Some(sender));
|
||||||
// This is the required asynchronous operation.
|
|
||||||
let entities = server.select_entities(&entity_selector, Some(sender));
|
|
||||||
|
|
||||||
Some(Arg::Entities(entities))
|
Some(Arg::Entities(entities))
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn consume_with_syntax<'a>(
|
fn consume_with_syntax<'a>(
|
||||||
@@ -388,18 +381,12 @@ impl ArgumentConsumer for EntitiesArgumentConsumer {
|
|||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResultWithSyntax<'a> {
|
) -> ConsumeResultWithSyntax<'a> {
|
||||||
let Some(raw_arg) = args.pop() else {
|
let Some(raw_arg) = args.pop() else {
|
||||||
return Box::pin(async { Ok(None) });
|
return Ok(None);
|
||||||
};
|
};
|
||||||
|
|
||||||
let selector = match parse_target_selector_with_context(raw_arg) {
|
let selector = parse_target_selector_with_context(raw_arg)?;
|
||||||
Ok(selector) => selector,
|
let entities = server.select_entities(&selector, Some(sender));
|
||||||
Err(error) => return Box::pin(async move { Err(error) }),
|
Ok(Some(Arg::Entities(entities)))
|
||||||
};
|
|
||||||
|
|
||||||
Box::pin(async move {
|
|
||||||
let entities = server.select_entities(&selector, Some(sender));
|
|
||||||
Ok(Some(Arg::Entities(entities)))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,37 +35,31 @@ impl GetClientSideArgParser for EntityArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for EntityArgumentConsumer {
|
impl ArgumentConsumer for EntityArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
sender: &'a CommandSender,
|
sender: &'a CommandSender,
|
||||||
server: &'a Server,
|
server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let s = args.pop().map(|arg| arg.value)?;
|
||||||
|
|
||||||
let Some(s) = s_opt else {
|
|
||||||
return Box::pin(async move { None });
|
|
||||||
};
|
|
||||||
|
|
||||||
let entity_selector = match s.parse::<TargetSelector>() {
|
let entity_selector = match s.parse::<TargetSelector>() {
|
||||||
Ok(selector) => selector,
|
Ok(selector) => selector,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
debug!("Failed to parse target selector '{s}': {e}");
|
debug!("Failed to parse target selector '{s}': {e}");
|
||||||
return Box::pin(async move { None });
|
return None;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if entity_selector.get_limit() > 1 {
|
if entity_selector.get_limit() > 1 {
|
||||||
debug!("Target selector '{s}' has limit > 1, expected single entity");
|
debug!("Target selector '{s}' has limit > 1, expected single entity");
|
||||||
return Box::pin(async move { None });
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
Box::pin(async move {
|
// todo: command context
|
||||||
// todo: command context
|
let entities = server.select_entities(&entity_selector, Some(sender));
|
||||||
let entities = server.select_entities(&entity_selector, Some(sender));
|
|
||||||
|
|
||||||
entities.into_iter().next().map(Arg::Entity)
|
entities.into_iter().next().map(Arg::Entity)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn consume_with_syntax<'a>(
|
fn consume_with_syntax<'a>(
|
||||||
@@ -75,22 +69,17 @@ impl ArgumentConsumer for EntityArgumentConsumer {
|
|||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResultWithSyntax<'a> {
|
) -> ConsumeResultWithSyntax<'a> {
|
||||||
let Some(raw_arg) = args.pop() else {
|
let Some(raw_arg) = args.pop() else {
|
||||||
return Box::pin(async { Ok(None) });
|
return Ok(None);
|
||||||
};
|
};
|
||||||
|
|
||||||
let selector = match parse_target_selector_with_context(raw_arg) {
|
let selector = parse_target_selector_with_context(raw_arg)?;
|
||||||
Ok(selector) => selector,
|
|
||||||
Err(error) => return Box::pin(async move { Err(error) }),
|
|
||||||
};
|
|
||||||
|
|
||||||
if selector.get_limit() > 1 {
|
if selector.get_limit() > 1 {
|
||||||
return Box::pin(async { Ok(None) });
|
return Ok(None);
|
||||||
}
|
}
|
||||||
|
|
||||||
Box::pin(async move {
|
let entities = server.select_entities(&selector, Some(sender));
|
||||||
let entities = server.select_entities(&selector, Some(sender));
|
Ok(entities.into_iter().next().map(Arg::Entity))
|
||||||
Ok(entities.into_iter().next().map(Arg::Entity))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -47,17 +47,15 @@ impl ArgumentConsumer for EntityAnchorArgumentConsumer {
|
|||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let Some(anchor_str) = args.pop().map(|arg| arg.value) else {
|
let anchor_str = args.pop().map(|arg| arg.value)?;
|
||||||
return Box::pin(async move { None });
|
|
||||||
};
|
|
||||||
|
|
||||||
let anchor = match anchor_str.to_lowercase().as_str() {
|
let anchor = match anchor_str.to_lowercase().as_str() {
|
||||||
"feet" => EntityAnchor::Feet,
|
"feet" => EntityAnchor::Feet,
|
||||||
"eyes" => EntityAnchor::Eyes,
|
"eyes" => EntityAnchor::Eyes,
|
||||||
_ => return Box::pin(async move { None }),
|
_ => return None,
|
||||||
};
|
};
|
||||||
|
|
||||||
Box::pin(async move { Some(Arg::EntityAnchor(anchor)) })
|
Some(Arg::EntityAnchor(anchor))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,15 +23,15 @@ impl GetClientSideArgParser for GamemodeArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for GamemodeArgumentConsumer {
|
impl ArgumentConsumer for GamemodeArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||||
|
|
||||||
let result: Option<Arg<'a>> = s_opt.and_then(|s| {
|
s_opt.and_then(|s| {
|
||||||
if let Ok(id) = s.parse::<i8>()
|
if let Ok(id) = s.parse::<i8>()
|
||||||
&& let Ok(gamemode) = GameMode::try_from(id)
|
&& let Ok(gamemode) = GameMode::try_from(id)
|
||||||
{
|
{
|
||||||
@@ -39,9 +39,7 @@ impl ArgumentConsumer for GamemodeArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
GameMode::from_str(s).map(Arg::GameMode).ok() // Convert Result to Option<T>
|
GameMode::from_str(s).map(Arg::GameMode).ok() // Convert Result to Option<T>
|
||||||
});
|
})
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -76,16 +76,11 @@ impl ArgumentConsumer for GameProfilesArgumentConsumer {
|
|||||||
server: &'a Server,
|
server: &'a Server,
|
||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let Some(raw_arg) = args.pop() else {
|
let raw_arg = args.pop()?;
|
||||||
return Box::pin(async { None });
|
|
||||||
};
|
|
||||||
|
|
||||||
Box::pin(async move {
|
resolve_profiles_from_token(sender, server, raw_arg)
|
||||||
resolve_profiles_from_token(sender, server, raw_arg)
|
.ok()
|
||||||
.await
|
.map(Arg::GameProfiles)
|
||||||
.ok()
|
|
||||||
.map(Arg::GameProfiles)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn consume_with_syntax<'a>(
|
fn consume_with_syntax<'a>(
|
||||||
@@ -95,78 +90,89 @@ impl ArgumentConsumer for GameProfilesArgumentConsumer {
|
|||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResultWithSyntax<'a> {
|
) -> ConsumeResultWithSyntax<'a> {
|
||||||
let Some(raw_arg) = args.pop() else {
|
let Some(raw_arg) = args.pop() else {
|
||||||
return Box::pin(async { Ok(None) });
|
return Ok(None);
|
||||||
};
|
};
|
||||||
|
|
||||||
Box::pin(async move {
|
let resolved = resolve_profiles_from_token(sender, server, raw_arg)?;
|
||||||
let resolved = resolve_profiles_from_token(sender, server, raw_arg).await?;
|
Ok(Some(Arg::GameProfiles(resolved)))
|
||||||
Ok(Some(Arg::GameProfiles(resolved)))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn suggest<'a>(
|
fn suggest(&self, _sender: &CommandSender, server: &Server, _input: &str) -> SuggestResult {
|
||||||
&'a self,
|
let mut suggestions = Vec::new();
|
||||||
_sender: &CommandSender,
|
if self.suggest_selectors {
|
||||||
server: &'a Server,
|
suggestions.extend(selector_suggestions());
|
||||||
_input: &'a str,
|
}
|
||||||
) -> SuggestResult<'a> {
|
|
||||||
Box::pin(async move {
|
|
||||||
let mut suggestions = Vec::new();
|
|
||||||
if self.suggest_selectors {
|
|
||||||
suggestions.extend(selector_suggestions());
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut names = Vec::new();
|
let mut names = Vec::new();
|
||||||
match self.suggestion_mode {
|
match self.suggestion_mode {
|
||||||
GameProfileSuggestionMode::OnlinePlayers => {
|
GameProfileSuggestionMode::OnlinePlayers => {
|
||||||
for player in server.get_all_players() {
|
for player in server.get_all_players() {
|
||||||
|
push_name_if_missing(&mut names, player.gameprofile.name.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
GameProfileSuggestionMode::NonOpOnlinePlayers => {
|
||||||
|
let ops = server
|
||||||
|
.data
|
||||||
|
.operator_config
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
for player in server.get_all_players() {
|
||||||
|
if ops.ops.iter().all(|op| op.uuid != player.gameprofile.id) {
|
||||||
push_name_if_missing(&mut names, player.gameprofile.name.clone());
|
push_name_if_missing(&mut names, player.gameprofile.name.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
GameProfileSuggestionMode::NonOpOnlinePlayers => {
|
}
|
||||||
let ops = server.data.operator_config.read().await;
|
GameProfileSuggestionMode::OpNames => {
|
||||||
for player in server.get_all_players() {
|
let ops = server
|
||||||
if ops.ops.iter().all(|op| op.uuid != player.gameprofile.id) {
|
.data
|
||||||
push_name_if_missing(&mut names, player.gameprofile.name.clone());
|
.operator_config
|
||||||
}
|
.read()
|
||||||
}
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
for op in &ops.ops {
|
||||||
|
push_name_if_missing(&mut names, op.name.clone());
|
||||||
}
|
}
|
||||||
GameProfileSuggestionMode::OpNames => {
|
}
|
||||||
let ops = server.data.operator_config.read().await;
|
GameProfileSuggestionMode::BannedNames => {
|
||||||
for op in &ops.ops {
|
let banned = server
|
||||||
push_name_if_missing(&mut names, op.name.clone());
|
.data
|
||||||
}
|
.banned_player_list
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
for entry in &banned.banned_players {
|
||||||
|
push_name_if_missing(&mut names, entry.name.clone());
|
||||||
}
|
}
|
||||||
GameProfileSuggestionMode::BannedNames => {
|
}
|
||||||
let banned = server.data.banned_player_list.read().await;
|
GameProfileSuggestionMode::NonWhitelistedOnlinePlayers => {
|
||||||
for entry in &banned.banned_players {
|
let whitelist = server
|
||||||
push_name_if_missing(&mut names, entry.name.clone());
|
.data
|
||||||
}
|
.whitelist_config
|
||||||
}
|
.read()
|
||||||
GameProfileSuggestionMode::NonWhitelistedOnlinePlayers => {
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
let whitelist = server.data.whitelist_config.read().await;
|
for player in server.get_all_players() {
|
||||||
for player in server.get_all_players() {
|
if !whitelist.is_whitelisted(&player.gameprofile) {
|
||||||
if !whitelist.is_whitelisted(&player.gameprofile) {
|
push_name_if_missing(&mut names, player.gameprofile.name.clone());
|
||||||
push_name_if_missing(&mut names, player.gameprofile.name.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
GameProfileSuggestionMode::WhitelistedNames => {
|
|
||||||
let whitelist = server.data.whitelist_config.read().await;
|
|
||||||
for entry in &whitelist.whitelist {
|
|
||||||
push_name_if_missing(&mut names, entry.name.clone());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
GameProfileSuggestionMode::WhitelistedNames => {
|
||||||
|
let whitelist = server
|
||||||
|
.data
|
||||||
|
.whitelist_config
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
for entry in &whitelist.whitelist {
|
||||||
|
push_name_if_missing(&mut names, entry.name.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
suggestions.extend(
|
suggestions.extend(
|
||||||
names
|
names
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|name| CommandSuggestion::new(name, None)),
|
.map(|name| CommandSuggestion::new(name, None)),
|
||||||
);
|
);
|
||||||
|
|
||||||
Ok(Some(suggestions))
|
Ok(Some(suggestions))
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -187,7 +193,7 @@ impl<'a> FindArg<'a> for GameProfilesArgumentConsumer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn resolve_profiles_from_token(
|
fn resolve_profiles_from_token(
|
||||||
sender: &CommandSender,
|
sender: &CommandSender,
|
||||||
server: &Server,
|
server: &Server,
|
||||||
raw_arg: RawArg<'_>,
|
raw_arg: RawArg<'_>,
|
||||||
@@ -212,12 +218,17 @@ async fn resolve_profiles_from_token(
|
|||||||
return Ok(vec![player.gameprofile.clone()]);
|
return Ok(vec![player.gameprofile.clone()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
let cached_entry = server.data.user_cache.write().await.get_by_uuid(uuid);
|
let cached_entry = server
|
||||||
|
.data
|
||||||
|
.user_cache
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.get_by_uuid(uuid);
|
||||||
if let Some(entry) = cached_entry {
|
if let Some(entry) = cached_entry {
|
||||||
return Ok(vec![profile_from_uuid_name(entry.uuid, entry.name)]);
|
return Ok(vec![profile_from_uuid_name(entry.uuid, entry.name)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(profile) = resolve_known_profile_by_uuid(server, uuid).await {
|
if let Some(profile) = resolve_known_profile_by_uuid(server, uuid) {
|
||||||
return Ok(vec![profile]);
|
return Ok(vec![profile]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -232,13 +243,13 @@ async fn resolve_profiles_from_token(
|
|||||||
.data
|
.data
|
||||||
.user_cache
|
.user_cache
|
||||||
.write()
|
.write()
|
||||||
.await
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
.get_by_name(raw_arg.value);
|
.get_by_name(raw_arg.value);
|
||||||
if let Some(entry) = cached_entry {
|
if let Some(entry) = cached_entry {
|
||||||
return Ok(vec![profile_from_uuid_name(entry.uuid, entry.name)]);
|
return Ok(vec![profile_from_uuid_name(entry.uuid, entry.name)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(profile) = resolve_known_profile_by_name(server, raw_arg.value).await {
|
if let Some(profile) = resolve_known_profile_by_name(server, raw_arg.value) {
|
||||||
return Ok(vec![profile]);
|
return Ok(vec![profile]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,7 +263,7 @@ async fn resolve_profiles_from_token(
|
|||||||
.data
|
.data
|
||||||
.user_cache
|
.user_cache
|
||||||
.write()
|
.write()
|
||||||
.await
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
.upsert(uuid, resolved_name.clone());
|
.upsert(uuid, resolved_name.clone());
|
||||||
return Ok(vec![profile_from_uuid_name(uuid, resolved_name)]);
|
return Ok(vec![profile_from_uuid_name(uuid, resolved_name)]);
|
||||||
}
|
}
|
||||||
@@ -266,7 +277,7 @@ async fn resolve_profiles_from_token(
|
|||||||
.data
|
.data
|
||||||
.user_cache
|
.user_cache
|
||||||
.write()
|
.write()
|
||||||
.await
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
.upsert(profile.id, profile.name.clone());
|
.upsert(profile.id, profile.name.clone());
|
||||||
return Ok(vec![profile]);
|
return Ok(vec![profile]);
|
||||||
}
|
}
|
||||||
@@ -274,16 +285,24 @@ async fn resolve_profiles_from_token(
|
|||||||
Err(syntax_player_unknown(raw_arg))
|
Err(syntax_player_unknown(raw_arg))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn resolve_known_profile_by_name(server: &Server, name: &str) -> Option<GameProfile> {
|
fn resolve_known_profile_by_name(server: &Server, name: &str) -> Option<GameProfile> {
|
||||||
{
|
{
|
||||||
let ops = server.data.operator_config.read().await;
|
let ops = server
|
||||||
|
.data
|
||||||
|
.operator_config
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
if let Some(op) = ops.ops.iter().find(|op| op.name.eq_ignore_ascii_case(name)) {
|
if let Some(op) = ops.ops.iter().find(|op| op.name.eq_ignore_ascii_case(name)) {
|
||||||
return Some(profile_from_uuid_name(op.uuid, op.name.clone()));
|
return Some(profile_from_uuid_name(op.uuid, op.name.clone()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
let banned_players = server.data.banned_player_list.read().await;
|
let banned_players = server
|
||||||
|
.data
|
||||||
|
.banned_player_list
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
if let Some(entry) = banned_players
|
if let Some(entry) = banned_players
|
||||||
.banned_players
|
.banned_players
|
||||||
.iter()
|
.iter()
|
||||||
@@ -294,7 +313,11 @@ async fn resolve_known_profile_by_name(server: &Server, name: &str) -> Option<Ga
|
|||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
let whitelist = server.data.whitelist_config.read().await;
|
let whitelist = server
|
||||||
|
.data
|
||||||
|
.whitelist_config
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
if let Some(entry) = whitelist
|
if let Some(entry) = whitelist
|
||||||
.whitelist
|
.whitelist
|
||||||
.iter()
|
.iter()
|
||||||
@@ -307,16 +330,24 @@ async fn resolve_known_profile_by_name(server: &Server, name: &str) -> Option<Ga
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn resolve_known_profile_by_uuid(server: &Server, uuid: Uuid) -> Option<GameProfile> {
|
fn resolve_known_profile_by_uuid(server: &Server, uuid: Uuid) -> Option<GameProfile> {
|
||||||
{
|
{
|
||||||
let ops = server.data.operator_config.read().await;
|
let ops = server
|
||||||
|
.data
|
||||||
|
.operator_config
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
if let Some(op) = ops.ops.iter().find(|op| op.uuid == uuid) {
|
if let Some(op) = ops.ops.iter().find(|op| op.uuid == uuid) {
|
||||||
return Some(profile_from_uuid_name(op.uuid, op.name.clone()));
|
return Some(profile_from_uuid_name(op.uuid, op.name.clone()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
let banned_players = server.data.banned_player_list.read().await;
|
let banned_players = server
|
||||||
|
.data
|
||||||
|
.banned_player_list
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
if let Some(entry) = banned_players
|
if let Some(entry) = banned_players
|
||||||
.banned_players
|
.banned_players
|
||||||
.iter()
|
.iter()
|
||||||
@@ -327,7 +358,11 @@ async fn resolve_known_profile_by_uuid(server: &Server, uuid: Uuid) -> Option<Ga
|
|||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
let whitelist = server.data.whitelist_config.read().await;
|
let whitelist = server
|
||||||
|
.data
|
||||||
|
.whitelist_config
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
if let Some(entry) = whitelist.whitelist.iter().find(|entry| entry.uuid == uuid) {
|
if let Some(entry) = whitelist.whitelist.iter().find(|entry| entry.uuid == uuid) {
|
||||||
return Some(profile_from_uuid_name(entry.uuid, entry.name.clone()));
|
return Some(profile_from_uuid_name(entry.uuid, entry.name.clone()));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,17 +48,15 @@ impl GetClientSideArgParser for HexColorArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for HexColorArgumentConsumer {
|
impl ArgumentConsumer for HexColorArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||||
|
|
||||||
let result = s_opt.and_then(|s| parse_hex_color(s).map(Arg::HexColor));
|
s_opt.and_then(|s| parse_hex_color(s).map(Arg::HexColor))
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn consume_with_syntax<'a>(
|
fn consume_with_syntax<'a>(
|
||||||
@@ -68,31 +66,24 @@ impl ArgumentConsumer for HexColorArgumentConsumer {
|
|||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResultWithSyntax<'a> {
|
) -> ConsumeResultWithSyntax<'a> {
|
||||||
let Some(raw_arg) = args.pop() else {
|
let Some(raw_arg) = args.pop() else {
|
||||||
return Box::pin(async { Ok(None) });
|
return Ok(None);
|
||||||
};
|
};
|
||||||
|
|
||||||
let result = parse_hex_color(raw_arg.value)
|
parse_hex_color(raw_arg.value)
|
||||||
.map(|color| Some(Arg::HexColor(color)))
|
.map(|color| Some(Arg::HexColor(color)))
|
||||||
.ok_or_else(|| {
|
.ok_or_else(|| {
|
||||||
INVALID_HEX_ERROR_TYPE.create_without_context_args_slice(&[TextComponent::text(
|
INVALID_HEX_ERROR_TYPE.create_without_context_args_slice(&[TextComponent::text(
|
||||||
raw_arg.value.to_string(),
|
raw_arg.value.to_string(),
|
||||||
)])
|
)])
|
||||||
});
|
})
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn suggest<'a>(
|
fn suggest(&self, _sender: &CommandSender, _server: &Server, _input: &str) -> SuggestResult {
|
||||||
&'a self,
|
|
||||||
_sender: &CommandSender,
|
|
||||||
_server: &'a Server,
|
|
||||||
_input: &'a str,
|
|
||||||
) -> SuggestResult<'a> {
|
|
||||||
let suggestions = vec![
|
let suggestions = vec![
|
||||||
CommandSuggestion::new("F00".to_string(), None),
|
CommandSuggestion::new("F00".to_string(), None),
|
||||||
CommandSuggestion::new("FF0000".to_string(), None),
|
CommandSuggestion::new("FF0000".to_string(), None),
|
||||||
];
|
];
|
||||||
Box::pin(async move { Ok(Some(suggestions)) })
|
Ok(Some(suggestions))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,19 +35,16 @@ impl ArgumentConsumer for MsgArgConsumer {
|
|||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let first_word_opt = args.pop();
|
let first_word = args.pop()?;
|
||||||
|
|
||||||
let mut msg = match first_word_opt {
|
let mut msg = first_word.value.to_string();
|
||||||
Some(word) => word.value.to_string(),
|
|
||||||
None => return Box::pin(async { None }),
|
|
||||||
};
|
|
||||||
|
|
||||||
while let Some(word) = args.pop() {
|
while let Some(word) = args.pop() {
|
||||||
msg.push(' ');
|
msg.push(' ');
|
||||||
msg.push_str(word.value);
|
msg.push_str(word.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
Box::pin(async move { Some(Arg::Msg(msg)) })
|
Some(Arg::Msg(msg))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
use std::pin::Pin;
|
|
||||||
use std::{collections::HashMap, hash::Hash, sync::Arc};
|
use std::{collections::HashMap, hash::Hash, sync::Arc};
|
||||||
|
|
||||||
use bounded_num::{NotInBounds, Number};
|
use bounded_num::{NotInBounds, Number};
|
||||||
@@ -60,12 +59,10 @@ pub mod textcomponent;
|
|||||||
pub mod time;
|
pub mod time;
|
||||||
|
|
||||||
/// see [`crate::command::tree::builder::argument`]
|
/// see [`crate::command::tree::builder::argument`]
|
||||||
pub type ConsumeResult<'a> = Pin<Box<dyn Future<Output = Option<Arg<'a>>> + Send + 'a>>;
|
pub type ConsumeResult<'a> = Option<Arg<'a>>;
|
||||||
pub type ConsumeResultWithSyntax<'a> =
|
pub type ConsumeResultWithSyntax<'a> = Result<Option<Arg<'a>>, CommandSyntaxError>;
|
||||||
Pin<Box<dyn Future<Output = Result<Option<Arg<'a>>, CommandSyntaxError>> + Send + 'a>>;
|
|
||||||
|
|
||||||
pub type SuggestResult<'a> =
|
pub type SuggestResult = Result<Option<Vec<CommandSuggestion>>, CommandError>;
|
||||||
Pin<Box<dyn Future<Output = Result<Option<Vec<CommandSuggestion>>, CommandError>> + Send + 'a>>;
|
|
||||||
|
|
||||||
pub trait ArgumentConsumer: Sync + Send + GetClientSideArgParser {
|
pub trait ArgumentConsumer: Sync + Send + GetClientSideArgParser {
|
||||||
fn consume<'a>(
|
fn consume<'a>(
|
||||||
@@ -81,20 +78,14 @@ pub trait ArgumentConsumer: Sync + Send + GetClientSideArgParser {
|
|||||||
server: &'a Server,
|
server: &'a Server,
|
||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResultWithSyntax<'a> {
|
) -> ConsumeResultWithSyntax<'a> {
|
||||||
let future = self.consume(sender, server, args);
|
Ok(self.consume(sender, server, args))
|
||||||
Box::pin(async move { Ok(future.await) })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Used for tab completion (but only if argument suggestion type is "`minecraft:ask_server`"!).
|
/// Used for tab completion (but only if argument suggestion type is "`minecraft:ask_server`"!).
|
||||||
///
|
///
|
||||||
/// NOTE: This is called after this consumer's [`ArgumentConsumer::consume`] method returned None, so if args is used here, make sure [`ArgumentConsumer::consume`] never returns None after mutating args.
|
/// NOTE: This is called after this consumer's [`ArgumentConsumer::consume`] method returned None, so if args is used here, make sure [`ArgumentConsumer::consume`] never returns None after mutating args.
|
||||||
fn suggest<'a>(
|
fn suggest(&self, _sender: &CommandSender, _server: &Server, _input: &str) -> SuggestResult {
|
||||||
&'a self,
|
Ok(None)
|
||||||
_sender: &CommandSender,
|
|
||||||
_server: &'a Server,
|
|
||||||
_input: &'a str,
|
|
||||||
) -> SuggestResult<'a> {
|
|
||||||
Box::pin(async move { Ok(None) })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -30,17 +30,13 @@ impl GetClientSideArgParser for PlayersArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for PlayersArgumentConsumer {
|
impl ArgumentConsumer for PlayersArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
sender: &'a CommandSender,
|
sender: &'a CommandSender,
|
||||||
server: &'a Server,
|
server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let s = args.pop().map(|arg| arg.value)?;
|
||||||
|
|
||||||
let Some(s) = s_opt else {
|
|
||||||
return Box::pin(async move { None });
|
|
||||||
};
|
|
||||||
|
|
||||||
let sync_result: Option<Vec<Arc<Player>>> = match s {
|
let sync_result: Option<Vec<Arc<Player>>> = match s {
|
||||||
"@s" => match sender {
|
"@s" => match sender {
|
||||||
@@ -57,20 +53,18 @@ impl ArgumentConsumer for PlayersArgumentConsumer {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if let Some(players) = sync_result {
|
if let Some(players) = sync_result {
|
||||||
return Box::pin(async move { Some(Arg::Players(players)) });
|
return Some(Arg::Players(players));
|
||||||
}
|
}
|
||||||
|
|
||||||
Box::pin(async move {
|
let players = match s {
|
||||||
let players = match s {
|
"@r" => server
|
||||||
"@r" => server
|
.get_random_player()
|
||||||
.get_random_player()
|
.map_or_else(|| Some(vec![]), |p| Some(vec![p])),
|
||||||
.map_or_else(|| Some(vec![]), |p| Some(vec![p])),
|
"@a" | "@e" => Some(server.get_all_players()),
|
||||||
"@a" | "@e" => Some(server.get_all_players()),
|
name => server.get_player_by_name(name).map(|p| vec![p]),
|
||||||
name => server.get_player_by_name(name).map(|p| vec![p]),
|
};
|
||||||
};
|
|
||||||
|
|
||||||
players.map(Arg::Players)
|
players.map(Arg::Players)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn consume_with_syntax<'a>(
|
fn consume_with_syntax<'a>(
|
||||||
@@ -80,22 +74,14 @@ impl ArgumentConsumer for PlayersArgumentConsumer {
|
|||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResultWithSyntax<'a> {
|
) -> ConsumeResultWithSyntax<'a> {
|
||||||
let Some(raw_arg) = args.pop() else {
|
let Some(raw_arg) = args.pop() else {
|
||||||
return Box::pin(async { Ok(None) });
|
return Ok(None);
|
||||||
};
|
};
|
||||||
|
|
||||||
let selector = match parse_target_selector_with_context(raw_arg) {
|
let selector = parse_target_selector_with_context(raw_arg)?;
|
||||||
Ok(selector) => selector,
|
ensure_player_only_selector(&selector, raw_arg)?;
|
||||||
Err(error) => return Box::pin(async move { Err(error) }),
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Err(error) = ensure_player_only_selector(&selector, raw_arg) {
|
let players = server.select_players(&selector, Some(sender));
|
||||||
return Box::pin(async move { Err(error) });
|
Ok(Some(Arg::Players(players)))
|
||||||
}
|
|
||||||
|
|
||||||
Box::pin(async move {
|
|
||||||
let players = server.select_players(&selector, Some(sender));
|
|
||||||
Ok(Some(Arg::Players(players)))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,24 +28,18 @@ impl GetClientSideArgParser for Position2DArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for Position2DArgumentConsumer {
|
impl ArgumentConsumer for Position2DArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
sender: &'a CommandSender,
|
sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let x_str_opt = args.pop().map(|arg| arg.value);
|
let x_str = args.pop()?.value;
|
||||||
let z_str_opt = args.pop().map(|arg| arg.value);
|
let z_str = args.pop()?.value;
|
||||||
|
|
||||||
let (Some(x_str), Some(z_str)) = (x_str_opt, z_str_opt) else {
|
MaybeRelativePosition2D::try_new(x_str, z_str)
|
||||||
return Box::pin(async move { None });
|
|
||||||
};
|
|
||||||
|
|
||||||
let result: Option<Arg<'a>> = MaybeRelativePosition2D::try_new(x_str, z_str)
|
|
||||||
.and_then(|pos| pos.try_to_absolute(sender.position()))
|
.and_then(|pos| pos.try_to_absolute(sender.position()))
|
||||||
.map(Arg::Pos2D);
|
.map(Arg::Pos2D)
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -25,25 +25,19 @@ impl GetClientSideArgParser for Position3DArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for Position3DArgumentConsumer {
|
impl ArgumentConsumer for Position3DArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
sender: &'a CommandSender,
|
sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let x_str_opt = args.pop().map(|arg| arg.value);
|
let x_str = args.pop()?.value;
|
||||||
let y_str_opt = args.pop().map(|arg| arg.value);
|
let y_str = args.pop()?.value;
|
||||||
let z_str_opt = args.pop().map(|arg| arg.value);
|
let z_str = args.pop()?.value;
|
||||||
|
|
||||||
let (Some(x_str), Some(y_str), Some(z_str)) = (x_str_opt, y_str_opt, z_str_opt) else {
|
MaybeRelativePosition3D::try_new(x_str, y_str, z_str)
|
||||||
return Box::pin(async move { None });
|
|
||||||
};
|
|
||||||
|
|
||||||
let result: Option<Arg<'a>> = MaybeRelativePosition3D::try_new(x_str, y_str, z_str)
|
|
||||||
.and_then(|pos| pos.try_to_absolute(sender.position()))
|
.and_then(|pos| pos.try_to_absolute(sender.position()))
|
||||||
.map(Arg::Pos3D);
|
.map(Arg::Pos3D)
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,25 +28,19 @@ impl GetClientSideArgParser for BlockPosArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for BlockPosArgumentConsumer {
|
impl ArgumentConsumer for BlockPosArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
sender: &'a CommandSender,
|
sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let x_str_opt = args.pop().map(|arg| arg.value);
|
let x_str = args.pop()?.value;
|
||||||
let y_str_opt = args.pop().map(|arg| arg.value);
|
let y_str = args.pop()?.value;
|
||||||
let z_str_opt = args.pop().map(|arg| arg.value);
|
let z_str = args.pop()?.value;
|
||||||
|
|
||||||
let (Some(x_str), Some(y_str), Some(z_str)) = (x_str_opt, y_str_opt, z_str_opt) else {
|
MaybeRelativeBlockPos::try_new(x_str, y_str, z_str)
|
||||||
return Box::pin(async move { None });
|
|
||||||
};
|
|
||||||
|
|
||||||
let result: Option<Arg<'a>> = MaybeRelativeBlockPos::try_new(x_str, y_str, z_str)
|
|
||||||
.and_then(|pos| pos.try_to_absolute(sender))
|
.and_then(|pos| pos.try_to_absolute(sender))
|
||||||
.map(Arg::BlockPos);
|
.map(Arg::BlockPos)
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,23 +27,15 @@ impl GetClientSideArgParser for DamageTypeArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for DamageTypeArgumentConsumer {
|
impl ArgumentConsumer for DamageTypeArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let name_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let name = args.pop().map(|arg| arg.value)?;
|
||||||
|
let name = name.strip_prefix("minecraft:").unwrap_or(name);
|
||||||
let result: Option<Arg<'a>> = name_opt.map_or_else(
|
DamageType::from_name(name).map(Arg::DamageType)
|
||||||
|| None,
|
|
||||||
|name| {
|
|
||||||
let name = name.strip_prefix("minecraft:").unwrap_or(name);
|
|
||||||
DamageType::from_name(name).map(Arg::DamageType)
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,22 +27,16 @@ impl GetClientSideArgParser for EffectTypeArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for EffectTypeArgumentConsumer {
|
impl ArgumentConsumer for EffectTypeArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let status_effect: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let name = args.pop().map(|arg| arg.value)?;
|
||||||
|
let status_effect =
|
||||||
match status_effect {
|
StatusEffect::from_name(name.strip_prefix("minecraft:").unwrap_or(name))?;
|
||||||
Some(name) => Box::pin(async move {
|
Some(Arg::Effect(status_effect))
|
||||||
let status_effect =
|
|
||||||
StatusEffect::from_name(name.strip_prefix("minecraft:").unwrap_or(name))?;
|
|
||||||
Some(Arg::Effect(status_effect))
|
|
||||||
}),
|
|
||||||
None => Box::pin(async move { None }),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,19 +27,14 @@ impl GetClientSideArgParser for EnchantmentArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for EnchantmentArgumentConsumer {
|
impl ArgumentConsumer for EnchantmentArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let name_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let name = args.pop().map(|arg| arg.value)?;
|
||||||
|
Enchantment::from_name(name).map(Arg::Enchantment)
|
||||||
let result: Option<Arg<'a>> = name_opt.map_or_else(
|
|
||||||
|| None,
|
|
||||||
|name| Enchantment::from_name(name).map(Arg::Enchantment),
|
|
||||||
);
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -37,12 +37,7 @@ impl ArgumentConsumer for ItemArgumentConsumer {
|
|||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let item = args.pop().map(|arg| arg.value);
|
args.pop().map(|arg| Arg::Item(arg.value))
|
||||||
// TODO: When supporting data components in this argument, do it for ItemPredicateArgumentConsumer as well (both tags and items)
|
|
||||||
match item {
|
|
||||||
Some(s) => Box::pin(async move { Some(Arg::Item(s)) }),
|
|
||||||
None => Box::pin(async move { None }),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -182,11 +177,7 @@ impl ArgumentConsumer for ItemPredicateArgumentConsumer {
|
|||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let item = args.pop().map(|arg| arg.value);
|
args.pop().map(|arg| Arg::Item(arg.value))
|
||||||
match item {
|
|
||||||
Some(s) => Box::pin(async move { Some(Arg::Item(s)) }),
|
|
||||||
None => Box::pin(async move { None }),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,23 +27,14 @@ impl GetClientSideArgParser for ParticleArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for ParticleArgumentConsumer {
|
impl ArgumentConsumer for ParticleArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let name_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let name = args.pop().map(|arg| arg.value)?;
|
||||||
|
Particle::from_name(name.strip_prefix("minecraft:").unwrap_or(name)).map(Arg::Particle)
|
||||||
let result: Option<Arg<'a>> = name_opt.map_or_else(
|
|
||||||
|| None,
|
|
||||||
|name| {
|
|
||||||
Particle::from_name(name.strip_prefix("minecraft:").unwrap_or(name))
|
|
||||||
.map(Arg::Particle)
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ impl ArgumentConsumer for ResourceLocationArgumentConsumer {
|
|||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let identifier = args.pop().and_then(|arg| Identifier::parse(arg.value).ok());
|
let identifier = args.pop().and_then(|arg| Identifier::parse(arg.value).ok());
|
||||||
|
|
||||||
Box::pin(async move { identifier.map(Arg::ResourceLocation) })
|
identifier.map(Arg::ResourceLocation)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -45,26 +45,19 @@ impl GetClientSideArgParser for RotationArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for RotationArgumentConsumer {
|
impl ArgumentConsumer for RotationArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let yaw_str_opt = args.pop().map(|arg| arg.value);
|
let yaw_str = args.pop()?.value;
|
||||||
let pitch_str_opt = args.pop().map(|arg| arg.value);
|
let pitch_str = args.pop()?.value;
|
||||||
|
|
||||||
let (Some(yaw_str), Some(pitch_str)) = (yaw_str_opt, pitch_str_opt) else {
|
let (yaw, yaw_rel) = parse_rotation_component(yaw_str)?;
|
||||||
return Box::pin(async move { None });
|
let (pitch, pitch_rel) = parse_rotation_component(pitch_str)?;
|
||||||
};
|
|
||||||
|
|
||||||
let result: Option<Arg<'a>> =
|
Some(Arg::Rotation(yaw, yaw_rel, pitch, pitch_rel))
|
||||||
parse_rotation_component(yaw_str).and_then(|(yaw, yaw_rel)| {
|
|
||||||
parse_rotation_component(pitch_str)
|
|
||||||
.map(|(pitch, pitch_rel)| Arg::Rotation(yaw, yaw_rel, pitch, pitch_rel))
|
|
||||||
});
|
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,15 +29,13 @@ impl GetClientSideArgParser for SimpleArgConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for SimpleArgConsumer {
|
impl ArgumentConsumer for SimpleArgConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
args.pop().map(|arg| Arg::Simple(arg.value))
|
||||||
|
|
||||||
Box::pin(async move { s_opt.map(Arg::Simple) })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,18 +27,13 @@ impl ArgumentConsumer for SlotArgumentConsumer {
|
|||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let slot = args.pop().map(|arg| arg.value);
|
let s = args.pop()?.value;
|
||||||
match slot {
|
if let Some(range) = get_slot_range(s)
|
||||||
Some(s) => Box::pin(async move {
|
&& range.len() == 1
|
||||||
if let Some(range) = get_slot_range(s)
|
{
|
||||||
&& range.len() == 1
|
return Some(Arg::Slot(range[0], s.to_string()));
|
||||||
{
|
|
||||||
return Some(Arg::Slot(range[0], s.to_string()));
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}),
|
|
||||||
None => Box::pin(async move { None }),
|
|
||||||
}
|
}
|
||||||
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,16 +73,11 @@ impl ArgumentConsumer for SlotsArgumentConsumer {
|
|||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let slots = args.pop().map(|arg| arg.value);
|
let s = args.pop()?.value;
|
||||||
match slots {
|
if let Some(range) = get_slot_range(s) {
|
||||||
Some(s) => Box::pin(async move {
|
return Some(Arg::Slots(range, s.to_string()));
|
||||||
if let Some(range) = get_slot_range(s) {
|
|
||||||
return Some(Arg::Slots(range, s.to_string()));
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}),
|
|
||||||
None => Box::pin(async move { None }),
|
|
||||||
}
|
}
|
||||||
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,15 +28,13 @@ impl GetClientSideArgParser for SoundArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for SoundArgumentConsumer {
|
impl ArgumentConsumer for SoundArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
args.pop().map(|arg| Arg::Block(arg.value))
|
||||||
|
|
||||||
Box::pin(async move { s_opt.map(Arg::Block) })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -25,15 +25,15 @@ impl GetClientSideArgParser for SoundCategoryArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for SoundCategoryArgumentConsumer {
|
impl ArgumentConsumer for SoundCategoryArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||||
|
|
||||||
let result: Option<Arg<'a>> = s_opt.and_then(|s| {
|
s_opt.and_then(|s| {
|
||||||
let category = match s.to_lowercase().as_str() {
|
let category = match s.to_lowercase().as_str() {
|
||||||
"master" => Some(SoundCategory::Master),
|
"master" => Some(SoundCategory::Master),
|
||||||
"music" => Some(SoundCategory::Music),
|
"music" => Some(SoundCategory::Music),
|
||||||
@@ -50,28 +50,19 @@ impl ArgumentConsumer for SoundCategoryArgumentConsumer {
|
|||||||
};
|
};
|
||||||
|
|
||||||
category.map(Arg::SoundCategory)
|
category.map(Arg::SoundCategory)
|
||||||
});
|
})
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn suggest<'a>(
|
fn suggest(&self, _sender: &CommandSender, _server: &Server, _input: &str) -> SuggestResult {
|
||||||
&'a self,
|
let categories = [
|
||||||
_sender: &CommandSender,
|
"master", "music", "record", "weather", "block", "hostile", "neutral", "player",
|
||||||
_server: &'a Server,
|
"ambient", "voice",
|
||||||
_input: &'a str,
|
];
|
||||||
) -> SuggestResult<'a> {
|
let suggestions: Vec<CommandSuggestion> = categories
|
||||||
Box::pin(async move {
|
.iter()
|
||||||
let categories = [
|
.map(|cat| CommandSuggestion::new((*cat).to_string(), None))
|
||||||
"master", "music", "record", "weather", "block", "hostile", "neutral", "player",
|
.collect();
|
||||||
"ambient", "voice",
|
Ok(Some(suggestions))
|
||||||
];
|
|
||||||
let suggestions: Vec<CommandSuggestion> = categories
|
|
||||||
.iter()
|
|
||||||
.map(|cat| CommandSuggestion::new((*cat).to_string(), None))
|
|
||||||
.collect();
|
|
||||||
Ok(Some(suggestions))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,15 +28,13 @@ impl GetClientSideArgParser for SummonableEntitiesArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for SummonableEntitiesArgumentConsumer {
|
impl ArgumentConsumer for SummonableEntitiesArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
args.pop().map(|arg| Arg::Block(arg.value))
|
||||||
|
|
||||||
Box::pin(async move { s_opt.map(Arg::Block) })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -50,17 +50,15 @@ impl GetClientSideArgParser for TeamColorArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for TeamColorArgumentConsumer {
|
impl ArgumentConsumer for TeamColorArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||||
|
|
||||||
let result = s_opt.and_then(|s| NamedColor::try_from(s).ok().map(Arg::TeamColor));
|
s_opt.and_then(|s| NamedColor::try_from(s).ok().map(Arg::TeamColor))
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn consume_with_syntax<'a>(
|
fn consume_with_syntax<'a>(
|
||||||
@@ -70,32 +68,25 @@ impl ArgumentConsumer for TeamColorArgumentConsumer {
|
|||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResultWithSyntax<'a> {
|
) -> ConsumeResultWithSyntax<'a> {
|
||||||
let Some(raw_arg) = args.pop() else {
|
let Some(raw_arg) = args.pop() else {
|
||||||
return Box::pin(async { Ok(None) });
|
return Ok(None);
|
||||||
};
|
};
|
||||||
|
|
||||||
let result = NamedColor::try_from(raw_arg.value)
|
NamedColor::try_from(raw_arg.value)
|
||||||
.map(|color| Some(Arg::TeamColor(color)))
|
.map(|color| Some(Arg::TeamColor(color)))
|
||||||
.map_err(|()| {
|
.map_err(|()| {
|
||||||
INVALID_COLOR_ERROR_TYPE.create_without_context_args_slice(&[TextComponent::text(
|
INVALID_COLOR_ERROR_TYPE.create_without_context_args_slice(&[TextComponent::text(
|
||||||
raw_arg.value.to_string(),
|
raw_arg.value.to_string(),
|
||||||
)])
|
)])
|
||||||
});
|
})
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn suggest<'a>(
|
fn suggest(&self, _sender: &CommandSender, _server: &Server, input: &str) -> SuggestResult {
|
||||||
&'a self,
|
|
||||||
_sender: &CommandSender,
|
|
||||||
_server: &'a Server,
|
|
||||||
input: &'a str,
|
|
||||||
) -> SuggestResult<'a> {
|
|
||||||
let suggestions: Vec<CommandSuggestion> = TEAM_COLORS
|
let suggestions: Vec<CommandSuggestion> = TEAM_COLORS
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|color| color.starts_with(input))
|
.filter(|color| color.starts_with(input))
|
||||||
.map(|color| CommandSuggestion::new((*color).to_string(), None))
|
.map(|color| CommandSuggestion::new((*color).to_string(), None))
|
||||||
.collect();
|
.collect();
|
||||||
Box::pin(async move { Ok(Some(suggestions)) })
|
Ok(Some(suggestions))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,22 +20,18 @@ impl GetClientSideArgParser for TextComponentArgConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for TextComponentArgConsumer {
|
impl ArgumentConsumer for TextComponentArgConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let s = args.pop().map(|arg| arg.value)?;
|
||||||
|
|
||||||
let Some(s) = s_opt else {
|
|
||||||
return Box::pin(async move { None });
|
|
||||||
};
|
|
||||||
|
|
||||||
let text_component_opt = parse_text_component(s);
|
let text_component_opt = parse_text_component(s);
|
||||||
|
|
||||||
// TODO: Allow identifiers (starting with alphabetic or _, then alphanumeric+-_.) as display names
|
// TODO: Allow identifiers (starting with alphabetic or _, then alphanumeric+-_.) as display names
|
||||||
let final_arg: Option<Arg<'a>> = text_component_opt.map_or_else(
|
text_component_opt.map_or_else(
|
||||||
|| {
|
|| {
|
||||||
(s.starts_with('"') && s.ends_with('"')).then(|| {
|
(s.starts_with('"') && s.ends_with('"')).then(|| {
|
||||||
let s_owned = s.replace('"', "");
|
let s_owned = s.replace('"', "");
|
||||||
@@ -43,9 +39,7 @@ impl ArgumentConsumer for TextComponentArgConsumer {
|
|||||||
})
|
})
|
||||||
},
|
},
|
||||||
|text_component| Some(Arg::TextComponent(text_component)),
|
|text_component| Some(Arg::TextComponent(text_component)),
|
||||||
);
|
)
|
||||||
|
|
||||||
Box::pin(async move { final_arg })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -65,21 +65,19 @@ impl GetClientSideArgParser for TimeArgumentConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArgumentConsumer for TimeArgumentConsumer {
|
impl ArgumentConsumer for TimeArgumentConsumer {
|
||||||
fn consume<'a, 'b>(
|
fn consume<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
_sender: &'a CommandSender,
|
_sender: &'a CommandSender,
|
||||||
_server: &'a Server,
|
_server: &'a Server,
|
||||||
args: &'b mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResult<'a> {
|
) -> ConsumeResult<'a> {
|
||||||
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
let s_opt: Option<&'a str> = args.pop().map(|arg| arg.value);
|
||||||
|
|
||||||
let result: Option<Arg<'a>> = s_opt.and_then(|s| {
|
s_opt.and_then(|s| {
|
||||||
let mut reader = StringReader::new(s);
|
let mut reader = StringReader::new(s);
|
||||||
let parser = TimeArgumentType::new(self.min);
|
let parser = TimeArgumentType::new(self.min);
|
||||||
parser.parse(&mut reader).ok().map(Arg::Time)
|
parser.parse(&mut reader).ok().map(Arg::Time)
|
||||||
});
|
})
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn consume_with_syntax<'a>(
|
fn consume_with_syntax<'a>(
|
||||||
@@ -89,17 +87,15 @@ impl ArgumentConsumer for TimeArgumentConsumer {
|
|||||||
args: &mut RawArgs<'a>,
|
args: &mut RawArgs<'a>,
|
||||||
) -> ConsumeResultWithSyntax<'a> {
|
) -> ConsumeResultWithSyntax<'a> {
|
||||||
let Some(raw_arg) = args.pop() else {
|
let Some(raw_arg) = args.pop() else {
|
||||||
return Box::pin(async { Ok(None) });
|
return Ok(None);
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut reader = StringReader::new(raw_arg.value);
|
let mut reader = StringReader::new(raw_arg.value);
|
||||||
let parser = TimeArgumentType::new(self.min);
|
let parser = TimeArgumentType::new(self.min);
|
||||||
let result = parser
|
parser
|
||||||
.parse(&mut reader)
|
.parse(&mut reader)
|
||||||
.map(|ticks| Some(Arg::Time(ticks)))
|
.map(|ticks| Some(Arg::Time(ticks)))
|
||||||
.map_err(|error| map_local_syntax_error(error, raw_arg));
|
.map_err(|error| map_local_syntax_error(error, raw_arg))
|
||||||
|
|
||||||
Box::pin(async move { result })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,12 +9,9 @@ use crate::command::{
|
|||||||
errors::command_syntax_error::CommandSyntaxError, string_reader::StringReader,
|
errors::command_syntax_error::CommandSyntaxError, string_reader::StringReader,
|
||||||
};
|
};
|
||||||
use std::any::Any;
|
use std::any::Any;
|
||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
pub type JavaClientArgumentType = pumpkin_protocol::java::client::play::ArgumentType;
|
pub type JavaClientArgumentType = pumpkin_protocol::java::client::play::ArgumentType;
|
||||||
pub type ParseWithSourceAnyResult<'a> = Pin<
|
pub type ParseWithSourceAnyResult = Result<Box<dyn Any + Send + Sync>, CommandSyntaxError>;
|
||||||
Box<dyn Future<Output = Result<Box<dyn Any + Send + Sync>, CommandSyntaxError>> + Send + 'a>,
|
|
||||||
>;
|
|
||||||
|
|
||||||
/// Represents an argument type that parses a particular type `Item`.
|
/// Represents an argument type that parses a particular type `Item`.
|
||||||
pub trait ArgumentType: Send + Sync {
|
pub trait ArgumentType: Send + Sync {
|
||||||
@@ -32,27 +29,27 @@ pub trait ArgumentType: Send + Sync {
|
|||||||
///
|
///
|
||||||
/// Errors should be propagated using the `?` operator, which will
|
/// Errors should be propagated using the `?` operator, which will
|
||||||
/// replicate Brigadier's behavior of exceptions.
|
/// replicate Brigadier's behavior of exceptions.
|
||||||
fn parse_with_source<'a>(
|
fn parse_with_source(
|
||||||
&'a self,
|
&self,
|
||||||
reader: &'a mut StringReader,
|
reader: &mut StringReader,
|
||||||
_source: &'a CommandSource,
|
_source: &CommandSource,
|
||||||
) -> Pin<Box<dyn Future<Output = Result<Self::Item, CommandSyntaxError>> + Send + 'a>> {
|
) -> Result<Self::Item, CommandSyntaxError> {
|
||||||
Box::pin(async move { self.parse(reader) })
|
self.parse(reader)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Provides a list of suggestions from this argument type.
|
/// Provides a list of suggestions from this argument type.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
_builder: SuggestionsBuilder,
|
_builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move { Suggestions::empty() })
|
Suggestions::empty()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the Java client-side parser used for this argument type.
|
/// Returns the Java client-side parser used for this argument type.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType;
|
fn client_side_parser(&self) -> JavaClientArgumentType;
|
||||||
|
|
||||||
/// Overrides the suggestion providers provided from this argument if a [`Some`] containing them
|
/// Overrides the suggestion providers provided from this argument if a [`Some`] containing them
|
||||||
/// is returned.
|
/// is returned.
|
||||||
@@ -94,23 +91,23 @@ pub trait AnyArgumentType: Sealed + Send + Sync {
|
|||||||
///
|
///
|
||||||
/// Errors should be propagated using the `?` operator, which will
|
/// Errors should be propagated using the `?` operator, which will
|
||||||
/// replicate Brigadier's behavior of exceptions.
|
/// replicate Brigadier's behavior of exceptions.
|
||||||
fn parse_with_source<'a>(
|
fn parse_with_source(
|
||||||
&'a self,
|
&self,
|
||||||
reader: &'a mut StringReader,
|
reader: &mut StringReader,
|
||||||
source: &'a CommandSource,
|
source: &CommandSource,
|
||||||
) -> ParseWithSourceAnyResult<'a>;
|
) -> ParseWithSourceAnyResult;
|
||||||
|
|
||||||
/// Provides a list of suggestions from this argument type.
|
/// Provides a list of suggestions from this argument type.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>>;
|
) -> Suggestions;
|
||||||
|
|
||||||
/// Returns the Java client-side parser used for this argument type.
|
/// Returns the Java client-side parser used for this argument type.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType;
|
fn client_side_parser(&self) -> JavaClientArgumentType;
|
||||||
|
|
||||||
/// Overrides the suggestion providers provided from this argument if a [`Some`] containing them
|
/// Overrides the suggestion providers provided from this argument if a [`Some`] containing them
|
||||||
/// is returned.
|
/// is returned.
|
||||||
@@ -145,31 +142,29 @@ impl<U: ArgumentType<Item = T> + 'static, T: Send + Sync + 'static> AnyArgumentT
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_with_source<'a>(
|
fn parse_with_source(
|
||||||
&'a self,
|
&self,
|
||||||
reader: &'a mut StringReader,
|
reader: &mut StringReader,
|
||||||
source: &'a CommandSource,
|
source: &CommandSource,
|
||||||
) -> ParseWithSourceAnyResult<'a> {
|
) -> ParseWithSourceAnyResult {
|
||||||
Box::pin(async move {
|
match self.parse_with_source(reader, source) {
|
||||||
match self.parse_with_source(reader, source).await {
|
Ok(value) => {
|
||||||
Ok(value) => {
|
let value: Box<dyn Any + Send + Sync> = Box::new(value);
|
||||||
let value: Box<dyn Any + Send + Sync> = Box::new(value);
|
Ok(value)
|
||||||
Ok(value)
|
|
||||||
}
|
|
||||||
Err(error) => Err(error),
|
|
||||||
}
|
}
|
||||||
})
|
Err(error) => Err(error),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
self.list_suggestions(context, builder)
|
self.list_suggestions(context, builder)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
fn client_side_parser(&self) -> JavaClientArgumentType {
|
||||||
self.client_side_parser()
|
self.client_side_parser()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
use crate::command::{
|
use crate::command::{
|
||||||
argument_types::FromStringReader,
|
argument_types::FromStringReader,
|
||||||
argument_types::argument_type::{ArgumentType, JavaClientArgumentType},
|
argument_types::argument_type::{ArgumentType, JavaClientArgumentType},
|
||||||
@@ -46,16 +44,14 @@ impl ArgumentType for AttributeArgumentType {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move {
|
builder
|
||||||
builder
|
.filter_and_suggest_iter(Attributes::ALL.iter().map(|a| a.name))
|
||||||
.filter_and_suggest_iter(Attributes::ALL.iter().map(|a| a.name))
|
.build()
|
||||||
.build()
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
use crate::command::{
|
use crate::command::{
|
||||||
argument_types::argument_type::{ArgumentType, JavaClientArgumentType},
|
argument_types::argument_type::{ArgumentType, JavaClientArgumentType},
|
||||||
context::command_context::CommandContext,
|
context::command_context::CommandContext,
|
||||||
@@ -46,12 +44,12 @@ impl ArgumentType for BlockArgumentType {
|
|||||||
JavaClientArgumentType::BlockState
|
JavaClientArgumentType::BlockState
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move { builder.build() })
|
builder.build()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
use crate::command::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
use crate::command::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||||
use crate::command::argument_types::coordinates::Coordinates;
|
use crate::command::argument_types::coordinates::Coordinates;
|
||||||
use crate::command::context::command_context::CommandContext;
|
use crate::command::context::command_context::CommandContext;
|
||||||
@@ -56,23 +54,21 @@ impl ArgumentType for BlockPosArgumentType {
|
|||||||
examples!("1 3 5", "-3 ~24 ~-1", "80 80 80", "^ ^9 ^56")
|
examples!("1 3 5", "-3 ~24 ~-1", "80 80 80", "^ ^9 ^56")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move {
|
let remainder = builder.remaining();
|
||||||
let remainder = builder.remaining();
|
|
||||||
|
|
||||||
let suggested_coordinates = if remainder.bytes().next() == Some(b'^') {
|
let suggested_coordinates = if remainder.bytes().next() == Some(b'^') {
|
||||||
TextCoordinates::Local
|
TextCoordinates::Local
|
||||||
} else {
|
} else {
|
||||||
TextCoordinates::Global
|
TextCoordinates::Global
|
||||||
};
|
};
|
||||||
|
|
||||||
builder.suggest_3d_coordinates(suggested_coordinates, |value| {
|
builder.suggest_3d_coordinates(suggested_coordinates, |value| {
|
||||||
self.parse(&mut StringReader::new(value)).is_ok()
|
self.parse(&mut StringReader::new(value)).is_ok()
|
||||||
})
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
use pumpkin_data::translation;
|
use pumpkin_data::translation;
|
||||||
use pumpkin_util::math::position::{BlockPos, ColumnPos};
|
use pumpkin_util::math::position::{BlockPos, ColumnPos};
|
||||||
use pumpkin_util::math::vector2::Vector2;
|
use pumpkin_util::math::vector2::Vector2;
|
||||||
@@ -48,23 +46,21 @@ impl ArgumentType for ColumnPosArgumentType {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move {
|
let remainder = builder.remaining();
|
||||||
let remainder = builder.remaining();
|
|
||||||
|
|
||||||
let suggested_coordinates = if remainder.bytes().next() == Some(b'^') {
|
let suggested_coordinates = if remainder.bytes().next() == Some(b'^') {
|
||||||
TextCoordinates::Local
|
TextCoordinates::Local
|
||||||
} else {
|
} else {
|
||||||
TextCoordinates::Global
|
TextCoordinates::Global
|
||||||
};
|
};
|
||||||
|
|
||||||
builder.suggest_2d_coordinates(suggested_coordinates, |value| {
|
builder.suggest_2d_coordinates(suggested_coordinates, |value| {
|
||||||
self.parse(&mut StringReader::new(value)).is_ok()
|
self.parse(&mut StringReader::new(value)).is_ok()
|
||||||
})
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
use crate::command::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
use crate::command::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||||
use crate::command::argument_types::coordinates::Coordinates;
|
use crate::command::argument_types::coordinates::Coordinates;
|
||||||
use crate::command::context::command_context::CommandContext;
|
use crate::command::context::command_context::CommandContext;
|
||||||
@@ -60,23 +58,21 @@ impl ArgumentType for Vec3ArgumentType {
|
|||||||
examples!("1 1 1", "3 ~34 ~-2", "40 50 60", "^ ^4 ^3")
|
examples!("1 1 1", "3 ~34 ~-2", "40 50 60", "^ ^4 ^3")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move {
|
let remainder = builder.remaining();
|
||||||
let remainder = builder.remaining();
|
|
||||||
|
|
||||||
let suggestioned_coordinates = if remainder.bytes().next() == Some(b'^') {
|
let suggestioned_coordinates = if remainder.bytes().next() == Some(b'^') {
|
||||||
TextCoordinates::Local
|
TextCoordinates::Local
|
||||||
} else {
|
} else {
|
||||||
TextCoordinates::Global
|
TextCoordinates::Global
|
||||||
};
|
};
|
||||||
|
|
||||||
builder.suggest_3d_coordinates(suggestioned_coordinates, |value| {
|
builder.suggest_3d_coordinates(suggestioned_coordinates, |value| {
|
||||||
self.parse(&mut StringReader::new(value)).is_ok()
|
self.parse(&mut StringReader::new(value)).is_ok()
|
||||||
})
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ use crate::command::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
|||||||
use crate::entity::EntityBase;
|
use crate::entity::EntityBase;
|
||||||
use crate::entity::player::Player;
|
use crate::entity::player::Player;
|
||||||
use pumpkin_data::translation;
|
use pumpkin_data::translation;
|
||||||
use std::pin::Pin;
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
/// A [`CommandErrorType`] to tell that no entities could be found.
|
/// A [`CommandErrorType`] to tell that no entities could be found.
|
||||||
@@ -87,17 +86,12 @@ impl ArgumentType for EntityArgumentType {
|
|||||||
self.parse_with_allow_selectors(reader, true)
|
self.parse_with_allow_selectors(reader, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_with_source<'a>(
|
fn parse_with_source(
|
||||||
&'a self,
|
&self,
|
||||||
reader: &'a mut StringReader,
|
reader: &mut StringReader,
|
||||||
source: &'a CommandSource,
|
source: &CommandSource,
|
||||||
) -> Pin<Box<dyn Future<Output = Result<Self::Item, CommandSyntaxError>> + Send + 'a>> {
|
) -> Result<Self::Item, CommandSyntaxError> {
|
||||||
Box::pin(async move {
|
self.parse_with_allow_selectors(reader, source.has_permission(ENTITY_SELECTOR_PERMISSION))
|
||||||
self.parse_with_allow_selectors(
|
|
||||||
reader,
|
|
||||||
source.has_permission(ENTITY_SELECTOR_PERMISSION).await,
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||||
@@ -118,12 +112,12 @@ impl ArgumentType for EntityArgumentType {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
EntitySelectorParserSuggestions::list_suggestions(context, builder)
|
EntitySelectorParserSuggestions::list_suggestions(context, &builder)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,22 +150,21 @@ impl EntityArgumentType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Tries to get a single entity from a parsed argument of the provided [`CommandContext`].
|
/// Tries to get a single entity from a parsed argument of the provided [`CommandContext`].
|
||||||
pub async fn get_entity(
|
pub fn get_entity(
|
||||||
context: &CommandContext<'_>,
|
context: &CommandContext<'_>,
|
||||||
name: &str,
|
name: &str,
|
||||||
) -> Result<Arc<dyn EntityBase>, CommandSyntaxError> {
|
) -> Result<Arc<dyn EntityBase>, CommandSyntaxError> {
|
||||||
context
|
context
|
||||||
.get_argument::<EntitySelector>(name)?
|
.get_argument::<EntitySelector>(name)?
|
||||||
.find_single_entity(context.source.as_ref())
|
.find_single_entity(context.source.as_ref())
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tries to get at least 1 entity from a parsed argument of the provided [`CommandContext`].
|
/// Tries to get at least 1 entity from a parsed argument of the provided [`CommandContext`].
|
||||||
pub async fn get_entities(
|
pub fn get_entities(
|
||||||
context: &CommandContext<'_>,
|
context: &CommandContext<'_>,
|
||||||
name: &str,
|
name: &str,
|
||||||
) -> Result<Vec<Arc<dyn EntityBase>>, CommandSyntaxError> {
|
) -> Result<Vec<Arc<dyn EntityBase>>, CommandSyntaxError> {
|
||||||
let entities = Self::get_optional_entities(context, name).await?;
|
let entities = Self::get_optional_entities(context, name)?;
|
||||||
if entities.is_empty() {
|
if entities.is_empty() {
|
||||||
Err(NO_ENTITIES_ERROR_TYPE.create_without_context())
|
Err(NO_ENTITIES_ERROR_TYPE.create_without_context())
|
||||||
} else {
|
} else {
|
||||||
@@ -180,33 +173,31 @@ impl EntityArgumentType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Tries to get any number of entities from a parsed argument of the provided [`CommandContext`].
|
/// Tries to get any number of entities from a parsed argument of the provided [`CommandContext`].
|
||||||
pub async fn get_optional_entities(
|
pub fn get_optional_entities(
|
||||||
context: &CommandContext<'_>,
|
context: &CommandContext<'_>,
|
||||||
name: &str,
|
name: &str,
|
||||||
) -> Result<Vec<Arc<dyn EntityBase>>, CommandSyntaxError> {
|
) -> Result<Vec<Arc<dyn EntityBase>>, CommandSyntaxError> {
|
||||||
context
|
context
|
||||||
.get_argument::<EntitySelector>(name)?
|
.get_argument::<EntitySelector>(name)?
|
||||||
.find_entities(context.source.as_ref())
|
.find_entities(context.source.as_ref())
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tries to get a single player from a parsed argument of the provided [`CommandContext`].
|
/// Tries to get a single player from a parsed argument of the provided [`CommandContext`].
|
||||||
pub async fn get_player(
|
pub fn get_player(
|
||||||
context: &CommandContext<'_>,
|
context: &CommandContext<'_>,
|
||||||
name: &str,
|
name: &str,
|
||||||
) -> Result<Arc<Player>, CommandSyntaxError> {
|
) -> Result<Arc<Player>, CommandSyntaxError> {
|
||||||
context
|
context
|
||||||
.get_argument::<EntitySelector>(name)?
|
.get_argument::<EntitySelector>(name)?
|
||||||
.find_single_player(context.source.as_ref())
|
.find_single_player(context.source.as_ref())
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tries to get at least 1 player from a parsed argument of the provided [`CommandContext`].
|
/// Tries to get at least 1 player from a parsed argument of the provided [`CommandContext`].
|
||||||
pub async fn get_players(
|
pub fn get_players(
|
||||||
context: &CommandContext<'_>,
|
context: &CommandContext<'_>,
|
||||||
name: &str,
|
name: &str,
|
||||||
) -> Result<Vec<Arc<Player>>, CommandSyntaxError> {
|
) -> Result<Vec<Arc<Player>>, CommandSyntaxError> {
|
||||||
let players = Self::get_optional_players(context, name).await?;
|
let players = Self::get_optional_players(context, name)?;
|
||||||
if players.is_empty() {
|
if players.is_empty() {
|
||||||
Err(NO_PLAYERS_ERROR_TYPE.create_without_context())
|
Err(NO_PLAYERS_ERROR_TYPE.create_without_context())
|
||||||
} else {
|
} else {
|
||||||
@@ -215,13 +206,12 @@ impl EntityArgumentType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Tries to get any number of players from a parsed argument of the provided [`CommandContext`].
|
/// Tries to get any number of players from a parsed argument of the provided [`CommandContext`].
|
||||||
pub async fn get_optional_players(
|
pub fn get_optional_players(
|
||||||
context: &CommandContext<'_>,
|
context: &CommandContext<'_>,
|
||||||
name: &str,
|
name: &str,
|
||||||
) -> Result<Vec<Arc<Player>>, CommandSyntaxError> {
|
) -> Result<Vec<Arc<Player>>, CommandSyntaxError> {
|
||||||
context
|
context
|
||||||
.get_argument::<EntitySelector>(name)?
|
.get_argument::<EntitySelector>(name)?
|
||||||
.find_players(context.source.as_ref())
|
.find_players(context.source.as_ref())
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,7 +9,6 @@ use crate::entity::Entity;
|
|||||||
use pumpkin_data::translation;
|
use pumpkin_data::translation;
|
||||||
use pumpkin_util::math::vector3::Vector3;
|
use pumpkin_util::math::vector3::Vector3;
|
||||||
use pumpkin_util::text::TextComponent;
|
use pumpkin_util::text::TextComponent;
|
||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
pub const INVALID_ERROR_TYPE: CommandErrorType<1> = CommandErrorType::new(
|
pub const INVALID_ERROR_TYPE: CommandErrorType<1> = CommandErrorType::new(
|
||||||
translation::java::ARGUMENT_ANCHOR_INVALID,
|
translation::java::ARGUMENT_ANCHOR_INVALID,
|
||||||
@@ -37,12 +36,12 @@ impl ArgumentType for EntityAnchorArgumentType {
|
|||||||
JavaClientArgumentType::EntityAnchor
|
JavaClientArgumentType::EntityAnchor
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move { builder.filter_and_suggest(&["eyes", "feet"]).build() })
|
builder.filter_and_suggest(&["eyes", "feet"]).build()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn examples(&self) -> Vec<String> {
|
fn examples(&self) -> Vec<String> {
|
||||||
|
|||||||
@@ -62,11 +62,8 @@ pub struct EntitySelector {
|
|||||||
impl EntitySelector {
|
impl EntitySelector {
|
||||||
/// Returns an [`Err`] if a [`CommandSource`] does not have permission to use
|
/// Returns an [`Err`] if a [`CommandSource`] does not have permission to use
|
||||||
/// this entity selector.
|
/// this entity selector.
|
||||||
pub async fn check_permissions(
|
pub fn check_permissions(&self, source: &CommandSource) -> Result<(), CommandSyntaxError> {
|
||||||
&self,
|
if self.uses_selector_variable && !source.has_permission(ENTITY_SELECTOR_PERMISSION) {
|
||||||
source: &CommandSource,
|
|
||||||
) -> Result<(), CommandSyntaxError> {
|
|
||||||
if self.uses_selector_variable && !source.has_permission(ENTITY_SELECTOR_PERMISSION).await {
|
|
||||||
Err(SELECTORS_NOT_ALLOWED_ERROR_TYPE.create_without_context())
|
Err(SELECTORS_NOT_ALLOWED_ERROR_TYPE.create_without_context())
|
||||||
} else {
|
} else {
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -82,11 +79,11 @@ impl EntitySelector {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Tries to find a single entity represented by this selector.
|
/// Tries to find a single entity represented by this selector.
|
||||||
pub async fn find_single_entity(
|
pub fn find_single_entity(
|
||||||
&self,
|
&self,
|
||||||
source: &CommandSource,
|
source: &CommandSource,
|
||||||
) -> Result<Arc<dyn EntityBase>, CommandSyntaxError> {
|
) -> Result<Arc<dyn EntityBase>, CommandSyntaxError> {
|
||||||
let list = self.find_entities(source).await?;
|
let list = self.find_entities(source)?;
|
||||||
match list.as_slice() {
|
match list.as_slice() {
|
||||||
[] => Err(entity::NO_ENTITIES_ERROR_TYPE.create_without_context()),
|
[] => Err(entity::NO_ENTITIES_ERROR_TYPE.create_without_context()),
|
||||||
[entity] => Ok(entity.clone()),
|
[entity] => Ok(entity.clone()),
|
||||||
@@ -95,14 +92,13 @@ impl EntitySelector {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Tries to find any entities represented by this selector. If none are found, an empty `Vec` will still be returned.
|
/// Tries to find any entities represented by this selector. If none are found, an empty `Vec` will still be returned.
|
||||||
pub async fn find_entities(
|
pub fn find_entities(
|
||||||
&self,
|
&self,
|
||||||
source: &CommandSource,
|
source: &CommandSource,
|
||||||
) -> Result<Vec<Arc<dyn EntityBase>>, CommandSyntaxError> {
|
) -> Result<Vec<Arc<dyn EntityBase>>, CommandSyntaxError> {
|
||||||
self.check_permissions(source).await?;
|
self.check_permissions(source)?;
|
||||||
if !self.includes_entities {
|
if !self.includes_entities {
|
||||||
self.find_players(source)
|
self.find_players(source)
|
||||||
.await
|
|
||||||
.map(|v| v.into_iter().map(|p| p as Arc<dyn EntityBase>).collect())
|
.map(|v| v.into_iter().map(|p| p as Arc<dyn EntityBase>).collect())
|
||||||
} else if let Some(name) = self.player_name.as_ref() {
|
} else if let Some(name) = self.player_name.as_ref() {
|
||||||
// Try to get the player by name.
|
// Try to get the player by name.
|
||||||
@@ -160,11 +156,11 @@ impl EntitySelector {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Tries to find a single player represented by this selector.
|
/// Tries to find a single player represented by this selector.
|
||||||
pub async fn find_single_player(
|
pub fn find_single_player(
|
||||||
&self,
|
&self,
|
||||||
source: &CommandSource,
|
source: &CommandSource,
|
||||||
) -> Result<Arc<Player>, CommandSyntaxError> {
|
) -> Result<Arc<Player>, CommandSyntaxError> {
|
||||||
let mut list = self.find_players(source).await?;
|
let mut list = self.find_players(source)?;
|
||||||
if list.len() == 1 {
|
if list.len() == 1 {
|
||||||
list.pop()
|
list.pop()
|
||||||
.ok_or_else(|| entity::NO_PLAYERS_ERROR_TYPE.create_without_context())
|
.ok_or_else(|| entity::NO_PLAYERS_ERROR_TYPE.create_without_context())
|
||||||
@@ -174,11 +170,11 @@ impl EntitySelector {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Tries to find any players represented by this selector.
|
/// Tries to find any players represented by this selector.
|
||||||
pub async fn find_players(
|
pub fn find_players(
|
||||||
&self,
|
&self,
|
||||||
source: &CommandSource,
|
source: &CommandSource,
|
||||||
) -> Result<Vec<Arc<Player>>, CommandSyntaxError> {
|
) -> Result<Vec<Arc<Player>>, CommandSyntaxError> {
|
||||||
self.check_permissions(source).await?;
|
self.check_permissions(source)?;
|
||||||
if let Some(name) = self.player_name.as_ref() {
|
if let Some(name) = self.player_name.as_ref() {
|
||||||
// Try to get the player by name.
|
// Try to get the player by name.
|
||||||
let player = source
|
let player = source
|
||||||
@@ -529,7 +525,10 @@ impl EntitySelectorPredicate {
|
|||||||
Self::Team(expected_team, invert) => {
|
Self::Team(expected_team, invert) => {
|
||||||
let actual_name = entity_actual_name(entity);
|
let actual_name = entity_actual_name(entity);
|
||||||
let world = entity.get_entity().world.load();
|
let world = entity.get_entity().world.load();
|
||||||
let scoreboard = world.scoreboard.blocking_lock();
|
let scoreboard = world
|
||||||
|
.scoreboard
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
let has_team = scoreboard.get_teams().iter().any(|(name, team)| {
|
let has_team = scoreboard.get_teams().iter().any(|(name, team)| {
|
||||||
name == expected_team && team.players.contains(&actual_name)
|
name == expected_team && team.players.contains(&actual_name)
|
||||||
});
|
});
|
||||||
@@ -538,7 +537,10 @@ impl EntitySelectorPredicate {
|
|||||||
Self::Scores(scores_map) => {
|
Self::Scores(scores_map) => {
|
||||||
let actual_name = entity_actual_name(entity);
|
let actual_name = entity_actual_name(entity);
|
||||||
let world = entity.get_entity().world.load();
|
let world = entity.get_entity().world.load();
|
||||||
let scoreboard = world.scoreboard.blocking_lock();
|
let scoreboard = world
|
||||||
|
.scoreboard
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
let entity_scores = scoreboard.get_scores().get(&actual_name);
|
let entity_scores = scoreboard.get_scores().get(&actual_name);
|
||||||
for (objective, bounds) in scores_map {
|
for (objective, bounds) in scores_map {
|
||||||
let score_val = entity_scores
|
let score_val = entity_scores
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ use pumpkin_util::math::bounds::{DoubleBounds, FloatDegreeBounds, IntBounds};
|
|||||||
use pumpkin_util::math::vector2::Vector2;
|
use pumpkin_util::math::vector2::Vector2;
|
||||||
use pumpkin_util::math::vector3::Vector3;
|
use pumpkin_util::math::vector3::Vector3;
|
||||||
use pumpkin_util::text::TextComponent;
|
use pumpkin_util::text::TextComponent;
|
||||||
use std::pin::Pin;
|
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
pub const INVALID_NAME_OR_UUID_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
pub const INVALID_NAME_OR_UUID_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||||
@@ -593,31 +592,25 @@ impl EntitySelectorParserSuggestions {
|
|||||||
builder
|
builder
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn list_suggestions<'a>(
|
pub fn list_suggestions(
|
||||||
context: &'a CommandContext<'_>,
|
context: &CommandContext<'_>,
|
||||||
suggestions_builder: SuggestionsBuilder,
|
suggestions_builder: &SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move {
|
let mut reader = StringReader::new(suggestions_builder.input.clone());
|
||||||
let mut reader = StringReader::new(suggestions_builder.input.clone());
|
reader.set_cursor(suggestions_builder.start);
|
||||||
reader.set_cursor(suggestions_builder.start);
|
let mut parser = EntitySelectorParser::new(
|
||||||
let mut parser = EntitySelectorParser::new(
|
&mut reader,
|
||||||
&mut reader,
|
context.source.has_permission(ENTITY_SELECTOR_PERMISSION),
|
||||||
context
|
);
|
||||||
.source
|
|
||||||
.has_permission(ENTITY_SELECTOR_PERMISSION)
|
|
||||||
.await,
|
|
||||||
);
|
|
||||||
|
|
||||||
let _ = parser.parse();
|
let _ = parser.parse();
|
||||||
|
|
||||||
parser.fill_suggestions(&suggestions_builder, |mut suggestions| {
|
parser.fill_suggestions(suggestions_builder, |mut suggestions| {
|
||||||
for player in context.server().get_all_players() {
|
for player in context.server().get_all_players() {
|
||||||
suggestions =
|
suggestions = suggestions.filter_and_suggest_one(player.gameprofile.name.clone());
|
||||||
suggestions.filter_and_suggest_one(player.gameprofile.name.clone());
|
}
|
||||||
}
|
// ONLY FOR EntityArgumentType: This is server-side, so no other entity will show up.
|
||||||
// ONLY FOR EntityArgumentType: This is server-side, so no other entity will show up.
|
suggestions
|
||||||
suggestions
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ use crate::net::{GameProfile, offline_uuid};
|
|||||||
use crate::server::Server;
|
use crate::server::Server;
|
||||||
use arc_swap::ArcSwap;
|
use arc_swap::ArcSwap;
|
||||||
use pumpkin_data::translation;
|
use pumpkin_data::translation;
|
||||||
use std::pin::Pin;
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
@@ -49,24 +48,26 @@ impl GameProfileResult {
|
|||||||
/// - `server.data.whitelist_config`
|
/// - `server.data.whitelist_config`
|
||||||
///
|
///
|
||||||
/// Instead, call this method *before* using `write()`/`read()` on a lock.
|
/// Instead, call this method *before* using `write()`/`read()` on a lock.
|
||||||
pub async fn resolve(
|
pub fn resolve(&self, source: &CommandSource) -> Result<Vec<GameProfile>, CommandSyntaxError> {
|
||||||
&self,
|
|
||||||
source: &CommandSource,
|
|
||||||
) -> Result<Vec<GameProfile>, CommandSyntaxError> {
|
|
||||||
let players = match self {
|
let players = match self {
|
||||||
Self::Selector(selector) => selector.find_players(source).await,
|
Self::Selector(selector) => selector.find_players(source),
|
||||||
Self::Name(name) => {
|
Self::Name(name) => {
|
||||||
let server = source.server();
|
let server = source.server();
|
||||||
if let Some(player) = server.get_player_by_name(name) {
|
if let Some(player) = server.get_player_by_name(name) {
|
||||||
return Ok(vec![player.gameprofile.clone()]);
|
return Ok(vec![player.gameprofile.clone()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
let cached_entry = server.data.user_cache.write().await.get_by_name(name);
|
let cached_entry = server
|
||||||
|
.data
|
||||||
|
.user_cache
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.get_by_name(name);
|
||||||
if let Some(entry) = cached_entry {
|
if let Some(entry) = cached_entry {
|
||||||
return Ok(vec![Self::profile_from_uuid_name(entry.uuid, entry.name)]);
|
return Ok(vec![Self::profile_from_uuid_name(entry.uuid, entry.name)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(profile) = Self::resolve_known_profile_by_name(server, name).await {
|
if let Some(profile) = Self::resolve_known_profile_by_name(server, name) {
|
||||||
return Ok(vec![profile]);
|
return Ok(vec![profile]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,7 +81,7 @@ impl GameProfileResult {
|
|||||||
.data
|
.data
|
||||||
.user_cache
|
.user_cache
|
||||||
.write()
|
.write()
|
||||||
.await
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
.upsert(uuid, resolved_name.clone());
|
.upsert(uuid, resolved_name.clone());
|
||||||
Ok(vec![Self::profile_from_uuid_name(uuid, resolved_name)])
|
Ok(vec![Self::profile_from_uuid_name(uuid, resolved_name)])
|
||||||
}
|
}
|
||||||
@@ -92,7 +93,7 @@ impl GameProfileResult {
|
|||||||
.data
|
.data
|
||||||
.user_cache
|
.user_cache
|
||||||
.write()
|
.write()
|
||||||
.await
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
.upsert(profile.id, profile.name.clone());
|
.upsert(profile.id, profile.name.clone());
|
||||||
return Ok(vec![profile]);
|
return Ok(vec![profile]);
|
||||||
}
|
}
|
||||||
@@ -106,12 +107,17 @@ impl GameProfileResult {
|
|||||||
return Ok(vec![player.gameprofile.clone()]);
|
return Ok(vec![player.gameprofile.clone()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
let cached_entry = server.data.user_cache.write().await.get_by_uuid(*uuid);
|
let cached_entry = server
|
||||||
|
.data
|
||||||
|
.user_cache
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.get_by_uuid(*uuid);
|
||||||
if let Some(entry) = cached_entry {
|
if let Some(entry) = cached_entry {
|
||||||
return Ok(vec![Self::profile_from_uuid_name(entry.uuid, entry.name)]);
|
return Ok(vec![Self::profile_from_uuid_name(entry.uuid, entry.name)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(profile) = Self::resolve_known_profile_by_uuid(server, *uuid).await {
|
if let Some(profile) = Self::resolve_known_profile_by_uuid(server, *uuid) {
|
||||||
return Ok(vec![profile]);
|
return Ok(vec![profile]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,13 +128,21 @@ impl GameProfileResult {
|
|||||||
Ok(players.iter().map(|p| &p.gameprofile).cloned().collect())
|
Ok(players.iter().map(|p| &p.gameprofile).cloned().collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn resolve_known_profile_by_name(server: &Server, name: &str) -> Option<GameProfile> {
|
fn resolve_known_profile_by_name(server: &Server, name: &str) -> Option<GameProfile> {
|
||||||
let ops = server.data.operator_config.read().await;
|
let ops = server
|
||||||
|
.data
|
||||||
|
.operator_config
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
if let Some(op) = ops.ops.iter().find(|op| op.name.eq_ignore_ascii_case(name)) {
|
if let Some(op) = ops.ops.iter().find(|op| op.name.eq_ignore_ascii_case(name)) {
|
||||||
return Some(Self::profile_from_uuid_name(op.uuid, op.name.clone()));
|
return Some(Self::profile_from_uuid_name(op.uuid, op.name.clone()));
|
||||||
}
|
}
|
||||||
|
|
||||||
let banned_players = server.data.banned_player_list.read().await;
|
let banned_players = server
|
||||||
|
.data
|
||||||
|
.banned_player_list
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
if let Some(entry) = banned_players
|
if let Some(entry) = banned_players
|
||||||
.banned_players
|
.banned_players
|
||||||
.iter()
|
.iter()
|
||||||
@@ -137,7 +151,11 @@ impl GameProfileResult {
|
|||||||
return Some(Self::profile_from_uuid_name(entry.uuid, entry.name.clone()));
|
return Some(Self::profile_from_uuid_name(entry.uuid, entry.name.clone()));
|
||||||
}
|
}
|
||||||
|
|
||||||
let whitelist = server.data.whitelist_config.read().await;
|
let whitelist = server
|
||||||
|
.data
|
||||||
|
.whitelist_config
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
if let Some(entry) = whitelist
|
if let Some(entry) = whitelist
|
||||||
.whitelist
|
.whitelist
|
||||||
.iter()
|
.iter()
|
||||||
@@ -149,13 +167,21 @@ impl GameProfileResult {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn resolve_known_profile_by_uuid(server: &Server, uuid: Uuid) -> Option<GameProfile> {
|
fn resolve_known_profile_by_uuid(server: &Server, uuid: Uuid) -> Option<GameProfile> {
|
||||||
let ops = server.data.operator_config.read().await;
|
let ops = server
|
||||||
|
.data
|
||||||
|
.operator_config
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
if let Some(op) = ops.ops.iter().find(|op| op.uuid == uuid) {
|
if let Some(op) = ops.ops.iter().find(|op| op.uuid == uuid) {
|
||||||
return Some(Self::profile_from_uuid_name(op.uuid, op.name.clone()));
|
return Some(Self::profile_from_uuid_name(op.uuid, op.name.clone()));
|
||||||
}
|
}
|
||||||
|
|
||||||
let banned_players = server.data.banned_player_list.read().await;
|
let banned_players = server
|
||||||
|
.data
|
||||||
|
.banned_player_list
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
if let Some(entry) = banned_players
|
if let Some(entry) = banned_players
|
||||||
.banned_players
|
.banned_players
|
||||||
.iter()
|
.iter()
|
||||||
@@ -164,7 +190,11 @@ impl GameProfileResult {
|
|||||||
return Some(Self::profile_from_uuid_name(entry.uuid, entry.name.clone()));
|
return Some(Self::profile_from_uuid_name(entry.uuid, entry.name.clone()));
|
||||||
}
|
}
|
||||||
|
|
||||||
let whitelist = server.data.whitelist_config.read().await;
|
let whitelist = server
|
||||||
|
.data
|
||||||
|
.whitelist_config
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
if let Some(entry) = whitelist.whitelist.iter().find(|entry| entry.uuid == uuid) {
|
if let Some(entry) = whitelist.whitelist.iter().find(|entry| entry.uuid == uuid) {
|
||||||
return Some(Self::profile_from_uuid_name(entry.uuid, entry.name.clone()));
|
return Some(Self::profile_from_uuid_name(entry.uuid, entry.name.clone()));
|
||||||
}
|
}
|
||||||
@@ -202,12 +232,12 @@ impl ArgumentType for GameProfileArgumentType {
|
|||||||
JavaClientArgumentType::GameProfile
|
JavaClientArgumentType::GameProfile
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
EntitySelectorParserSuggestions::list_suggestions(context, builder)
|
EntitySelectorParserSuggestions::list_suggestions(context, &builder)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn examples(&self) -> Vec<String> {
|
fn examples(&self) -> Vec<String> {
|
||||||
@@ -255,13 +285,12 @@ impl GameProfileArgumentType {
|
|||||||
/// - `server.data.whitelist_config`
|
/// - `server.data.whitelist_config`
|
||||||
///
|
///
|
||||||
/// Instead, call this function *before* using `write()`/`read()` on a lock.
|
/// Instead, call this function *before* using `write()`/`read()` on a lock.
|
||||||
pub async fn get(
|
pub fn get(
|
||||||
context: &CommandContext<'_>,
|
context: &CommandContext<'_>,
|
||||||
name: &str,
|
name: &str,
|
||||||
) -> Result<Vec<GameProfile>, CommandSyntaxError> {
|
) -> Result<Vec<GameProfile>, CommandSyntaxError> {
|
||||||
context
|
context
|
||||||
.get_argument::<GameProfileResult>(name)?
|
.get_argument::<GameProfileResult>(name)?
|
||||||
.resolve(context.source.as_ref())
|
.resolve(context.source.as_ref())
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,6 @@ use crate::command::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
|||||||
use pumpkin_data::translation;
|
use pumpkin_data::translation;
|
||||||
use pumpkin_util::GameMode;
|
use pumpkin_util::GameMode;
|
||||||
use pumpkin_util::text::TextComponent;
|
use pumpkin_util::text::TextComponent;
|
||||||
use std::pin::Pin;
|
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
pub const INVALID_ERROR_TYPE: CommandErrorType<1> = CommandErrorType::new(
|
pub const INVALID_ERROR_TYPE: CommandErrorType<1> = CommandErrorType::new(
|
||||||
@@ -30,17 +29,15 @@ impl ArgumentType for GameModeArgumentType {
|
|||||||
JavaClientArgumentType::Gamemode
|
JavaClientArgumentType::Gamemode
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
mut builder: SuggestionsBuilder,
|
mut builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move {
|
for gamemode in GameMode::VALUES {
|
||||||
for gamemode in GameMode::VALUES {
|
builder = builder.filter_and_suggest_one(gamemode.name());
|
||||||
builder = builder.filter_and_suggest_one(gamemode.name());
|
}
|
||||||
}
|
builder.build()
|
||||||
builder.build()
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn examples(&self) -> Vec<String> {
|
fn examples(&self) -> Vec<String> {
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ use crate::command::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
|||||||
use pumpkin_data::translation::java::ARGUMENT_HEXCOLOR_INVALID;
|
use pumpkin_data::translation::java::ARGUMENT_HEXCOLOR_INVALID;
|
||||||
use pumpkin_util::text::TextComponent;
|
use pumpkin_util::text::TextComponent;
|
||||||
use pumpkin_util::text::color::RGBColor;
|
use pumpkin_util::text::color::RGBColor;
|
||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
pub const INVALID_HEX_ERROR_TYPE: CommandErrorType<1> =
|
pub const INVALID_HEX_ERROR_TYPE: CommandErrorType<1> =
|
||||||
CommandErrorType::new(ARGUMENT_HEXCOLOR_INVALID, ARGUMENT_HEXCOLOR_INVALID);
|
CommandErrorType::new(ARGUMENT_HEXCOLOR_INVALID, ARGUMENT_HEXCOLOR_INVALID);
|
||||||
@@ -38,12 +37,12 @@ impl ArgumentType for HexColorArgumentType {
|
|||||||
JavaClientArgumentType::HexColor
|
JavaClientArgumentType::HexColor
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move { builder.filter_and_suggest(&["F00", "FF0000"]).build() })
|
builder.filter_and_suggest(&["F00", "FF0000"]).build()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn examples(&self) -> Vec<String> {
|
fn examples(&self) -> Vec<String> {
|
||||||
|
|||||||
@@ -26,12 +26,12 @@ impl ArgumentType for NbtTagArgumentType {
|
|||||||
JavaClientArgumentType::NbtTag
|
JavaClientArgumentType::NbtTag
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> std::pin::Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move { SnbtParser::parse_for_suggestions(builder) })
|
SnbtParser::parse_for_suggestions(builder)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn examples(&self) -> Vec<String> {
|
fn examples(&self) -> Vec<String> {
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ use crate::command::{
|
|||||||
string_reader::StringReader,
|
string_reader::StringReader,
|
||||||
suggestion::suggestions::{Suggestions, SuggestionsBuilder},
|
suggestion::suggestions::{Suggestions, SuggestionsBuilder},
|
||||||
};
|
};
|
||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
/// Represents an argument type parsing a scoreboard objective name.
|
/// Represents an argument type parsing a scoreboard objective name.
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||||
@@ -23,18 +22,20 @@ impl ArgumentType for ObjectiveArgumentType {
|
|||||||
JavaClientArgumentType::Objective
|
JavaClientArgumentType::Objective
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
mut builder: SuggestionsBuilder,
|
mut builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move {
|
let scoreboard = context
|
||||||
let scoreboard = context.world().scoreboard.lock().await;
|
.world()
|
||||||
for objective_name in scoreboard.get_objectives().keys() {
|
.scoreboard
|
||||||
builder = builder.filter_and_suggest_one(objective_name.as_str());
|
.lock()
|
||||||
}
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
builder.build()
|
for objective_name in scoreboard.get_objectives().keys() {
|
||||||
})
|
builder = builder.filter_and_suggest_one(objective_name.as_str());
|
||||||
|
}
|
||||||
|
builder.build()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn examples(&self) -> Vec<String> {
|
fn examples(&self) -> Vec<String> {
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
use pumpkin_protocol::java::client::play::SuggestionProviders;
|
use pumpkin_protocol::java::client::play::SuggestionProviders;
|
||||||
use pumpkin_util::identifier::Identifier;
|
use pumpkin_util::identifier::Identifier;
|
||||||
|
|
||||||
@@ -19,17 +17,15 @@ impl ArgumentType for PlacedFeatureNameArgumentType {
|
|||||||
Identifier::from_reader(reader)
|
Identifier::from_reader(reader)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
let names = pumpkin_world::generation::feature::placed_features::all_placed_feature_names();
|
let names = pumpkin_world::generation::feature::placed_features::all_placed_feature_names();
|
||||||
Box::pin(async move {
|
builder
|
||||||
builder
|
.filter_and_suggest_iter(names.iter().copied())
|
||||||
.filter_and_suggest_iter(names.iter().copied())
|
.build()
|
||||||
.build()
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
use crate::command::argument_types::FromStringReader;
|
use crate::command::argument_types::FromStringReader;
|
||||||
use crate::command::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
use crate::command::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||||
use crate::command::context::command_context::CommandContext;
|
use crate::command::context::command_context::CommandContext;
|
||||||
@@ -18,17 +16,15 @@ impl ArgumentType for PoolNameArgumentType {
|
|||||||
Identifier::from_reader(reader)
|
Identifier::from_reader(reader)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
let names = pumpkin_world::generation::structure::template::all_pool_names();
|
let names = pumpkin_world::generation::structure::template::all_pool_names();
|
||||||
Box::pin(async move {
|
builder
|
||||||
builder
|
.filter_and_suggest_iter(names.iter().map(|n| format!("minecraft:{n}")))
|
||||||
.filter_and_suggest_iter(names.iter().map(|n| format!("minecraft:{n}")))
|
.build()
|
||||||
.build()
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ use pumpkin_util::identifier::Identifier;
|
|||||||
use pumpkin_util::text::TextComponent;
|
use pumpkin_util::text::TextComponent;
|
||||||
use std::any::Any;
|
use std::any::Any;
|
||||||
use std::iter::Iterator;
|
use std::iter::Iterator;
|
||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
pub static ENTITY_TYPE_REGISTRY: &Identifier = &Identifier::vanilla_static("entity_type");
|
pub static ENTITY_TYPE_REGISTRY: &Identifier = &Identifier::vanilla_static("entity_type");
|
||||||
static ERROR_UNKNOWN_RESOURCE: CommandErrorType<2> = CommandErrorType::new(
|
static ERROR_UNKNOWN_RESOURCE: CommandErrorType<2> = CommandErrorType::new(
|
||||||
@@ -59,18 +58,16 @@ impl ArgumentType for ResourceArgument {
|
|||||||
&self,
|
&self,
|
||||||
_context: &CommandContext,
|
_context: &CommandContext,
|
||||||
suggestions_builder: SuggestionsBuilder,
|
suggestions_builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send>> {
|
) -> Suggestions {
|
||||||
if self.0 == ENTITY_TYPE_REGISTRY {
|
if self.0 == ENTITY_TYPE_REGISTRY {
|
||||||
Box::pin(async move {
|
let entity_types = EntityType::ALL
|
||||||
let entity_types = EntityType::ALL
|
.iter()
|
||||||
.iter()
|
.map(|entity_type| format!("minecraft:{}", entity_type.resource_name));
|
||||||
.map(|entity_type| format!("minecraft:{}", entity_type.resource_name));
|
suggestions_builder
|
||||||
suggestions_builder
|
.filter_and_suggest_iter(entity_types)
|
||||||
.filter_and_suggest_iter(entity_types)
|
.build()
|
||||||
.build()
|
|
||||||
})
|
|
||||||
} else {
|
} else {
|
||||||
Box::pin(async move { Suggestions::empty() })
|
Suggestions::empty()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ use pumpkin_data::{Advancement, translation};
|
|||||||
use pumpkin_util::identifier::Identifier;
|
use pumpkin_util::identifier::Identifier;
|
||||||
use pumpkin_util::resource::ResourceKey;
|
use pumpkin_util::resource::ResourceKey;
|
||||||
use pumpkin_util::text::TextComponent;
|
use pumpkin_util::text::TextComponent;
|
||||||
use std::pin::Pin;
|
|
||||||
use std::string::ToString;
|
use std::string::ToString;
|
||||||
|
|
||||||
pub static ADVANCEMENT_REGISTRY: &Identifier = &Identifier::vanilla_static("advancement");
|
pub static ADVANCEMENT_REGISTRY: &Identifier = &Identifier::vanilla_static("advancement");
|
||||||
@@ -55,23 +54,19 @@ impl ArgumentType for ResourceKeyArgument {
|
|||||||
&self,
|
&self,
|
||||||
context: &CommandContext,
|
context: &CommandContext,
|
||||||
suggestions_builder: SuggestionsBuilder,
|
suggestions_builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send>> {
|
) -> Suggestions {
|
||||||
if self.0 == ADVANCEMENT_REGISTRY {
|
if self.0 == ADVANCEMENT_REGISTRY {
|
||||||
let advancements = context.server().advancement_manager.get_advancements();
|
let advancements = context.server().advancement_manager.get_advancements();
|
||||||
Box::pin(async move {
|
suggestions_builder
|
||||||
suggestions_builder
|
.filter_and_suggest_iter(advancements.iter().map(ToString::to_string))
|
||||||
.filter_and_suggest_iter(advancements.iter().map(ToString::to_string))
|
.build()
|
||||||
.build()
|
|
||||||
})
|
|
||||||
} else if self.0 == BIOME_REGISTRY {
|
} else if self.0 == BIOME_REGISTRY {
|
||||||
Box::pin(async move {
|
let biomes = pumpkin_data::biome::Biome::ALL
|
||||||
let biomes = pumpkin_data::biome::Biome::ALL
|
.iter()
|
||||||
.iter()
|
.map(|biome| format!("minecraft:{}", biome.registry_id));
|
||||||
.map(|biome| format!("minecraft:{}", biome.registry_id));
|
suggestions_builder.filter_and_suggest_iter(biomes).build()
|
||||||
suggestions_builder.filter_and_suggest_iter(biomes).build()
|
|
||||||
})
|
|
||||||
} else {
|
} else {
|
||||||
Box::pin(async move { Suggestions::empty() })
|
Suggestions::empty()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
use std::collections::BTreeSet;
|
use std::collections::BTreeSet;
|
||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
use pumpkin_data::structures::StructureSet;
|
use pumpkin_data::structures::StructureSet;
|
||||||
use pumpkin_data::tag::{self, RegistryKey};
|
use pumpkin_data::tag::{self, RegistryKey};
|
||||||
@@ -121,12 +120,12 @@ impl ArgumentType for ResourceOrTagKeyArgument {
|
|||||||
ResourceOrTag::from_string_reader(reader)
|
ResourceOrTag::from_string_reader(reader)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move { suggest_for_registry(&self.0, builder) })
|
suggest_for_registry(&self.0, builder)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||||
@@ -190,12 +189,12 @@ impl ArgumentType for ResourceOrTagArgument {
|
|||||||
Ok(value)
|
Ok(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move { suggest_for_registry(&self.0, builder) })
|
suggest_for_registry(&self.0, builder)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ use pumpkin_data::slot_ranges::{
|
|||||||
};
|
};
|
||||||
use pumpkin_data::translation;
|
use pumpkin_data::translation;
|
||||||
use pumpkin_util::text::TextComponent;
|
use pumpkin_util::text::TextComponent;
|
||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
pub const UNKNOWN_SLOT_ERROR_TYPE: CommandErrorType<1> = CommandErrorType::new(
|
pub const UNKNOWN_SLOT_ERROR_TYPE: CommandErrorType<1> = CommandErrorType::new(
|
||||||
translation::java::SLOT_UNKNOWN,
|
translation::java::SLOT_UNKNOWN,
|
||||||
@@ -45,16 +44,14 @@ impl ArgumentType for SlotArgumentType {
|
|||||||
JavaClientArgumentType::ItemSlot
|
JavaClientArgumentType::ItemSlot
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move {
|
builder
|
||||||
builder
|
.filter_and_suggest(&SLOT_RANGE_SINGLE_SLOT_NAMES)
|
||||||
.filter_and_suggest(&SLOT_RANGE_SINGLE_SLOT_NAMES)
|
.build()
|
||||||
.build()
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn examples(&self) -> Vec<String> {
|
fn examples(&self) -> Vec<String> {
|
||||||
@@ -84,12 +81,12 @@ impl ArgumentType for SlotsArgumentType {
|
|||||||
JavaClientArgumentType::ItemSlots
|
JavaClientArgumentType::ItemSlots
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move { builder.filter_and_suggest(&SLOT_RANGE_ALL_NAMES).build() })
|
builder.filter_and_suggest(&SLOT_RANGE_ALL_NAMES).build()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn examples(&self) -> Vec<String> {
|
fn examples(&self) -> Vec<String> {
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
use crate::command::argument_types::FromStringReader;
|
use crate::command::argument_types::FromStringReader;
|
||||||
use crate::command::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
use crate::command::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||||
use crate::command::context::command_context::CommandContext;
|
use crate::command::context::command_context::CommandContext;
|
||||||
@@ -18,17 +16,15 @@ impl ArgumentType for StructureNameArgumentType {
|
|||||||
Identifier::from_reader(reader)
|
Identifier::from_reader(reader)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
let names = pumpkin_world::generation::structure::template::all_structure_names();
|
let names = pumpkin_world::generation::structure::template::all_structure_names();
|
||||||
Box::pin(async move {
|
builder
|
||||||
builder
|
.filter_and_suggest_iter(names.iter().copied())
|
||||||
.filter_and_suggest_iter(names.iter().copied())
|
.build()
|
||||||
.build()
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ use crate::command::{
|
|||||||
string_reader::StringReader,
|
string_reader::StringReader,
|
||||||
suggestion::suggestions::{Suggestions, SuggestionsBuilder},
|
suggestion::suggestions::{Suggestions, SuggestionsBuilder},
|
||||||
};
|
};
|
||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
/// Represents an argument type parsing a team name.
|
/// Represents an argument type parsing a team name.
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||||
@@ -23,18 +22,20 @@ impl ArgumentType for TeamArgumentType {
|
|||||||
JavaClientArgumentType::Team
|
JavaClientArgumentType::Team
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
mut builder: SuggestionsBuilder,
|
mut builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move {
|
let scoreboard = context
|
||||||
let scoreboard = context.world().scoreboard.lock().await;
|
.world()
|
||||||
for team_name in scoreboard.get_teams().keys() {
|
.scoreboard
|
||||||
builder = builder.filter_and_suggest_one(team_name.as_str());
|
.lock()
|
||||||
}
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
builder.build()
|
for team_name in scoreboard.get_teams().keys() {
|
||||||
})
|
builder = builder.filter_and_suggest_one(team_name.as_str());
|
||||||
|
}
|
||||||
|
builder.build()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn examples(&self) -> Vec<String> {
|
fn examples(&self) -> Vec<String> {
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ use crate::command::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
|||||||
use pumpkin_data::translation::java::ARGUMENT_COLOR_INVALID;
|
use pumpkin_data::translation::java::ARGUMENT_COLOR_INVALID;
|
||||||
use pumpkin_util::text::TextComponent;
|
use pumpkin_util::text::TextComponent;
|
||||||
use pumpkin_util::text::color::NamedColor;
|
use pumpkin_util::text::color::NamedColor;
|
||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
pub const INVALID_VALUE_ERROR_TYPE: CommandErrorType<1> =
|
pub const INVALID_VALUE_ERROR_TYPE: CommandErrorType<1> =
|
||||||
CommandErrorType::new(ARGUMENT_COLOR_INVALID, ARGUMENT_COLOR_INVALID);
|
CommandErrorType::new(ARGUMENT_COLOR_INVALID, ARGUMENT_COLOR_INVALID);
|
||||||
@@ -30,33 +29,31 @@ impl ArgumentType for TeamColorArgumentType {
|
|||||||
JavaClientArgumentType::Color
|
JavaClientArgumentType::Color
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move {
|
builder
|
||||||
builder
|
.filter_and_suggest(&[
|
||||||
.filter_and_suggest(&[
|
"black",
|
||||||
"black",
|
"dark_blue",
|
||||||
"dark_blue",
|
"dark_green",
|
||||||
"dark_green",
|
"dark_aqua",
|
||||||
"dark_aqua",
|
"dark_red",
|
||||||
"dark_red",
|
"dark_purple",
|
||||||
"dark_purple",
|
"gold",
|
||||||
"gold",
|
"gray",
|
||||||
"gray",
|
"dark_gray",
|
||||||
"dark_gray",
|
"blue",
|
||||||
"blue",
|
"green",
|
||||||
"green",
|
"aqua",
|
||||||
"aqua",
|
"red",
|
||||||
"red",
|
"light_purple",
|
||||||
"light_purple",
|
"yellow",
|
||||||
"yellow",
|
"white",
|
||||||
"white",
|
])
|
||||||
])
|
.build()
|
||||||
.build()
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn examples(&self) -> Vec<String> {
|
fn examples(&self) -> Vec<String> {
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
use crate::command::argument_types::FromStringReader;
|
use crate::command::argument_types::FromStringReader;
|
||||||
use crate::command::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
use crate::command::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||||
use crate::command::context::command_context::CommandContext;
|
use crate::command::context::command_context::CommandContext;
|
||||||
@@ -19,17 +17,15 @@ impl ArgumentType for TemplateNameArgumentType {
|
|||||||
Ok(identifier.path().to_string())
|
Ok(identifier.path().to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
let names = pumpkin_world::generation::structure::template::all_template_names();
|
let names = pumpkin_world::generation::structure::template::all_template_names();
|
||||||
Box::pin(async move {
|
builder
|
||||||
builder
|
.filter_and_suggest_iter(names.iter().map(|n| format!("minecraft:{n}")))
|
||||||
.filter_and_suggest_iter(names.iter().map(|n| format!("minecraft:{n}")))
|
.build()
|
||||||
.build()
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ use crate::command::string_reader::StringReader;
|
|||||||
use crate::command::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
use crate::command::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||||
use pumpkin_data::translation;
|
use pumpkin_data::translation;
|
||||||
use pumpkin_util::text::TextComponent;
|
use pumpkin_util::text::TextComponent;
|
||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
pub const INVALID_UNIT_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
pub const INVALID_UNIT_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||||
translation::java::ARGUMENT_TIME_INVALID_UNIT,
|
translation::java::ARGUMENT_TIME_INVALID_UNIT,
|
||||||
@@ -73,21 +72,19 @@ impl ArgumentType for TimeArgumentType {
|
|||||||
JavaClientArgumentType::Time { min: self.min }
|
JavaClientArgumentType::Time { min: self.min }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_suggestions<'a>(
|
fn list_suggestions(
|
||||||
&'a self,
|
&self,
|
||||||
_context: &'a CommandContext,
|
_context: &CommandContext,
|
||||||
suggestions_builder: SuggestionsBuilder,
|
suggestions_builder: SuggestionsBuilder,
|
||||||
) -> Pin<Box<dyn Future<Output = Suggestions> + Send + 'a>> {
|
) -> Suggestions {
|
||||||
Box::pin(async move {
|
let mut reader = StringReader::new(suggestions_builder.remaining());
|
||||||
let mut reader = StringReader::new(suggestions_builder.remaining());
|
if reader.read_float().is_err() {
|
||||||
if reader.read_float().is_err() {
|
suggestions_builder.build()
|
||||||
suggestions_builder.build()
|
} else {
|
||||||
} else {
|
suggestions_builder
|
||||||
suggestions_builder
|
.filter_and_suggest(&["t", "s", "d"])
|
||||||
.filter_and_suggest(&["t", "s", "d"])
|
.build()
|
||||||
.build()
|
}
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn examples(&self) -> Vec<String> {
|
fn examples(&self) -> Vec<String> {
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ use pumpkin_protocol::bedrock::client::available_commands::{
|
|||||||
use pumpkin_protocol::java::client::play::SuggestionProviders;
|
use pumpkin_protocol::java::client::play::SuggestionProviders;
|
||||||
|
|
||||||
#[expect(clippy::too_many_lines)]
|
#[expect(clippy::too_many_lines)]
|
||||||
pub async fn send_c_commands_packet(
|
pub fn send_c_commands_packet(
|
||||||
player: &Arc<Player>,
|
player: &Arc<Player>,
|
||||||
server: &Server,
|
server: &Server,
|
||||||
dispatcher: &CommandDispatcher,
|
dispatcher: &CommandDispatcher,
|
||||||
@@ -50,7 +50,7 @@ pub async fn send_c_commands_packet(
|
|||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
if !cmd_src.has_permission(server, permission.as_str()).await {
|
if !cmd_src.has_permission(server, permission.as_str()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,7 +208,7 @@ pub async fn send_c_commands_packet(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let packet = CCommands::new(proto_nodes.into(), VarInt(root_node_index as i32));
|
let packet = CCommands::new(proto_nodes.into(), VarInt(root_node_index as i32));
|
||||||
player.send_client_packet(&packet).await;
|
player.try_send_client_packet(&packet);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn resolve_node_id(node_id: NodeId, node_id_offset: usize, root_node_index: usize) -> usize {
|
fn resolve_node_id(node_id: NodeId, node_id_offset: usize, root_node_index: usize) -> usize {
|
||||||
@@ -319,7 +319,7 @@ struct BuilderContext<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[expect(clippy::too_many_lines)]
|
#[expect(clippy::too_many_lines)]
|
||||||
pub async fn send_bedrock_commands_packet(
|
pub fn send_bedrock_commands_packet(
|
||||||
player: &Arc<Player>,
|
player: &Arc<Player>,
|
||||||
server: &Server,
|
server: &Server,
|
||||||
dispatcher: &CommandDispatcher,
|
dispatcher: &CommandDispatcher,
|
||||||
@@ -348,7 +348,7 @@ pub async fn send_bedrock_commands_packet(
|
|||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
if !cmd_src.has_permission(server, permission.as_str()).await {
|
if !cmd_src.has_permission(server, permission.as_str()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -441,8 +441,10 @@ pub async fn send_bedrock_commands_packet(
|
|||||||
constraints: Vec::new(),
|
constraints: Vec::new(),
|
||||||
};
|
};
|
||||||
|
|
||||||
if let crate::net::ClientPlatform::Bedrock(bedrock_client) = player.client.as_ref() {
|
if let crate::net::ClientPlatform::Bedrock(bedrock_client) = player.client.as_ref()
|
||||||
bedrock_client.send_packet(&packet).await;
|
&& let Ok(data) = bedrock_client.serialize_packet(&packet)
|
||||||
|
{
|
||||||
|
bedrock_client.try_enqueue_packet(data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ use crate::command::suggestion::suggestions::SuggestionsBuilder;
|
|||||||
use crate::entity::EntityBase;
|
use crate::entity::EntityBase;
|
||||||
use crate::entity::player::Player;
|
use crate::entity::player::Player;
|
||||||
use crate::entity::player::advancement::PlayerAdvancement;
|
use crate::entity::player::advancement::PlayerAdvancement;
|
||||||
use futures::future::join_all;
|
|
||||||
use pumpkin_data::advancement_data::AdvancementNode;
|
use pumpkin_data::advancement_data::AdvancementNode;
|
||||||
use pumpkin_data::{ADVANCEMENT_TREE, Advancement, translation};
|
use pumpkin_data::{ADVANCEMENT_TREE, Advancement, translation};
|
||||||
use pumpkin_util::PermissionLvl;
|
use pumpkin_util::PermissionLvl;
|
||||||
@@ -141,13 +140,13 @@ impl Action {
|
|||||||
///
|
///
|
||||||
/// Returns the number of advancements successfully modified. An advancement is counted as
|
/// Returns the number of advancements successfully modified. An advancement is counted as
|
||||||
/// successful if [`perform_single_inner`] returns `true`
|
/// successful if [`perform_single_inner`] returns `true`
|
||||||
async fn perform(
|
fn perform(
|
||||||
&self,
|
self,
|
||||||
player: &Arc<Player>,
|
player: &Arc<Player>,
|
||||||
advancements: &[&'static Advancement],
|
advancements: &[&'static Advancement],
|
||||||
show_advancement: bool,
|
show_advancement: bool,
|
||||||
) -> i32 {
|
) -> i32 {
|
||||||
let mut guard = player.advancements.lock().await;
|
let mut guard = player.advancements.blocking_lock();
|
||||||
if !show_advancement {
|
if !show_advancement {
|
||||||
guard.flush_dirty(player, true);
|
guard.flush_dirty(player, true);
|
||||||
}
|
}
|
||||||
@@ -161,13 +160,13 @@ impl Action {
|
|||||||
count
|
count
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn perform_criterion(
|
fn perform_criterion(
|
||||||
&self,
|
self,
|
||||||
player: &Arc<Player>,
|
player: &Arc<Player>,
|
||||||
advancement: &'static Advancement,
|
advancement: &'static Advancement,
|
||||||
criterion: &str,
|
criterion: &str,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
let mut guard = player.advancements.lock().await;
|
let mut guard = player.advancements.blocking_lock();
|
||||||
match self {
|
match self {
|
||||||
Self::Grant => guard.award(advancement, criterion),
|
Self::Grant => guard.award(advancement, criterion),
|
||||||
Self::Revoke => guard.revoke(advancement, criterion),
|
Self::Revoke => guard.revoke(advancement, criterion),
|
||||||
@@ -261,41 +260,41 @@ fn add_children(parent: &AdvancementNode, output: &mut Vec<&Advancement>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
async fn perform_and_show(
|
fn perform_and_show(
|
||||||
context: Arc<CommandSource>,
|
context: &CommandSource,
|
||||||
players: &[Arc<Player>],
|
players: &[Arc<Player>],
|
||||||
action: Action,
|
action: Action,
|
||||||
advancements: &[&'static Advancement],
|
advancements: &[&'static Advancement],
|
||||||
) -> Result<i32, CommandSyntaxError> {
|
) -> Result<i32, CommandSyntaxError> {
|
||||||
perform(context, players, action, advancements, true).await
|
perform(context, players, action, advancements, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Performs a batch action (grant or revoke) on multiple advancements for multiple players.
|
/// 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
|
/// 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. It automatically handles error messaging based on the number of players and
|
||||||
/// advancements involved, as well as the number of successful operations.
|
/// advancements involved.
|
||||||
///
|
///
|
||||||
/// # Arguments
|
/// # Arguments
|
||||||
///
|
///
|
||||||
/// * `context` - The command source context used to send feedback messages to the command executor
|
/// * `context` - The command source context for sending feedback
|
||||||
/// * `targets` - Slice of players who will be affected by the action
|
/// * `targets` - The players to apply the action to
|
||||||
/// * `action` - The action to perform on each advancement (Grant or Revoke)
|
/// * `action` - The action to perform on each advancement (Grant or Revoke)
|
||||||
/// * `advancements` - Slice of advancements to apply the action to
|
/// * `advancements` - A slice of advancements to apply the action to
|
||||||
/// * `show_advancement` - Whether to show advancement notifications to players (currently unused)
|
/// * `show_advancement` - Whether to show advancement notifications to players
|
||||||
///
|
///
|
||||||
/// # Returns
|
/// # Returns
|
||||||
///
|
///
|
||||||
/// Returns `Ok(i)` with the total count of successful operations if at least one advancement
|
/// Returns `Ok(count)` with the total number of advancements successfully granted/revoked across
|
||||||
/// was successfully modified for at least one player.
|
/// all players.
|
||||||
///
|
///
|
||||||
/// Returns `Err` with an appropriate localized error message if no operations succeeded. The
|
/// Returns `Err` with an appropriate localized error message if no operations succeeded. The
|
||||||
/// error message varies based on:
|
/// error message varies based on:
|
||||||
/// - Whether one or many players were targeted
|
/// - Whether one or many players were targeted
|
||||||
/// - Whether one or many advancements were involved
|
/// - Whether one or many advancements were involved
|
||||||
/// - The type of action (Grant or Revoke)
|
/// - The type of action (Grant or Revoke)
|
||||||
async fn perform(
|
fn perform(
|
||||||
context: Arc<CommandSource>,
|
context: &CommandSource,
|
||||||
targets: &[Arc<Player>],
|
targets: &[Arc<Player>],
|
||||||
action: Action,
|
action: Action,
|
||||||
advancements: &[&'static Advancement],
|
advancements: &[&'static Advancement],
|
||||||
@@ -303,7 +302,7 @@ async fn perform(
|
|||||||
) -> Result<i32, CommandSyntaxError> {
|
) -> Result<i32, CommandSyntaxError> {
|
||||||
let mut i = 0;
|
let mut i = 0;
|
||||||
for player in targets {
|
for player in targets {
|
||||||
i += action.perform(player, advancements, show_advancement).await;
|
i += action.perform(player, advancements, show_advancement);
|
||||||
}
|
}
|
||||||
if i == 0 {
|
if i == 0 {
|
||||||
return if let [first_advancement] = advancements[..] {
|
return if let [first_advancement] = advancements[..] {
|
||||||
@@ -378,7 +377,7 @@ async fn perform(
|
|||||||
],
|
],
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
context.send_feedback(translate, true).await;
|
context.send_feedback(translate, true);
|
||||||
Ok(i)
|
Ok(i)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -402,23 +401,19 @@ async fn perform(
|
|||||||
/// Returns `Err` with an appropriate error message if:
|
/// Returns `Err` with an appropriate error message if:
|
||||||
/// - The criterion doesn't exist in the advancement
|
/// - The criterion doesn't exist in the advancement
|
||||||
/// - No operations succeeded
|
/// - No operations succeeded
|
||||||
pub async fn perform_criterion(
|
pub fn perform_criterion(
|
||||||
context: Arc<CommandSource>,
|
context: &CommandSource,
|
||||||
targets: &[Arc<Player>],
|
targets: &[Arc<Player>],
|
||||||
action: Action,
|
action: Action,
|
||||||
advancement: &'static Advancement,
|
advancement: &'static Advancement,
|
||||||
criterion: &str,
|
criterion: &str,
|
||||||
) -> Result<i32, CommandSyntaxError> {
|
) -> Result<i32, CommandSyntaxError> {
|
||||||
if advancement.criteria.contains(&criterion) {
|
if advancement.criteria.contains(&criterion) {
|
||||||
let count = join_all(
|
let count = targets
|
||||||
targets
|
.iter()
|
||||||
.iter()
|
.map(|player| action.perform_criterion(player, advancement, criterion))
|
||||||
.map(|player| action.perform_criterion(player, advancement, criterion)),
|
.filter(|&success| success)
|
||||||
)
|
.count() as i32;
|
||||||
.await
|
|
||||||
.into_iter()
|
|
||||||
.filter(|&success| success)
|
|
||||||
.count() as i32;
|
|
||||||
if count == 0 {
|
if count == 0 {
|
||||||
if let [first_player] = targets {
|
if let [first_player] = targets {
|
||||||
Err(match action {
|
Err(match action {
|
||||||
@@ -461,14 +456,16 @@ pub async fn perform_criterion(
|
|||||||
],
|
],
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
context.send_feedback(translate, true).await;
|
context.send_feedback(translate, true);
|
||||||
Ok(count)
|
Ok(count)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Err(ERROR_CRITERION_NOT_FOUND.create_without_context(
|
Err(
|
||||||
advancement.name(),
|
ERROR_CRITERION_NOT_FOUND.create_without_context_args_slice(&[
|
||||||
TextComponent::text(criterion.to_owned()),
|
advancement.name(),
|
||||||
))
|
TextComponent::text(criterion.to_owned()),
|
||||||
|
]),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -478,18 +475,15 @@ struct OnlyAdvancementCriterionExecutor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CommandExecutor for OnlyAdvancementCriterionExecutor {
|
impl CommandExecutor for OnlyAdvancementCriterionExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
let action = self.action;
|
let action = self.action;
|
||||||
Box::pin(async move {
|
perform_criterion(
|
||||||
perform_criterion(
|
&context.source,
|
||||||
context.source.clone(),
|
&EntityArgumentType::get_players(context, ARG_TARGETS)?,
|
||||||
&EntityArgumentType::get_players(context, ARG_TARGETS).await?,
|
action,
|
||||||
action,
|
ResourceKeyArgument::get_advancement(context, ARG_ADVANCEMENT)?,
|
||||||
ResourceKeyArgument::get_advancement(context, ARG_ADVANCEMENT)?,
|
StringArgumentType::get(context, ARG_CRITERION)?,
|
||||||
StringArgumentType::get(context, ARG_CRITERION)?,
|
)
|
||||||
)
|
|
||||||
.await
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -500,21 +494,18 @@ struct AdvancementExecutor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CommandExecutor for AdvancementExecutor {
|
impl CommandExecutor for AdvancementExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
let action = self.action;
|
let action = self.action;
|
||||||
let mode = self.mode;
|
let mode = self.mode;
|
||||||
Box::pin(async move {
|
perform_and_show(
|
||||||
perform_and_show(
|
&context.source,
|
||||||
context.source.clone(),
|
&EntityArgumentType::get_players(context, ARG_TARGETS)?,
|
||||||
&EntityArgumentType::get_players(context, ARG_TARGETS).await?,
|
action,
|
||||||
action,
|
&get_advancements(
|
||||||
&get_advancements(
|
ResourceKeyArgument::get_advancement(context, ARG_ADVANCEMENT)?,
|
||||||
ResourceKeyArgument::get_advancement(context, ARG_ADVANCEMENT)?,
|
mode,
|
||||||
mode,
|
),
|
||||||
),
|
)
|
||||||
)
|
|
||||||
.await
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -522,18 +513,18 @@ impl CommandExecutor for AdvancementExecutor {
|
|||||||
struct CriterionSuggestionProvider;
|
struct CriterionSuggestionProvider;
|
||||||
|
|
||||||
impl SuggestionProvider for CriterionSuggestionProvider {
|
impl SuggestionProvider for CriterionSuggestionProvider {
|
||||||
fn suggest<'a>(
|
fn suggest(
|
||||||
&'a self,
|
&self,
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
builder: SuggestionsBuilder,
|
builder: SuggestionsBuilder,
|
||||||
) -> SuggestionProviderResult<'a> {
|
) -> SuggestionProviderResult {
|
||||||
let suggestion = ResourceKeyArgument::get_advancement(context, ARG_ADVANCEMENT)
|
let suggestion = ResourceKeyArgument::get_advancement(context, ARG_ADVANCEMENT)
|
||||||
.ok()
|
.ok()
|
||||||
.map(|adv| adv.criteria)
|
.map(|adv| adv.criteria)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.flatten()
|
.flatten()
|
||||||
.map(ToString::to_string);
|
.map(ToString::to_string);
|
||||||
Box::pin(async move { builder.filter_and_suggest_iter(suggestion).build() })
|
builder.filter_and_suggest_iter(suggestion).build()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -543,18 +534,15 @@ struct EveryAdvancementExecutor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CommandExecutor for EveryAdvancementExecutor {
|
impl CommandExecutor for EveryAdvancementExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
let action = self.action;
|
let action = self.action;
|
||||||
Box::pin(async move {
|
perform(
|
||||||
perform(
|
&context.source,
|
||||||
context.source.clone(),
|
&EntityArgumentType::get_players(context, ARG_TARGETS)?,
|
||||||
&EntityArgumentType::get_players(context, ARG_TARGETS).await?,
|
action,
|
||||||
action,
|
&Advancement::get_advancements_list(),
|
||||||
&Advancement::get_advancements_list(),
|
false,
|
||||||
false,
|
)
|
||||||
)
|
|
||||||
.await
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -59,180 +59,162 @@ struct GetExecutor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CommandExecutor for GetExecutor {
|
impl CommandExecutor for GetExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let target = EntityArgumentType::get_entity(context, ARG_TARGET)?;
|
||||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
let living = target
|
||||||
let living = target
|
.get_living_entity()
|
||||||
.get_living_entity()
|
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
|
||||||
|
|
||||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||||
let scale = if self.has_scale {
|
let scale = if self.has_scale {
|
||||||
DoubleArgumentType::get(context, ARG_SCALE)?
|
DoubleArgumentType::get(context, ARG_SCALE)?
|
||||||
} else {
|
} else {
|
||||||
1.0
|
1.0
|
||||||
};
|
};
|
||||||
|
|
||||||
let has_attr = living
|
let has_attr = living
|
||||||
.attributes
|
.attributes
|
||||||
.read()
|
.read()
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
.contains_key(&attribute.id);
|
.contains_key(&attribute.id);
|
||||||
if !has_attr {
|
if !has_attr {
|
||||||
return Err(NO_ATTRIBUTE_ERROR.create_without_context(
|
return Err(NO_ATTRIBUTE_ERROR.create_without_context(
|
||||||
target.get_name(),
|
target.get_name(),
|
||||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.is_base {
|
if self.is_base {
|
||||||
let base_value = living.get_attribute_base(&attribute);
|
let base_value = living.get_attribute_base(&attribute);
|
||||||
let scaled_value = base_value * scale;
|
let scaled_value = base_value * scale;
|
||||||
|
|
||||||
context
|
context.source.send_feedback(
|
||||||
.source
|
TextComponent::translate_cross(
|
||||||
.send_feedback(
|
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_GET_SUCCESS,
|
||||||
TextComponent::translate_cross(
|
translation::java::COMMANDS_ATTRIBUTE_BASE_VALUE_GET_SUCCESS,
|
||||||
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::translate(attribute_translation_key(&attribute), []),
|
TextComponent::text(base_value.to_string()),
|
||||||
target.get_name(),
|
],
|
||||||
TextComponent::text(base_value.to_string()),
|
),
|
||||||
],
|
false,
|
||||||
),
|
);
|
||||||
false,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(scaled_value as i32)
|
Ok(scaled_value as i32)
|
||||||
} else {
|
} else {
|
||||||
let value = living.get_attribute_value(&attribute);
|
let value = living.get_attribute_value(&attribute);
|
||||||
let scaled_value = value * scale;
|
let scaled_value = value * scale;
|
||||||
|
|
||||||
context
|
context.source.send_feedback(
|
||||||
.source
|
TextComponent::translate_cross(
|
||||||
.send_feedback(
|
translation::java::COMMANDS_ATTRIBUTE_VALUE_GET_SUCCESS,
|
||||||
TextComponent::translate_cross(
|
translation::java::COMMANDS_ATTRIBUTE_VALUE_GET_SUCCESS,
|
||||||
translation::java::COMMANDS_ATTRIBUTE_VALUE_GET_SUCCESS,
|
[
|
||||||
translation::java::COMMANDS_ATTRIBUTE_VALUE_GET_SUCCESS,
|
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||||
[
|
target.get_name(),
|
||||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
TextComponent::text(value.to_string()),
|
||||||
target.get_name(),
|
],
|
||||||
TextComponent::text(value.to_string()),
|
),
|
||||||
],
|
false,
|
||||||
),
|
);
|
||||||
false,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(scaled_value as i32)
|
Ok(scaled_value as i32)
|
||||||
}
|
}
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct BaseSetExecutor;
|
struct BaseSetExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for BaseSetExecutor {
|
impl CommandExecutor for BaseSetExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let target = EntityArgumentType::get_entity(context, ARG_TARGET)?;
|
||||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
let living = target
|
||||||
let living = target
|
.get_living_entity()
|
||||||
.get_living_entity()
|
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
|
||||||
|
|
||||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||||
let value = DoubleArgumentType::get(context, ARG_VALUE)?;
|
let value = DoubleArgumentType::get(context, ARG_VALUE)?;
|
||||||
|
|
||||||
let has_attr = living
|
let has_attr = living
|
||||||
.attributes
|
.attributes
|
||||||
.read()
|
.read()
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
.contains_key(&attribute.id);
|
.contains_key(&attribute.id);
|
||||||
if !has_attr {
|
if !has_attr {
|
||||||
return Err(NO_ATTRIBUTE_ERROR.create_without_context(
|
return Err(NO_ATTRIBUTE_ERROR.create_without_context(
|
||||||
target.get_name(),
|
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()],
|
||||||
|
);
|
||||||
|
|
||||||
|
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), []),
|
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||||
));
|
target.get_name(),
|
||||||
}
|
TextComponent::text(value.to_string()),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
|
||||||
living.set_attribute_base(&attribute, value);
|
Ok(value as i32)
|
||||||
crate::entity::attributes::send_attribute_updates_for_living(
|
|
||||||
living,
|
|
||||||
vec![attribute.clone()],
|
|
||||||
);
|
|
||||||
|
|
||||||
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;
|
struct BaseResetExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for BaseResetExecutor {
|
impl CommandExecutor for BaseResetExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let target = EntityArgumentType::get_entity(context, ARG_TARGET)?;
|
||||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
let living = target
|
||||||
let living = target
|
.get_living_entity()
|
||||||
.get_living_entity()
|
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
|
||||||
|
|
||||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||||
|
|
||||||
let has_attr = living
|
let has_attr = living
|
||||||
.attributes
|
.attributes
|
||||||
.read()
|
.read()
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
.contains_key(&attribute.id);
|
.contains_key(&attribute.id);
|
||||||
if !has_attr {
|
if !has_attr {
|
||||||
return Err(NO_ATTRIBUTE_ERROR.create_without_context(
|
return Err(NO_ATTRIBUTE_ERROR.create_without_context(
|
||||||
target.get_name(),
|
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()],
|
||||||
|
);
|
||||||
|
|
||||||
|
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), []),
|
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||||
));
|
target.get_name(),
|
||||||
}
|
TextComponent::text(default_val.to_string()),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
|
||||||
let default_val = attribute.default_value;
|
Ok(default_val as i32)
|
||||||
living.set_attribute_base(&attribute, default_val);
|
|
||||||
crate::entity::attributes::send_attribute_updates_for_living(
|
|
||||||
living,
|
|
||||||
vec![attribute.clone()],
|
|
||||||
);
|
|
||||||
|
|
||||||
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)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -241,208 +223,193 @@ struct ModifierAddExecutor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CommandExecutor for ModifierAddExecutor {
|
impl CommandExecutor for ModifierAddExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let target = EntityArgumentType::get_entity(context, ARG_TARGET)?;
|
||||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
let living = target
|
||||||
let living = target
|
.get_living_entity()
|
||||||
.get_living_entity()
|
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
|
||||||
|
|
||||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||||
let uuid = UuidArgumentType::get(context, ARG_UUID)?;
|
let uuid = UuidArgumentType::get(context, ARG_UUID)?;
|
||||||
let _name = StringArgumentType::get(context, ARG_NAME)?;
|
let _name = StringArgumentType::get(context, ARG_NAME)?;
|
||||||
let value = DoubleArgumentType::get(context, ARG_VALUE)?;
|
let value = DoubleArgumentType::get(context, ARG_VALUE)?;
|
||||||
|
|
||||||
let modifier_id = uuid.to_string();
|
let modifier_id = uuid.to_string();
|
||||||
|
|
||||||
let res = {
|
let res = {
|
||||||
let mut map = living
|
let mut map = living
|
||||||
.attributes
|
.attributes
|
||||||
.write()
|
.write()
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
let inst = map.get_mut(&attribute.id).ok_or_else(|| {
|
let inst = map.get_mut(&attribute.id).ok_or_else(|| {
|
||||||
NO_ATTRIBUTE_ERROR.create_without_context(
|
NO_ATTRIBUTE_ERROR.create_without_context(
|
||||||
target.get_name(),
|
target.get_name(),
|
||||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
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()],
|
|
||||||
);
|
|
||||||
|
|
||||||
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)
|
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()],
|
||||||
|
);
|
||||||
|
|
||||||
|
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,
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ModifierRemoveExecutor;
|
struct ModifierRemoveExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for ModifierRemoveExecutor {
|
impl CommandExecutor for ModifierRemoveExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let target = EntityArgumentType::get_entity(context, ARG_TARGET)?;
|
||||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
let living = target
|
||||||
let living = target
|
.get_living_entity()
|
||||||
.get_living_entity()
|
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
|
||||||
|
|
||||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||||
let uuid = UuidArgumentType::get(context, ARG_UUID)?;
|
let uuid = UuidArgumentType::get(context, ARG_UUID)?;
|
||||||
|
|
||||||
let modifier_id = uuid.to_string();
|
let modifier_id = uuid.to_string();
|
||||||
|
|
||||||
let res = {
|
let res = {
|
||||||
let mut map = living
|
let mut map = living
|
||||||
.attributes
|
.attributes
|
||||||
.write()
|
.write()
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
let inst = map.get_mut(&attribute.id).ok_or_else(|| {
|
let inst = map.get_mut(&attribute.id).ok_or_else(|| {
|
||||||
NO_ATTRIBUTE_ERROR.create_without_context(
|
NO_ATTRIBUTE_ERROR.create_without_context(
|
||||||
target.get_name(),
|
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), []),
|
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||||
|
target.get_name(),
|
||||||
|
TextComponent::text(modifier_id.clone()),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let index = inst
|
inst.modifiers.remove(index);
|
||||||
.modifiers
|
inst.dirty.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||||
.iter()
|
Ok(())
|
||||||
.position(|m| m.id == modifier_id)
|
};
|
||||||
.ok_or_else(|| {
|
res?;
|
||||||
NO_MODIFIER_ERROR.create_without_context(
|
|
||||||
TextComponent::translate(attribute_translation_key(&attribute), []),
|
|
||||||
target.get_name(),
|
|
||||||
TextComponent::text(modifier_id.clone()),
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
inst.modifiers.remove(index);
|
crate::entity::attributes::send_attribute_updates_for_living(
|
||||||
inst.dirty.store(true, std::sync::atomic::Ordering::Relaxed);
|
living,
|
||||||
Ok(())
|
vec![attribute.clone()],
|
||||||
};
|
);
|
||||||
res?;
|
|
||||||
|
|
||||||
crate::entity::attributes::send_attribute_updates_for_living(
|
context.source.send_feedback(
|
||||||
living,
|
TextComponent::translate_cross(
|
||||||
vec![attribute.clone()],
|
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,
|
||||||
|
);
|
||||||
|
|
||||||
context
|
Ok(1)
|
||||||
.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;
|
struct ModifierGetExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for ModifierGetExecutor {
|
impl CommandExecutor for ModifierGetExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let target = EntityArgumentType::get_entity(context, ARG_TARGET)?;
|
||||||
let target = EntityArgumentType::get_entity(context, ARG_TARGET).await?;
|
let living = target
|
||||||
let living = target
|
.get_living_entity()
|
||||||
.get_living_entity()
|
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
||||||
.ok_or_else(|| FAILED_ENTITY_ERROR.create_without_context(target.get_name()))?;
|
|
||||||
|
|
||||||
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
let attribute = AttributeArgumentType::get(context, ARG_ATTRIBUTE)?;
|
||||||
let uuid = UuidArgumentType::get(context, ARG_UUID)?;
|
let uuid = UuidArgumentType::get(context, ARG_UUID)?;
|
||||||
|
|
||||||
let modifier_id = uuid.to_string();
|
let modifier_id = uuid.to_string();
|
||||||
|
|
||||||
let val = {
|
let val = {
|
||||||
let map = living
|
let map = living
|
||||||
.attributes
|
.attributes
|
||||||
.read()
|
.read()
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
let inst = map.get(&attribute.id).ok_or_else(|| {
|
let inst = map.get(&attribute.id).ok_or_else(|| {
|
||||||
NO_ATTRIBUTE_ERROR.create_without_context(
|
NO_ATTRIBUTE_ERROR.create_without_context(
|
||||||
target.get_name(),
|
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), []),
|
TextComponent::translate(attribute_translation_key(&attribute), []),
|
||||||
|
target.get_name(),
|
||||||
|
TextComponent::text(modifier_id.clone()),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let modifier = inst
|
modifier.amount
|
||||||
.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,
|
||||||
|
);
|
||||||
|
|
||||||
context
|
Ok(val as i32)
|
||||||
.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)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
use crate::command::CommandResult;
|
|
||||||
use crate::{
|
use crate::{
|
||||||
command::{
|
command::{
|
||||||
CommandError, CommandExecutor, CommandSender,
|
CommandError, CommandExecutor, CommandResult, CommandSender,
|
||||||
args::{
|
args::{
|
||||||
Arg, ConsumedArgs,
|
Arg, ConsumedArgs,
|
||||||
gameprofile::{GameProfileSuggestionMode, GameProfilesArgumentConsumer},
|
gameprofile::{GameProfileSuggestionMode, GameProfilesArgumentConsumer},
|
||||||
@@ -25,47 +24,43 @@ const ARG_REASON: &str = "reason";
|
|||||||
struct NoReasonExecutor;
|
struct NoReasonExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for NoReasonExecutor {
|
impl CommandExecutor for NoReasonExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
server: &'a crate::server::Server,
|
server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGET) else {
|
||||||
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGET) else {
|
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
};
|
||||||
};
|
|
||||||
|
|
||||||
ban_players(sender, server, targets.as_slice(), None).await
|
ban_players(sender, server, targets.as_slice(), None)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ReasonExecutor;
|
struct ReasonExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for ReasonExecutor {
|
impl CommandExecutor for ReasonExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
server: &'a crate::server::Server,
|
server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGET) else {
|
||||||
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGET) else {
|
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
};
|
||||||
};
|
|
||||||
|
|
||||||
let Some(Arg::Msg(reason)) = args.get(ARG_REASON) else {
|
let Some(Arg::Msg(reason)) = args.get(ARG_REASON) else {
|
||||||
return Err(InvalidConsumption(Some(ARG_REASON.into())));
|
return Err(InvalidConsumption(Some(ARG_REASON.into())));
|
||||||
};
|
};
|
||||||
|
|
||||||
ban_players(sender, server, targets.as_slice(), Some(reason)).await
|
ban_players(sender, server, targets.as_slice(), Some(reason))
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the number of players successfully banned.
|
/// Returns the number of players successfully banned.
|
||||||
async fn ban_players(
|
fn ban_players(
|
||||||
sender: &CommandSender,
|
sender: &CommandSender,
|
||||||
server: &crate::server::Server,
|
server: &crate::server::Server,
|
||||||
targets: &[GameProfile],
|
targets: &[GameProfile],
|
||||||
@@ -73,7 +68,7 @@ async fn ban_players(
|
|||||||
) -> Result<i32, CommandError> {
|
) -> Result<i32, CommandError> {
|
||||||
let mut count: usize = 0;
|
let mut count: usize = 0;
|
||||||
for target in targets {
|
for target in targets {
|
||||||
if ban_profile(sender, server, target, reason.cloned()).await {
|
if ban_profile(sender, server, target, reason.cloned()) {
|
||||||
count += 1;
|
count += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -90,13 +85,13 @@ async fn ban_players(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Returns `true` if the player was successfully banned.
|
/// Returns `true` if the player was successfully banned.
|
||||||
async fn ban_profile(
|
fn ban_profile(
|
||||||
sender: &CommandSender,
|
sender: &CommandSender,
|
||||||
server: &crate::server::Server,
|
server: &crate::server::Server,
|
||||||
profile: &GameProfile,
|
profile: &GameProfile,
|
||||||
reason: Option<String>,
|
reason: Option<String>,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
let mut banned_players = server.data.banned_player_list.write().await;
|
let mut banned_players = server.data.banned_player_list.write().unwrap();
|
||||||
|
|
||||||
let reason = reason.unwrap_or_else(|| "Banned by an operator.".to_string());
|
let reason = reason.unwrap_or_else(|| "Banned by an operator.".to_string());
|
||||||
|
|
||||||
@@ -123,28 +118,22 @@ async fn ban_profile(
|
|||||||
drop(banned_players);
|
drop(banned_players);
|
||||||
|
|
||||||
// Send messages
|
// Send messages
|
||||||
sender
|
sender.send_message(TextComponent::translate_cross(
|
||||||
.send_message(TextComponent::translate_cross(
|
translation::java::COMMANDS_BAN_SUCCESS,
|
||||||
translation::java::COMMANDS_BAN_SUCCESS,
|
translation::bedrock::COMMANDS_BAN_SUCCESS,
|
||||||
translation::bedrock::COMMANDS_BAN_SUCCESS,
|
[
|
||||||
[
|
TextComponent::text(profile.name.clone()),
|
||||||
TextComponent::text(profile.name.clone()),
|
TextComponent::text(reason),
|
||||||
TextComponent::text(reason),
|
],
|
||||||
],
|
));
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
if let Some(player) = server.get_player_by_uuid(profile.id) {
|
if let Some(player) = server.get_player_by_uuid(profile.id) {
|
||||||
player
|
let kick_msg = TextComponent::translate_cross(
|
||||||
.kick(
|
translation::java::MULTIPLAYER_DISCONNECT_BANNED,
|
||||||
DisconnectReason::Kicked,
|
translation::bedrock::DISCONNECTIONSCREEN_TITLE_BANNEDBYHOST,
|
||||||
TextComponent::translate_cross(
|
[],
|
||||||
translation::java::MULTIPLAYER_DISCONNECT_BANNED,
|
);
|
||||||
translation::bedrock::DISCONNECTIONSCREEN_TITLE_BANNEDBYHOST,
|
player.kick(DisconnectReason::Kicked, &kick_msg);
|
||||||
[],
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
true
|
true
|
||||||
|
|||||||
@@ -30,46 +30,42 @@ fn parse_ip(target: &str, server: &Server) -> Option<IpAddr> {
|
|||||||
struct NoReasonExecutor;
|
struct NoReasonExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for NoReasonExecutor {
|
impl CommandExecutor for NoReasonExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
server: &'a crate::server::Server,
|
server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let Some(Arg::Simple(target)) = args.get(&ARG_TARGET) else {
|
||||||
let Some(Arg::Simple(target)) = args.get(&ARG_TARGET) else {
|
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
};
|
||||||
};
|
|
||||||
|
|
||||||
ban_ip(sender, server, target, None).await
|
ban_ip(sender, server, target, None)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ReasonExecutor;
|
struct ReasonExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for ReasonExecutor {
|
impl CommandExecutor for ReasonExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
server: &'a crate::server::Server,
|
server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let Some(Arg::Simple(target)) = args.get(&ARG_TARGET) else {
|
||||||
let Some(Arg::Simple(target)) = args.get(&ARG_TARGET) else {
|
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
};
|
||||||
};
|
|
||||||
|
|
||||||
let Some(Arg::Msg(reason)) = args.get(ARG_REASON) else {
|
let Some(Arg::Msg(reason)) = args.get(ARG_REASON) else {
|
||||||
return Err(InvalidConsumption(Some(ARG_REASON.into())));
|
return Err(InvalidConsumption(Some(ARG_REASON.into())));
|
||||||
};
|
};
|
||||||
|
|
||||||
ban_ip(sender, server, target, Some(reason.clone())).await
|
ban_ip(sender, server, target, Some(reason.clone()))
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn ban_ip(
|
fn ban_ip(
|
||||||
sender: &CommandSender,
|
sender: &CommandSender,
|
||||||
server: &Server,
|
server: &Server,
|
||||||
target: &str,
|
target: &str,
|
||||||
@@ -85,7 +81,7 @@ async fn ban_ip(
|
|||||||
)));
|
)));
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut banned_ips = server.data.banned_ip_list.write().await;
|
let mut banned_ips = server.data.banned_ip_list.write().unwrap();
|
||||||
|
|
||||||
if banned_ips.get_entry(&target_ip).is_some() {
|
if banned_ips.get_entry(&target_ip).is_some() {
|
||||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||||
@@ -113,40 +109,32 @@ async fn ban_ip(
|
|||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join(" ");
|
.join(" ");
|
||||||
|
|
||||||
sender
|
sender.send_message(TextComponent::translate_cross(
|
||||||
.send_message(TextComponent::translate_cross(
|
translation::java::COMMANDS_BANIP_SUCCESS,
|
||||||
translation::java::COMMANDS_BANIP_SUCCESS,
|
translation::bedrock::COMMANDS_BANIP_SUCCESS,
|
||||||
translation::bedrock::COMMANDS_BANIP_SUCCESS,
|
[
|
||||||
[
|
TextComponent::text(target_ip.to_string()),
|
||||||
TextComponent::text(target_ip.to_string()),
|
TextComponent::text(reason),
|
||||||
TextComponent::text(reason),
|
],
|
||||||
],
|
));
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
sender
|
sender.send_message(TextComponent::translate_cross(
|
||||||
.send_message(TextComponent::translate_cross(
|
translation::java::COMMANDS_BANIP_INFO,
|
||||||
translation::java::COMMANDS_BANIP_INFO,
|
translation::java::COMMANDS_BANIP_INFO,
|
||||||
translation::java::COMMANDS_BANIP_INFO,
|
[
|
||||||
[
|
TextComponent::text(affected.len().to_string()),
|
||||||
TextComponent::text(affected.len().to_string()),
|
TextComponent::text(names),
|
||||||
TextComponent::text(names),
|
],
|
||||||
],
|
));
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let count = affected.len();
|
let count = affected.len();
|
||||||
for target in affected {
|
for target in affected {
|
||||||
target
|
let kick_msg = TextComponent::translate_cross(
|
||||||
.kick(
|
translation::java::MULTIPLAYER_DISCONNECT_IP_BANNED,
|
||||||
DisconnectReason::Kicked,
|
translation::java::MULTIPLAYER_DISCONNECT_IP_BANNED,
|
||||||
TextComponent::translate_cross(
|
[],
|
||||||
translation::java::MULTIPLAYER_DISCONNECT_IP_BANNED,
|
);
|
||||||
translation::java::MULTIPLAYER_DISCONNECT_IP_BANNED,
|
target.kick(DisconnectReason::Kicked, &kick_msg);
|
||||||
[],
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(count as i32)
|
Ok(count as i32)
|
||||||
|
|||||||
@@ -23,86 +23,78 @@ struct BanListCommandExecutor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CommandExecutor for BanListCommandExecutor {
|
impl CommandExecutor for BanListCommandExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let mut entries = Vec::new();
|
||||||
let mut entries = Vec::new();
|
|
||||||
|
|
||||||
let data = &context.server().data;
|
let data = &context.server().data;
|
||||||
|
|
||||||
if self.players {
|
if self.players {
|
||||||
let lock = data.banned_player_list.read().await;
|
let lock = data.banned_player_list.read().unwrap();
|
||||||
for entry in &lock.banned_players {
|
for entry in &lock.banned_players {
|
||||||
entries.push(BanListEntry {
|
entries.push(BanListEntry {
|
||||||
name: entry.name.clone(),
|
name: entry.name.clone(),
|
||||||
source: entry.source.clone(),
|
source: entry.source.clone(),
|
||||||
reason: entry.reason.clone(),
|
reason: entry.reason.clone(),
|
||||||
});
|
});
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if self.ips {
|
if self.ips {
|
||||||
let lock = data.banned_ip_list.read().await;
|
let lock = data.banned_ip_list.read().unwrap();
|
||||||
for entry in &lock.banned_ips {
|
for entry in &lock.banned_ips {
|
||||||
entries.push(BanListEntry {
|
entries.push(BanListEntry {
|
||||||
name: entry.ip.to_string(),
|
name: entry.ip.to_string(),
|
||||||
source: entry.source.clone(),
|
source: entry.source.clone(),
|
||||||
reason: entry.reason.clone(),
|
reason: entry.reason.clone(),
|
||||||
});
|
});
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let entries_len = entries.len() as i32;
|
let entries_len = entries.len() as i32;
|
||||||
let source = &context.source;
|
let source = &context.source;
|
||||||
|
|
||||||
if entries.is_empty() {
|
if entries.is_empty() {
|
||||||
source
|
source.send_feedback(
|
||||||
.send_feedback(
|
TextComponent::translate_cross(
|
||||||
TextComponent::translate_cross(
|
translation::java::COMMANDS_BANLIST_NONE,
|
||||||
translation::java::COMMANDS_BANLIST_NONE,
|
translation::java::COMMANDS_BANLIST_NONE,
|
||||||
translation::java::COMMANDS_BANLIST_NONE,
|
[],
|
||||||
[],
|
),
|
||||||
),
|
false,
|
||||||
false,
|
);
|
||||||
)
|
} else {
|
||||||
.await;
|
let bedrock_list_key = if self.ips && !self.players {
|
||||||
|
translation::bedrock::COMMANDS_BANLIST_IPS
|
||||||
} else {
|
} else {
|
||||||
let bedrock_list_key = if self.ips && !self.players {
|
translation::bedrock::COMMANDS_BANLIST_PLAYERS
|
||||||
translation::bedrock::COMMANDS_BANLIST_IPS
|
};
|
||||||
} else {
|
|
||||||
translation::bedrock::COMMANDS_BANLIST_PLAYERS
|
|
||||||
};
|
|
||||||
|
|
||||||
source
|
source.send_feedback(
|
||||||
.send_feedback(
|
TextComponent::translate_cross(
|
||||||
TextComponent::translate_cross(
|
translation::java::COMMANDS_BANLIST_LIST,
|
||||||
translation::java::COMMANDS_BANLIST_LIST,
|
bedrock_list_key,
|
||||||
bedrock_list_key,
|
[TextComponent::text(entries.len().to_string())],
|
||||||
[TextComponent::text(entries.len().to_string())],
|
),
|
||||||
),
|
false,
|
||||||
false,
|
);
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
for entry in entries {
|
for entry in entries {
|
||||||
source
|
source.send_feedback(
|
||||||
.send_feedback(
|
TextComponent::translate_cross(
|
||||||
TextComponent::translate_cross(
|
translation::java::COMMANDS_BANLIST_ENTRY,
|
||||||
translation::java::COMMANDS_BANLIST_ENTRY,
|
translation::java::COMMANDS_BANLIST_ENTRY,
|
||||||
translation::java::COMMANDS_BANLIST_ENTRY,
|
[
|
||||||
[
|
TextComponent::text(entry.name),
|
||||||
TextComponent::text(entry.name),
|
TextComponent::text(entry.source),
|
||||||
TextComponent::text(entry.source),
|
TextComponent::text(entry.reason),
|
||||||
TextComponent::text(entry.reason),
|
],
|
||||||
],
|
),
|
||||||
),
|
false,
|
||||||
false,
|
);
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(entries_len)
|
Ok(entries_len)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,25 +35,23 @@ const fn autocomplete_consumer() -> ResourceLocationArgumentConsumer {
|
|||||||
struct BossbarSuggestionProvider;
|
struct BossbarSuggestionProvider;
|
||||||
|
|
||||||
impl CommandSuggestionProvider for BossbarSuggestionProvider {
|
impl CommandSuggestionProvider for BossbarSuggestionProvider {
|
||||||
fn suggest<'a>(
|
fn suggest(
|
||||||
&'a self,
|
&self,
|
||||||
_src: &'a CommandSender,
|
_src: &CommandSender,
|
||||||
server: &'a Server,
|
server: &Server,
|
||||||
input: &'a str,
|
input: &str,
|
||||||
start: usize,
|
start: usize,
|
||||||
_end: usize,
|
_end: usize,
|
||||||
) -> CommandSuggestionResult<'a> {
|
) -> CommandSuggestionResult {
|
||||||
Box::pin(async move {
|
let mut builder = SuggestionsBuilder::new(input, start);
|
||||||
let mut builder = SuggestionsBuilder::new(input, start);
|
let bossbars = server.bossbars.lock().unwrap();
|
||||||
let bossbars = server.bossbars.lock().await;
|
let remaining = builder.remaining_lowercase().to_string();
|
||||||
let remaining = builder.remaining_lowercase().to_string();
|
for key in bossbars.custom_bossbars.keys() {
|
||||||
for key in bossbars.custom_bossbars.keys() {
|
if key.to_lowercase().starts_with(&remaining) {
|
||||||
if key.to_lowercase().starts_with(&remaining) {
|
builder = builder.suggest(key.clone());
|
||||||
builder = builder.suggest(key.clone());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
builder.build()
|
}
|
||||||
})
|
builder.build()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,269 +75,229 @@ enum CommandValueSet {
|
|||||||
struct AddExecutor;
|
struct AddExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for AddExecutor {
|
impl CommandExecutor for AddExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
server: &'a crate::server::Server,
|
server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let namespace = autocomplete_consumer()
|
||||||
let namespace = autocomplete_consumer()
|
.find_arg_default_name(args)?
|
||||||
.find_arg_default_name(args)?
|
.to_string();
|
||||||
.to_string();
|
|
||||||
|
|
||||||
let text_component = TextComponentArgConsumer::find_arg(args, ARG_NAME)?;
|
let text_component = TextComponentArgConsumer::find_arg(args, ARG_NAME)?;
|
||||||
|
|
||||||
if server.bossbars.lock().await.has_bossbar(&namespace) {
|
if server.bossbars.lock().unwrap().has_bossbar(&namespace) {
|
||||||
return Result::Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
return Result::Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||||
translation::java::COMMANDS_BOSSBAR_CREATE_FAILED,
|
translation::java::COMMANDS_BOSSBAR_CREATE_FAILED,
|
||||||
translation::bedrock::COMMANDS_BOSSBAR_ADD_FAILURE_EXISTS,
|
translation::bedrock::COMMANDS_BOSSBAR_ADD_FAILURE_EXISTS,
|
||||||
[TextComponent::text(namespace.clone())],
|
[TextComponent::text(namespace)],
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
let bossbar = Bossbar::new(text_component);
|
let bossbar = Bossbar::new(text_component);
|
||||||
let mut bossbars = server.bossbars.lock().await;
|
let mut bossbars = server.bossbars.lock().unwrap();
|
||||||
|
|
||||||
bossbars.create_bossbar(namespace.clone(), bossbar.clone());
|
bossbars.create_bossbar(namespace.clone(), bossbar.clone());
|
||||||
let new_size = bossbars.get_bossbars_len();
|
let new_size = bossbars.get_bossbars_len();
|
||||||
drop(bossbars);
|
drop(bossbars);
|
||||||
|
|
||||||
sender
|
sender.send_message(TextComponent::translate_cross(
|
||||||
.send_message(TextComponent::translate_cross(
|
translation::java::COMMANDS_BOSSBAR_CREATE_SUCCESS,
|
||||||
translation::java::COMMANDS_BOSSBAR_CREATE_SUCCESS,
|
translation::bedrock::COMMANDS_BOSSBAR_ADD_SUCCESS,
|
||||||
translation::bedrock::COMMANDS_BOSSBAR_ADD_SUCCESS,
|
[bossbar_prefix(bossbar.title, namespace)],
|
||||||
[bossbar_prefix(bossbar.title.clone(), namespace.clone())],
|
));
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(new_size as i32)
|
Ok(new_size as i32)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct GetExecutor(CommandValueGet);
|
struct GetExecutor(CommandValueGet);
|
||||||
|
|
||||||
impl CommandExecutor for GetExecutor {
|
impl CommandExecutor for GetExecutor {
|
||||||
#[expect(clippy::too_many_lines)]
|
fn execute(
|
||||||
fn execute<'a>(
|
&self,
|
||||||
&'a self,
|
sender: &CommandSender,
|
||||||
sender: &'a CommandSender,
|
server: &crate::server::Server,
|
||||||
server: &'a crate::server::Server,
|
args: &ConsumedArgs,
|
||||||
args: &'a ConsumedArgs<'a>,
|
) -> CommandResult {
|
||||||
) -> CommandResult<'a> {
|
let namespace = autocomplete_consumer()
|
||||||
Box::pin(async move {
|
.find_arg_default_name(args)?
|
||||||
let namespace = autocomplete_consumer()
|
.to_string();
|
||||||
.find_arg_default_name(args)?
|
|
||||||
.to_string();
|
|
||||||
|
|
||||||
let Some(bossbar) = server.bossbars.lock().await.get_bossbar(&namespace) else {
|
let Some(bossbar) = server.bossbars.lock().unwrap().get_bossbar(&namespace) else {
|
||||||
return Err(handle_bossbar_error(
|
return Err(handle_bossbar_error(
|
||||||
BossbarUpdateError::InvalidResourceLocation(namespace.clone()),
|
BossbarUpdateError::InvalidResourceLocation(namespace),
|
||||||
|
));
|
||||||
|
};
|
||||||
|
|
||||||
|
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),
|
||||||
|
TextComponent::text(bossbar.max.to_string()),
|
||||||
|
],
|
||||||
));
|
));
|
||||||
};
|
Ok(bossbar.max)
|
||||||
|
|
||||||
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 => {
|
|
||||||
let online_players: Vec<String> = server
|
|
||||||
.get_all_players()
|
|
||||||
.iter()
|
|
||||||
.filter(|player| bossbar.players.contains(&player.gameprofile.id))
|
|
||||||
.map(|player| player.gameprofile.name.clone())
|
|
||||||
.collect();
|
|
||||||
let count = online_players.len() as i32;
|
|
||||||
|
|
||||||
if count == 0 {
|
|
||||||
sender
|
|
||||||
.send_message(TextComponent::translate_cross(
|
|
||||||
translation::java::COMMANDS_BOSSBAR_GET_PLAYERS_NONE,
|
|
||||||
translation::bedrock::COMMANDS_BOSSBAR_GET_PLAYERS_NONE,
|
|
||||||
[bossbar_prefix(
|
|
||||||
bossbar.bossbar_data.title.clone(),
|
|
||||||
namespace.clone(),
|
|
||||||
)],
|
|
||||||
))
|
|
||||||
.await;
|
|
||||||
} else {
|
|
||||||
sender
|
|
||||||
.send_message(TextComponent::translate_cross(
|
|
||||||
translation::java::COMMANDS_BOSSBAR_GET_PLAYERS_SOME,
|
|
||||||
if count == 1 {
|
|
||||||
translation::bedrock::COMMANDS_BOSSBAR_GET_PLAYERS_ONE
|
|
||||||
} else {
|
|
||||||
translation::bedrock::COMMANDS_BOSSBAR_GET_PLAYERS
|
|
||||||
},
|
|
||||||
[
|
|
||||||
bossbar_prefix(
|
|
||||||
bossbar.bossbar_data.title.clone(),
|
|
||||||
namespace.clone(),
|
|
||||||
),
|
|
||||||
TextComponent::text(count.to_string()),
|
|
||||||
TextComponent::text(online_players.join(", ")),
|
|
||||||
],
|
|
||||||
))
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
Ok(count)
|
|
||||||
}
|
|
||||||
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_GET_VISIBLE_VISIBLE,
|
|
||||||
translation::bedrock::COMMANDS_BOSSBAR_GET_VISIBLE_TRUE,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
(
|
|
||||||
translation::java::COMMANDS_BOSSBAR_GET_VISIBLE_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)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
CommandValueGet::Players => {
|
||||||
|
let online_players: Vec<String> = server
|
||||||
|
.get_all_players()
|
||||||
|
.iter()
|
||||||
|
.filter(|player| bossbar.players.contains(&player.gameprofile.id))
|
||||||
|
.map(|player| player.gameprofile.name.clone())
|
||||||
|
.collect();
|
||||||
|
let count = online_players.len() as i32;
|
||||||
|
|
||||||
|
if count == 0 {
|
||||||
|
sender.send_message(TextComponent::translate_cross(
|
||||||
|
translation::java::COMMANDS_BOSSBAR_GET_PLAYERS_NONE,
|
||||||
|
translation::bedrock::COMMANDS_BOSSBAR_GET_PLAYERS_NONE,
|
||||||
|
[bossbar_prefix(bossbar.bossbar_data.title, namespace)],
|
||||||
|
));
|
||||||
|
} else {
|
||||||
|
sender.send_message(TextComponent::translate_cross(
|
||||||
|
translation::java::COMMANDS_BOSSBAR_GET_PLAYERS_SOME,
|
||||||
|
if count == 1 {
|
||||||
|
translation::bedrock::COMMANDS_BOSSBAR_GET_PLAYERS_ONE
|
||||||
|
} else {
|
||||||
|
translation::bedrock::COMMANDS_BOSSBAR_GET_PLAYERS
|
||||||
|
},
|
||||||
|
[
|
||||||
|
bossbar_prefix(bossbar.bossbar_data.title, namespace),
|
||||||
|
TextComponent::text(count.to_string()),
|
||||||
|
TextComponent::text(online_players.join(", ")),
|
||||||
|
],
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(count)
|
||||||
|
}
|
||||||
|
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),
|
||||||
|
TextComponent::text(bossbar.value.to_string()),
|
||||||
|
],
|
||||||
|
));
|
||||||
|
Ok(bossbar.value)
|
||||||
|
}
|
||||||
|
CommandValueGet::Visible => {
|
||||||
|
let (java_key, bedrock_key) = if bossbar.visible {
|
||||||
|
(
|
||||||
|
translation::java::COMMANDS_BOSSBAR_GET_VISIBLE_VISIBLE,
|
||||||
|
translation::bedrock::COMMANDS_BOSSBAR_GET_VISIBLE_TRUE,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(
|
||||||
|
translation::java::COMMANDS_BOSSBAR_GET_VISIBLE_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,
|
||||||
|
)],
|
||||||
|
));
|
||||||
|
Ok(bossbar.visible as i32)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ListExecutor;
|
struct ListExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for ListExecutor {
|
impl CommandExecutor for ListExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
server: &'a crate::server::Server,
|
server: &crate::server::Server,
|
||||||
_args: &'a ConsumedArgs<'a>,
|
_args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let bossbars = server.bossbars.lock().unwrap().get_all_bossbars();
|
||||||
let bossbars = server.bossbars.lock().await.get_all_bossbars();
|
|
||||||
|
|
||||||
if bossbars.is_empty() {
|
if bossbars.is_empty() {
|
||||||
sender
|
sender.send_message(TextComponent::translate_cross(
|
||||||
.send_message(TextComponent::translate_cross(
|
translation::java::COMMANDS_BOSSBAR_LIST_BARS_NONE,
|
||||||
translation::java::COMMANDS_BOSSBAR_LIST_BARS_NONE,
|
translation::bedrock::COMMANDS_BOSSBAR_LIST_NONE,
|
||||||
translation::bedrock::COMMANDS_BOSSBAR_LIST_NONE,
|
[],
|
||||||
[],
|
));
|
||||||
))
|
return Ok(0);
|
||||||
.await;
|
}
|
||||||
return Ok(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut bossbars_text = TextComponent::empty();
|
let mut bossbars_text = TextComponent::empty();
|
||||||
for (i, bossbar) in bossbars.iter().enumerate() {
|
for (i, bossbar) in bossbars.iter().enumerate() {
|
||||||
if i == 0 {
|
if i == 0 {
|
||||||
bossbars_text = bossbars_text.add_child(bossbar_prefix(
|
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.bossbar_data.title.clone(),
|
||||||
bossbar.namespace.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
|
sender.send_message(TextComponent::translate_cross(
|
||||||
.send_message(TextComponent::translate_cross(
|
translation::java::COMMANDS_BOSSBAR_LIST_BARS_SOME,
|
||||||
translation::java::COMMANDS_BOSSBAR_LIST_BARS_SOME,
|
translation::bedrock::COMMANDS_BOSSBAR_LIST,
|
||||||
translation::bedrock::COMMANDS_BOSSBAR_LIST,
|
[
|
||||||
[
|
TextComponent::text(bossbars.len().to_string()),
|
||||||
TextComponent::text(bossbars.len().to_string()),
|
bossbars_text,
|
||||||
bossbars_text,
|
],
|
||||||
],
|
));
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(bossbars.len() as i32)
|
Ok(bossbars.len() as i32)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct RemoveExecutor;
|
struct RemoveExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for RemoveExecutor {
|
impl CommandExecutor for RemoveExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
server: &'a crate::server::Server,
|
server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let namespace = autocomplete_consumer()
|
||||||
let namespace = autocomplete_consumer()
|
.find_arg_default_name(args)?
|
||||||
.find_arg_default_name(args)?
|
.to_string();
|
||||||
.to_string();
|
|
||||||
|
|
||||||
let Some(bossbar) = server.bossbars.lock().await.get_bossbar(&namespace) else {
|
let Some(bossbar) = server.bossbars.lock().unwrap().get_bossbar(&namespace) else {
|
||||||
return Err(handle_bossbar_error(
|
return Err(handle_bossbar_error(
|
||||||
BossbarUpdateError::InvalidResourceLocation(namespace),
|
BossbarUpdateError::InvalidResourceLocation(namespace),
|
||||||
));
|
));
|
||||||
};
|
};
|
||||||
|
|
||||||
sender
|
sender.send_message(TextComponent::translate_cross(
|
||||||
.send_message(TextComponent::translate_cross(
|
translation::java::COMMANDS_BOSSBAR_REMOVE_SUCCESS,
|
||||||
translation::java::COMMANDS_BOSSBAR_REMOVE_SUCCESS,
|
translation::bedrock::COMMANDS_BOSSBAR_REMOVE,
|
||||||
translation::bedrock::COMMANDS_BOSSBAR_REMOVE,
|
[bossbar_prefix(
|
||||||
[bossbar_prefix(
|
bossbar.bossbar_data.title,
|
||||||
bossbar.bossbar_data.title.clone(),
|
namespace.clone(),
|
||||||
namespace.clone(),
|
)],
|
||||||
)],
|
));
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let res = server
|
let res = server
|
||||||
.bossbars
|
.bossbars
|
||||||
.lock()
|
.lock()
|
||||||
.await
|
.unwrap()
|
||||||
.remove_bossbar(server, namespace);
|
.remove_bossbar(server, namespace);
|
||||||
match res {
|
match res {
|
||||||
Ok(()) => Ok(server.bossbars.lock().await.get_bossbars_len() as i32),
|
Ok(()) => Ok(server.bossbars.lock().unwrap().get_bossbars_len() as i32),
|
||||||
Err(error) => Err(handle_bossbar_error(error)),
|
Err(error) => Err(handle_bossbar_error(error)),
|
||||||
}
|
}
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -347,231 +305,201 @@ struct SetExecutor(CommandValueSet);
|
|||||||
|
|
||||||
impl CommandExecutor for SetExecutor {
|
impl CommandExecutor for SetExecutor {
|
||||||
#[expect(clippy::too_many_lines)]
|
#[expect(clippy::too_many_lines)]
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
server: &'a crate::server::Server,
|
server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let namespace = autocomplete_consumer()
|
||||||
let namespace = autocomplete_consumer()
|
.find_arg_default_name(args)?
|
||||||
.find_arg_default_name(args)?
|
.to_string();
|
||||||
.to_string();
|
|
||||||
|
|
||||||
let Some(bossbar) = server.bossbars.lock().await.get_bossbar(&namespace) else {
|
let Some(bossbar) = server.bossbars.lock().unwrap().get_bossbar(&namespace) else {
|
||||||
return Err(handle_bossbar_error(
|
return Err(handle_bossbar_error(
|
||||||
BossbarUpdateError::InvalidResourceLocation(namespace),
|
BossbarUpdateError::InvalidResourceLocation(namespace),
|
||||||
|
));
|
||||||
|
};
|
||||||
|
|
||||||
|
match self.0 {
|
||||||
|
CommandValueSet::Color => {
|
||||||
|
let color = BossbarColorArgumentConsumer.find_arg_default_name(args)?;
|
||||||
|
|
||||||
|
server
|
||||||
|
.bossbars
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.update_color(server, &namespace, *color)
|
||||||
|
.map_err(handle_bossbar_error)?;
|
||||||
|
|
||||||
|
sender.send_message(TextComponent::translate_cross(
|
||||||
|
translation::java::COMMANDS_BOSSBAR_SET_COLOR_SUCCESS,
|
||||||
|
translation::java::COMMANDS_BOSSBAR_SET_COLOR_SUCCESS,
|
||||||
|
[bossbar_prefix(bossbar.bossbar_data.title, namespace)],
|
||||||
));
|
));
|
||||||
};
|
|
||||||
|
|
||||||
match self.0 {
|
Ok(0)
|
||||||
CommandValueSet::Color => {
|
|
||||||
let color = BossbarColorArgumentConsumer.find_arg_default_name(args)?;
|
|
||||||
|
|
||||||
server
|
|
||||||
.bossbars
|
|
||||||
.lock()
|
|
||||||
.await
|
|
||||||
.update_color(server, &namespace, *color)
|
|
||||||
.map_err(handle_bossbar_error)?;
|
|
||||||
|
|
||||||
sender
|
|
||||||
.send_message(TextComponent::translate_cross(
|
|
||||||
translation::java::COMMANDS_BOSSBAR_SET_COLOR_SUCCESS,
|
|
||||||
translation::java::COMMANDS_BOSSBAR_SET_COLOR_SUCCESS,
|
|
||||||
[bossbar_prefix(
|
|
||||||
bossbar.bossbar_data.title.clone(),
|
|
||||||
namespace,
|
|
||||||
)],
|
|
||||||
))
|
|
||||||
.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())],
|
|
||||||
)));
|
|
||||||
};
|
|
||||||
|
|
||||||
server
|
|
||||||
.bossbars
|
|
||||||
.lock()
|
|
||||||
.await
|
|
||||||
.update_max(server, namespace.clone(), max_value)
|
|
||||||
.map_err(handle_bossbar_error)?;
|
|
||||||
|
|
||||||
sender
|
|
||||||
.send_message(TextComponent::translate_cross(
|
|
||||||
translation::java::COMMANDS_BOSSBAR_SET_MAX_SUCCESS,
|
|
||||||
translation::java::COMMANDS_BOSSBAR_SET_MAX_SUCCESS,
|
|
||||||
[
|
|
||||||
bossbar_prefix(bossbar.bossbar_data.title.clone(), namespace),
|
|
||||||
TextComponent::text(max_value.to_string()),
|
|
||||||
],
|
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(0)
|
|
||||||
}
|
|
||||||
CommandValueSet::Name => {
|
|
||||||
let name = TextComponentArgConsumer::find_arg(args, ARG_NAME)?;
|
|
||||||
server
|
|
||||||
.bossbars
|
|
||||||
.lock()
|
|
||||||
.await
|
|
||||||
.update_name(server, &namespace, &name)
|
|
||||||
.map_err(handle_bossbar_error)?;
|
|
||||||
|
|
||||||
sender
|
|
||||||
.send_message(TextComponent::translate_cross(
|
|
||||||
translation::java::COMMANDS_BOSSBAR_SET_NAME_SUCCESS,
|
|
||||||
translation::java::COMMANDS_BOSSBAR_SET_NAME_SUCCESS,
|
|
||||||
[bossbar_prefix(name.clone(), namespace)],
|
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(0)
|
|
||||||
}
|
|
||||||
CommandValueSet::Players(has_players) => {
|
|
||||||
if !has_players {
|
|
||||||
server
|
|
||||||
.bossbars
|
|
||||||
.lock()
|
|
||||||
.await
|
|
||||||
.set_players(server, namespace.clone(), vec![])
|
|
||||||
.map_err(handle_bossbar_error)?;
|
|
||||||
|
|
||||||
sender
|
|
||||||
.send_message(TextComponent::translate_cross(
|
|
||||||
translation::java::COMMANDS_BOSSBAR_SET_PLAYERS_SUCCESS_NONE,
|
|
||||||
translation::java::COMMANDS_BOSSBAR_SET_PLAYERS_SUCCESS_NONE,
|
|
||||||
[bossbar_prefix(
|
|
||||||
bossbar.bossbar_data.title.clone(),
|
|
||||||
namespace,
|
|
||||||
)],
|
|
||||||
))
|
|
||||||
.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();
|
|
||||||
|
|
||||||
server
|
|
||||||
.bossbars
|
|
||||||
.lock()
|
|
||||||
.await
|
|
||||||
.set_players(server, namespace.clone(), players)
|
|
||||||
.map_err(handle_bossbar_error)?;
|
|
||||||
|
|
||||||
let player_names = targets
|
|
||||||
.iter()
|
|
||||||
.map(|p| p.gameprofile.name.as_str())
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join(", ");
|
|
||||||
|
|
||||||
sender
|
|
||||||
.send_message(TextComponent::translate_cross(
|
|
||||||
translation::java::COMMANDS_BOSSBAR_SET_PLAYERS_SUCCESS_SOME,
|
|
||||||
translation::java::COMMANDS_BOSSBAR_SET_PLAYERS_SUCCESS_SOME,
|
|
||||||
[
|
|
||||||
bossbar_prefix(bossbar.bossbar_data.title.clone(), namespace),
|
|
||||||
TextComponent::text(count.to_string()),
|
|
||||||
TextComponent::text(player_names),
|
|
||||||
],
|
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(count as i32)
|
|
||||||
}
|
|
||||||
CommandValueSet::Style => {
|
|
||||||
let style = BossbarStyleArgumentConsumer.find_arg_default_name(args)?;
|
|
||||||
server
|
|
||||||
.bossbars
|
|
||||||
.lock()
|
|
||||||
.await
|
|
||||||
.update_style(server, &namespace, *style)
|
|
||||||
.map_err(handle_bossbar_error)?;
|
|
||||||
|
|
||||||
sender
|
|
||||||
.send_message(TextComponent::translate_cross(
|
|
||||||
translation::java::COMMANDS_BOSSBAR_SET_STYLE_SUCCESS,
|
|
||||||
translation::java::COMMANDS_BOSSBAR_SET_STYLE_SUCCESS,
|
|
||||||
[bossbar_prefix(
|
|
||||||
bossbar.bossbar_data.title.clone(),
|
|
||||||
namespace,
|
|
||||||
)],
|
|
||||||
))
|
|
||||||
.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())],
|
|
||||||
)));
|
|
||||||
};
|
|
||||||
|
|
||||||
server
|
|
||||||
.bossbars
|
|
||||||
.lock()
|
|
||||||
.await
|
|
||||||
.update_value(server, namespace.clone(), value)
|
|
||||||
.map_err(handle_bossbar_error)?;
|
|
||||||
|
|
||||||
sender
|
|
||||||
.send_message(TextComponent::translate_cross(
|
|
||||||
translation::java::COMMANDS_BOSSBAR_SET_VALUE_SUCCESS,
|
|
||||||
translation::java::COMMANDS_BOSSBAR_SET_VALUE_SUCCESS,
|
|
||||||
[
|
|
||||||
bossbar_prefix(bossbar.bossbar_data.title.clone(), namespace),
|
|
||||||
TextComponent::text(value.to_string()),
|
|
||||||
],
|
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(value)
|
|
||||||
}
|
|
||||||
CommandValueSet::Visible => {
|
|
||||||
let visibility = BoolArgConsumer::find_arg(args, ARG_VISIBLE)?;
|
|
||||||
|
|
||||||
server
|
|
||||||
.bossbars
|
|
||||||
.lock()
|
|
||||||
.await
|
|
||||||
.update_visibility(server, namespace.clone(), visibility)
|
|
||||||
.map_err(handle_bossbar_error)?;
|
|
||||||
|
|
||||||
let state = if visibility {
|
|
||||||
translation::java::COMMANDS_BOSSBAR_SET_VISIBLE_SUCCESS_VISIBLE
|
|
||||||
} else {
|
|
||||||
translation::java::COMMANDS_BOSSBAR_SET_VISIBLE_SUCCESS_HIDDEN
|
|
||||||
};
|
|
||||||
|
|
||||||
sender
|
|
||||||
.send_message(TextComponent::translate_cross(
|
|
||||||
state,
|
|
||||||
state,
|
|
||||||
[bossbar_prefix(
|
|
||||||
bossbar.bossbar_data.title.clone(),
|
|
||||||
namespace,
|
|
||||||
)],
|
|
||||||
))
|
|
||||||
.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())],
|
||||||
|
)));
|
||||||
|
};
|
||||||
|
|
||||||
|
server
|
||||||
|
.bossbars
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.update_max(server, namespace.clone(), max_value)
|
||||||
|
.map_err(handle_bossbar_error)?;
|
||||||
|
|
||||||
|
sender.send_message(TextComponent::translate_cross(
|
||||||
|
translation::java::COMMANDS_BOSSBAR_SET_MAX_SUCCESS,
|
||||||
|
translation::java::COMMANDS_BOSSBAR_SET_MAX_SUCCESS,
|
||||||
|
[
|
||||||
|
bossbar_prefix(bossbar.bossbar_data.title, namespace),
|
||||||
|
TextComponent::text(max_value.to_string()),
|
||||||
|
],
|
||||||
|
));
|
||||||
|
|
||||||
|
Ok(0)
|
||||||
|
}
|
||||||
|
CommandValueSet::Name => {
|
||||||
|
let name = TextComponentArgConsumer::find_arg(args, ARG_NAME)?;
|
||||||
|
server
|
||||||
|
.bossbars
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.update_name(server, &namespace, &name)
|
||||||
|
.map_err(handle_bossbar_error)?;
|
||||||
|
|
||||||
|
sender.send_message(TextComponent::translate_cross(
|
||||||
|
translation::java::COMMANDS_BOSSBAR_SET_NAME_SUCCESS,
|
||||||
|
translation::java::COMMANDS_BOSSBAR_SET_NAME_SUCCESS,
|
||||||
|
[bossbar_prefix(name, namespace)],
|
||||||
|
));
|
||||||
|
|
||||||
|
Ok(0)
|
||||||
|
}
|
||||||
|
CommandValueSet::Players(has_players) => {
|
||||||
|
if !has_players {
|
||||||
|
server
|
||||||
|
.bossbars
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.set_players(server, namespace.clone(), vec![])
|
||||||
|
.map_err(handle_bossbar_error)?;
|
||||||
|
|
||||||
|
sender.send_message(TextComponent::translate_cross(
|
||||||
|
translation::java::COMMANDS_BOSSBAR_SET_PLAYERS_SUCCESS_NONE,
|
||||||
|
translation::java::COMMANDS_BOSSBAR_SET_PLAYERS_SUCCESS_NONE,
|
||||||
|
[bossbar_prefix(bossbar.bossbar_data.title, namespace)],
|
||||||
|
));
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
server
|
||||||
|
.bossbars
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.set_players(server, namespace.clone(), players)
|
||||||
|
.map_err(handle_bossbar_error)?;
|
||||||
|
|
||||||
|
let player_names = targets
|
||||||
|
.iter()
|
||||||
|
.map(|p| p.gameprofile.name.as_str())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ");
|
||||||
|
|
||||||
|
sender.send_message(TextComponent::translate_cross(
|
||||||
|
translation::java::COMMANDS_BOSSBAR_SET_PLAYERS_SUCCESS_SOME,
|
||||||
|
translation::java::COMMANDS_BOSSBAR_SET_PLAYERS_SUCCESS_SOME,
|
||||||
|
[
|
||||||
|
bossbar_prefix(bossbar.bossbar_data.title, namespace),
|
||||||
|
TextComponent::text(count.to_string()),
|
||||||
|
TextComponent::text(player_names),
|
||||||
|
],
|
||||||
|
));
|
||||||
|
|
||||||
|
Ok(count as i32)
|
||||||
|
}
|
||||||
|
CommandValueSet::Style => {
|
||||||
|
let style = BossbarStyleArgumentConsumer.find_arg_default_name(args)?;
|
||||||
|
server
|
||||||
|
.bossbars
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.update_style(server, &namespace, *style)
|
||||||
|
.map_err(handle_bossbar_error)?;
|
||||||
|
|
||||||
|
sender.send_message(TextComponent::translate_cross(
|
||||||
|
translation::java::COMMANDS_BOSSBAR_SET_STYLE_SUCCESS,
|
||||||
|
translation::java::COMMANDS_BOSSBAR_SET_STYLE_SUCCESS,
|
||||||
|
[bossbar_prefix(bossbar.bossbar_data.title, namespace)],
|
||||||
|
));
|
||||||
|
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())],
|
||||||
|
)));
|
||||||
|
};
|
||||||
|
|
||||||
|
server
|
||||||
|
.bossbars
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.update_value(server, namespace.clone(), value)
|
||||||
|
.map_err(handle_bossbar_error)?;
|
||||||
|
|
||||||
|
sender.send_message(TextComponent::translate_cross(
|
||||||
|
translation::java::COMMANDS_BOSSBAR_SET_VALUE_SUCCESS,
|
||||||
|
translation::java::COMMANDS_BOSSBAR_SET_VALUE_SUCCESS,
|
||||||
|
[
|
||||||
|
bossbar_prefix(bossbar.bossbar_data.title, namespace),
|
||||||
|
TextComponent::text(value.to_string()),
|
||||||
|
],
|
||||||
|
));
|
||||||
|
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
CommandValueSet::Visible => {
|
||||||
|
let visibility = BoolArgConsumer::find_arg(args, ARG_VISIBLE)?;
|
||||||
|
|
||||||
|
server
|
||||||
|
.bossbars
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.update_visibility(server, namespace.clone(), visibility)
|
||||||
|
.map_err(handle_bossbar_error)?;
|
||||||
|
|
||||||
|
let state = if visibility {
|
||||||
|
translation::java::COMMANDS_BOSSBAR_SET_VISIBLE_SUCCESS_VISIBLE
|
||||||
|
} else {
|
||||||
|
translation::java::COMMANDS_BOSSBAR_SET_VISIBLE_SUCCESS_HIDDEN
|
||||||
|
};
|
||||||
|
|
||||||
|
sender.send_message(TextComponent::translate_cross(
|
||||||
|
state,
|
||||||
|
state,
|
||||||
|
[bossbar_prefix(bossbar.bossbar_data.title, namespace)],
|
||||||
|
));
|
||||||
|
|
||||||
|
Ok(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -106,22 +106,22 @@ fn test_and_clear(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn command_result(
|
fn command_result(
|
||||||
sender: &CommandSender,
|
sender: &CommandSender,
|
||||||
item_count: i32,
|
item_count: i32,
|
||||||
max_count: i32,
|
max_count: i32,
|
||||||
targets: &[Arc<Player>],
|
targets: &[Arc<Player>],
|
||||||
) -> Result<i32, CommandError> {
|
) -> Result<i32, CommandError> {
|
||||||
match clear_command_text_output(item_count, max_count, targets).await {
|
match clear_command_text_output(item_count, max_count, targets) {
|
||||||
Ok(success) => {
|
Ok(success) => {
|
||||||
sender.send_message(success).await;
|
sender.send_message(success);
|
||||||
Ok(item_count)
|
Ok(item_count)
|
||||||
}
|
}
|
||||||
Err(failure) => Err(CommandError::CommandFailed(failure)),
|
Err(failure) => Err(CommandError::CommandFailed(failure)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn clear_command_text_output(
|
fn clear_command_text_output(
|
||||||
item_count: i32,
|
item_count: i32,
|
||||||
max_count: i32,
|
max_count: i32,
|
||||||
targets: &[Arc<Player>],
|
targets: &[Arc<Player>],
|
||||||
@@ -179,103 +179,94 @@ const fn count_consumer() -> BoundedNumArgumentConsumer<i32> {
|
|||||||
struct SelfExecutor;
|
struct SelfExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for SelfExecutor {
|
impl CommandExecutor for SelfExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
_server: &'a crate::server::Server,
|
_server: &crate::server::Server,
|
||||||
_args: &'a ConsumedArgs<'a>,
|
_args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let target = sender.as_player().ok_or(CommandError::InvalidRequirement)?;
|
||||||
let target = sender.as_player().ok_or(CommandError::InvalidRequirement)?;
|
|
||||||
|
|
||||||
let items_cleared = clear_player(&target, &ItemPredicate::Any, MAX_NO_UPPER_LIMIT);
|
let items_cleared = clear_player(&target, &ItemPredicate::Any, MAX_NO_UPPER_LIMIT);
|
||||||
|
|
||||||
command_result(sender, items_cleared, MAX_NO_UPPER_LIMIT, &[target]).await
|
command_result(sender, items_cleared, MAX_NO_UPPER_LIMIT, &[target])
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Executor;
|
struct Executor;
|
||||||
|
|
||||||
impl CommandExecutor for Executor {
|
impl CommandExecutor for Executor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
_server: &'a crate::server::Server,
|
_server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
};
|
||||||
};
|
|
||||||
|
|
||||||
let mut total_items_cleared = 0;
|
let mut total_items_cleared = 0;
|
||||||
for target in targets {
|
for target in targets {
|
||||||
total_items_cleared +=
|
total_items_cleared += clear_player(target, &ItemPredicate::Any, MAX_NO_UPPER_LIMIT);
|
||||||
clear_player(target, &ItemPredicate::Any, MAX_NO_UPPER_LIMIT);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
command_result(sender, total_items_cleared, MAX_NO_UPPER_LIMIT, targets).await
|
command_result(sender, total_items_cleared, MAX_NO_UPPER_LIMIT, targets)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ItemExecutor;
|
struct ItemExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for ItemExecutor {
|
impl CommandExecutor for ItemExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
_server: &'a crate::server::Server,
|
_server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
};
|
||||||
};
|
|
||||||
|
|
||||||
let item = ItemPredicateArgumentConsumer::find_arg(args, ARG_ITEM)?;
|
let item = ItemPredicateArgumentConsumer::find_arg(args, ARG_ITEM)?;
|
||||||
|
|
||||||
let mut total_items_cleared = 0;
|
let mut total_items_cleared = 0;
|
||||||
for target in targets {
|
for target in targets {
|
||||||
total_items_cleared += clear_player(target, &item, MAX_NO_UPPER_LIMIT);
|
total_items_cleared += clear_player(target, &item, MAX_NO_UPPER_LIMIT);
|
||||||
}
|
}
|
||||||
|
|
||||||
command_result(sender, total_items_cleared, MAX_NO_UPPER_LIMIT, targets).await
|
command_result(sender, total_items_cleared, MAX_NO_UPPER_LIMIT, targets)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ItemCountExecutor;
|
struct ItemCountExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for ItemCountExecutor {
|
impl CommandExecutor for ItemCountExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
_server: &'a crate::server::Server,
|
_server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
||||||
let Some(Arg::Players(targets)) = args.get(&ARG_TARGETS) else {
|
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
};
|
||||||
};
|
|
||||||
|
|
||||||
let item = ItemPredicateArgumentConsumer::find_arg(args, ARG_ITEM)?;
|
let item = ItemPredicateArgumentConsumer::find_arg(args, ARG_ITEM)?;
|
||||||
let Ok(max) = count_consumer().find_arg_default_name(args)? else {
|
let Ok(max) = count_consumer().find_arg_default_name(args)? else {
|
||||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||||
translation::java::PARSING_INT_INVALID,
|
translation::java::PARSING_INT_INVALID,
|
||||||
translation::java::PARSING_INT_INVALID,
|
translation::java::PARSING_INT_INVALID,
|
||||||
[TextComponent::text(i32::MAX.to_string())],
|
[TextComponent::text(i32::MAX.to_string())],
|
||||||
)));
|
)));
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut total_items_cleared = 0;
|
let mut total_items_cleared = 0;
|
||||||
for target in targets {
|
for target in targets {
|
||||||
total_items_cleared += clear_player(target, &item, max);
|
total_items_cleared += clear_player(target, &item, max);
|
||||||
}
|
}
|
||||||
|
|
||||||
command_result(sender, total_items_cleared, max, targets).await
|
command_result(sender, total_items_cleared, max, targets)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -76,187 +76,182 @@ struct ClonedBlock {
|
|||||||
|
|
||||||
impl CommandExecutor for CloneExecutor {
|
impl CommandExecutor for CloneExecutor {
|
||||||
#[expect(clippy::too_many_lines)]
|
#[expect(clippy::too_many_lines)]
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let begin = BlockPosArgumentType::get_block_pos(context, ARG_BEGIN)?;
|
||||||
let begin = BlockPosArgumentType::get_block_pos(context, ARG_BEGIN)?;
|
let end = BlockPosArgumentType::get_block_pos(context, ARG_END)?;
|
||||||
let end = BlockPosArgumentType::get_block_pos(context, ARG_END)?;
|
let dest = BlockPosArgumentType::get_block_pos(context, ARG_DEST)?;
|
||||||
let dest = BlockPosArgumentType::get_block_pos(context, ARG_DEST)?;
|
|
||||||
|
|
||||||
let filter_block = if self.has_filter {
|
let filter_block = if self.has_filter {
|
||||||
Some(BlockArgumentType::get(context, ARG_FILTER)?)
|
Some(BlockArgumentType::get(context, ARG_FILTER)?)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
let min_x = begin.0.x.min(end.0.x);
|
let min_x = begin.0.x.min(end.0.x);
|
||||||
let max_x = begin.0.x.max(end.0.x);
|
let max_x = begin.0.x.max(end.0.x);
|
||||||
let min_y = begin.0.y.min(end.0.y);
|
let min_y = begin.0.y.min(end.0.y);
|
||||||
let max_y = begin.0.y.max(end.0.y);
|
let max_y = begin.0.y.max(end.0.y);
|
||||||
let min_z = begin.0.z.min(end.0.z);
|
let min_z = begin.0.z.min(end.0.z);
|
||||||
let max_z = begin.0.z.max(end.0.z);
|
let max_z = begin.0.z.max(end.0.z);
|
||||||
|
|
||||||
let size_x = max_x - min_x + 1;
|
let size_x = max_x - min_x + 1;
|
||||||
let size_y = max_y - min_y + 1;
|
let size_y = max_y - min_y + 1;
|
||||||
let size_z = max_z - min_z + 1;
|
let size_z = max_z - min_z + 1;
|
||||||
|
|
||||||
let volume = size_x * size_y * size_z;
|
let volume = size_x * size_y * size_z;
|
||||||
|
|
||||||
if volume > 32768 {
|
if volume > 32768 {
|
||||||
return Err(TOOBIG_ERROR.create_without_context_args_slice(&[
|
return Err(TOOBIG_ERROR.create_without_context_args_slice(&[
|
||||||
TextComponent::text("32768"),
|
TextComponent::text("32768"),
|
||||||
TextComponent::text(volume.to_string()),
|
TextComponent::text(volume.to_string()),
|
||||||
]));
|
]));
|
||||||
}
|
}
|
||||||
|
|
||||||
let dest_min_x = dest.0.x;
|
let dest_min_x = dest.0.x;
|
||||||
let dest_min_y = dest.0.y;
|
let dest_min_y = dest.0.y;
|
||||||
let dest_min_z = dest.0.z;
|
let dest_min_z = dest.0.z;
|
||||||
let dest_max_x = dest_min_x + size_x - 1;
|
let dest_max_x = dest_min_x + size_x - 1;
|
||||||
let dest_max_y = dest_min_y + size_y - 1;
|
let dest_max_y = dest_min_y + size_y - 1;
|
||||||
let dest_max_z = dest_min_z + size_z - 1;
|
let dest_max_z = dest_min_z + size_z - 1;
|
||||||
|
|
||||||
let overlap = !(dest_max_x < min_x
|
let overlap = !(dest_max_x < min_x
|
||||||
|| dest_min_x > max_x
|
|| dest_min_x > max_x
|
||||||
|| dest_max_y < min_y
|
|| dest_max_y < min_y
|
||||||
|| dest_min_y > max_y
|
|| dest_min_y > max_y
|
||||||
|| dest_max_z < min_z
|
|| dest_max_z < min_z
|
||||||
|| dest_min_z > max_z);
|
|| dest_min_z > max_z);
|
||||||
|
|
||||||
if overlap && self.clone_mode != CloneMode::Force {
|
if overlap && self.clone_mode != CloneMode::Force {
|
||||||
return Err(OVERLAP_ERROR.create_without_context());
|
return Err(OVERLAP_ERROR.create_without_context());
|
||||||
}
|
}
|
||||||
|
|
||||||
let world = context.source.world();
|
let world = context.source.world();
|
||||||
|
|
||||||
let limit_check_pos_1 = BlockPos::new(min_x, min_y, min_z);
|
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_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_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);
|
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)
|
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_2)
|
||||||
|| !world.is_in_build_limit(limit_check_pos_3)
|
|| !world.is_in_build_limit(limit_check_pos_3)
|
||||||
|| !world.is_in_build_limit(limit_check_pos_4)
|
|| !world.is_in_build_limit(limit_check_pos_4)
|
||||||
{
|
{
|
||||||
return Err(OUT_OF_WORLD_ERROR.create_without_context());
|
return Err(OUT_OF_WORLD_ERROR.create_without_context());
|
||||||
}
|
}
|
||||||
|
|
||||||
for cx in (min_x >> 4)..=(max_x >> 4) {
|
for cx in (min_x >> 4)..=(max_x >> 4) {
|
||||||
for cz in (min_z >> 4)..=(max_z >> 4) {
|
for cz in (min_z >> 4)..=(max_z >> 4) {
|
||||||
let chunk_pos = Vector2::new(cx, cz);
|
let chunk_pos = Vector2::new(cx, cz);
|
||||||
if world.level.read_chunk_sync(&chunk_pos, |_| ()).is_none() {
|
if world.level.read_chunk_sync(&chunk_pos, |_| ()).is_none() {
|
||||||
return Err(NOT_LOADED_ERROR.create_without_context());
|
return Err(NOT_LOADED_ERROR.create_without_context());
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for cx in (dest_min_x >> 4)..=(dest_max_x >> 4) {
|
for cx in (dest_min_x >> 4)..=(dest_max_x >> 4) {
|
||||||
for cz in (dest_min_z >> 4)..=(dest_max_z >> 4) {
|
for cz in (dest_min_z >> 4)..=(dest_max_z >> 4) {
|
||||||
let chunk_pos = Vector2::new(cx, cz);
|
let chunk_pos = Vector2::new(cx, cz);
|
||||||
if world.level.read_chunk_sync(&chunk_pos, |_| ()).is_none() {
|
if world.level.read_chunk_sync(&chunk_pos, |_| ()).is_none() {
|
||||||
return Err(NOT_LOADED_ERROR.create_without_context());
|
return Err(NOT_LOADED_ERROR.create_without_context());
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let mut blocks_to_clone = Vec::new();
|
let mut blocks_to_clone = Vec::new();
|
||||||
|
|
||||||
for x in 0..size_x {
|
for x in 0..size_x {
|
||||||
for y in 0..size_y {
|
for y in 0..size_y {
|
||||||
for z in 0..size_z {
|
for z in 0..size_z {
|
||||||
let src_pos = BlockPos::new(min_x + x, min_y + y, min_z + z);
|
let src_pos = BlockPos::new(min_x + x, min_y + y, min_z + z);
|
||||||
let dest_pos =
|
let dest_pos = BlockPos::new(dest_min_x + x, dest_min_y + y, dest_min_z + z);
|
||||||
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 state_id = world.get_block_state_id(&src_pos);
|
||||||
|
|
||||||
let should_clone = match self.mask_mode {
|
let should_clone = match self.mask_mode {
|
||||||
MaskMode::Replace => true,
|
MaskMode::Replace => true,
|
||||||
MaskMode::Masked => !pumpkin_data::block_properties::is_air(state_id),
|
MaskMode::Masked => !pumpkin_data::block_properties::is_air(state_id),
|
||||||
MaskMode::Filtered => {
|
MaskMode::Filtered => {
|
||||||
let block = Block::from_state_id(state_id);
|
let block = Block::from_state_id(state_id);
|
||||||
filter_block.is_some_and(|f| block.id == f.id)
|
filter_block.is_some_and(|f| block.id == f.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,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if should_clone {
|
||||||
|
let block_entity_nbt = world.get_block_entity(&src_pos).map(|be| {
|
||||||
|
let mut nbt = NbtCompound::new();
|
||||||
|
if let Ok(handle) = tokio::runtime::Handle::try_current() {
|
||||||
|
tokio::task::block_in_place(|| {
|
||||||
|
handle.block_on(be.write_internal(&mut nbt));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
nbt
|
||||||
|
});
|
||||||
|
|
||||||
|
blocks_to_clone.push(ClonedBlock {
|
||||||
|
src_pos,
|
||||||
|
dest_pos,
|
||||||
|
state_id,
|
||||||
|
block_entity_nbt,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let mut count = 0;
|
let mut count = 0;
|
||||||
|
for block in &blocks_to_clone {
|
||||||
|
world.set_block_state(&block.dest_pos, block.state_id, BlockFlags::NOTIFY_ALL);
|
||||||
|
|
||||||
|
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 {
|
for block in &blocks_to_clone {
|
||||||
world.set_block_state(&block.dest_pos, block.state_id, BlockFlags::NOTIFY_ALL);
|
if !is_dest_pos(&block.src_pos) {
|
||||||
|
world.set_block_state(
|
||||||
if let Some(nbt) = &block.block_entity_nbt {
|
&block.src_pos,
|
||||||
let mut new_nbt = nbt.clone();
|
BlockStateId::AIR,
|
||||||
new_nbt.put_int("x", block.dest_pos.0.x);
|
BlockFlags::NOTIFY_ALL,
|
||||||
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,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
context
|
context.source.send_feedback(
|
||||||
.source
|
TextComponent::translate_cross(
|
||||||
.send_feedback(
|
translation::java::COMMANDS_CLONE_SUCCESS,
|
||||||
TextComponent::translate_cross(
|
translation::bedrock::COMMANDS_CLONE_SUCCESS,
|
||||||
translation::java::COMMANDS_CLONE_SUCCESS,
|
[TextComponent::text(count.to_string())],
|
||||||
translation::bedrock::COMMANDS_CLONE_SUCCESS,
|
),
|
||||||
[TextComponent::text(count.to_string())],
|
true,
|
||||||
),
|
);
|
||||||
true,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(count)
|
Ok(count)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ const fn amount_consumer() -> BoundedNumArgumentConsumer<f32> {
|
|||||||
struct LocationExecutor;
|
struct LocationExecutor;
|
||||||
struct EntityExecutor(bool);
|
struct EntityExecutor(bool);
|
||||||
|
|
||||||
async fn send_damage_result(
|
fn send_damage_result(
|
||||||
sender: &CommandSender,
|
sender: &CommandSender,
|
||||||
success: bool,
|
success: bool,
|
||||||
amount: f32,
|
amount: f32,
|
||||||
@@ -46,89 +46,77 @@ async fn send_damage_result(
|
|||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
sender
|
sender.send_message(TextComponent::translate_cross(
|
||||||
.send_message(TextComponent::translate_cross(
|
translation::java::COMMANDS_DAMAGE_SUCCESS,
|
||||||
translation::java::COMMANDS_DAMAGE_SUCCESS,
|
translation::bedrock::COMMANDS_DAMAGE_SUCCESS,
|
||||||
translation::bedrock::COMMANDS_DAMAGE_SUCCESS,
|
[TextComponent::text(amount.to_string()), target_name],
|
||||||
[TextComponent::text(amount.to_string()), target_name],
|
));
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(1) // not arbitrary, this is what vanilla does
|
Ok(1) // not arbitrary, this is what vanilla does
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CommandExecutor for LocationExecutor {
|
impl CommandExecutor for LocationExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
_server: &'a crate::server::Server,
|
_server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let target = EntityArgumentConsumer::find_arg(args, ARG_TARGET)?;
|
||||||
let target = EntityArgumentConsumer::find_arg(args, ARG_TARGET)?;
|
|
||||||
|
|
||||||
let amount = BoundedNumArgumentConsumer::<f32>::find_arg(args, ARG_AMOUNT)??;
|
let amount = BoundedNumArgumentConsumer::<f32>::find_arg(args, ARG_AMOUNT)??;
|
||||||
|
|
||||||
let damage_type =
|
let damage_type = args
|
||||||
args.get(ARG_DAMAGE_TYPE)
|
.get(ARG_DAMAGE_TYPE)
|
||||||
.map_or(DamageType::GENERIC, |arg| match arg {
|
.map_or(DamageType::GENERIC, |arg| match arg {
|
||||||
Arg::DamageType(dt) => *dt,
|
Arg::DamageType(dt) => *dt,
|
||||||
_ => DamageType::GENERIC,
|
_ => DamageType::GENERIC,
|
||||||
});
|
});
|
||||||
|
|
||||||
let location = Position3DArgumentConsumer::find_arg(args, ARG_LOCATION)?;
|
let location = Position3DArgumentConsumer::find_arg(args, ARG_LOCATION)?;
|
||||||
|
|
||||||
let success = target.damage_with_context(
|
let success =
|
||||||
&*target,
|
target.damage_with_context(&*target, amount, damage_type, Some(location), None, None);
|
||||||
amount,
|
|
||||||
damage_type,
|
|
||||||
Some(location),
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
);
|
|
||||||
|
|
||||||
send_damage_result(sender, success, amount, target.get_display_name()).await
|
send_damage_result(sender, success, amount, target.get_display_name())
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CommandExecutor for EntityExecutor {
|
impl CommandExecutor for EntityExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
_server: &'a crate::server::Server,
|
_server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let target = EntityArgumentConsumer::find_arg(args, ARG_TARGET)?;
|
||||||
let target = EntityArgumentConsumer::find_arg(args, ARG_TARGET)?;
|
|
||||||
|
|
||||||
let amount = BoundedNumArgumentConsumer::<f32>::find_arg(args, ARG_AMOUNT)??;
|
let amount = BoundedNumArgumentConsumer::<f32>::find_arg(args, ARG_AMOUNT)??;
|
||||||
|
|
||||||
let damage_type =
|
let damage_type = args
|
||||||
args.get(ARG_DAMAGE_TYPE)
|
.get(ARG_DAMAGE_TYPE)
|
||||||
.map_or(DamageType::GENERIC, |arg| match arg {
|
.map_or(DamageType::GENERIC, |arg| match arg {
|
||||||
Arg::DamageType(dt) => *dt,
|
Arg::DamageType(dt) => *dt,
|
||||||
_ => DamageType::GENERIC,
|
_ => DamageType::GENERIC,
|
||||||
});
|
});
|
||||||
|
|
||||||
let source = EntityArgumentConsumer::find_arg(args, ARG_ENTITY).ok();
|
let source = EntityArgumentConsumer::find_arg(args, ARG_ENTITY).ok();
|
||||||
let cause = if self.0 {
|
let cause = if self.0 {
|
||||||
EntityArgumentConsumer::find_arg(args, ARG_CAUSE).ok()
|
EntityArgumentConsumer::find_arg(args, ARG_CAUSE).ok()
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
let success = target.damage_with_context(
|
let success = target.damage_with_context(
|
||||||
&*target,
|
&*target,
|
||||||
amount,
|
amount,
|
||||||
damage_type,
|
damage_type,
|
||||||
None,
|
None,
|
||||||
source.as_ref().map(|e| e.as_ref() as &dyn EntityBase),
|
source.as_ref().map(|e| e.as_ref() as &dyn EntityBase),
|
||||||
cause.as_ref().map(|e| e.as_ref() as &dyn EntityBase),
|
cause.as_ref().map(|e| e.as_ref() as &dyn EntityBase),
|
||||||
);
|
);
|
||||||
|
|
||||||
send_damage_result(sender, success, amount, target.get_display_name()).await
|
send_damage_result(sender, success, amount, target.get_display_name())
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,18 +22,16 @@ const ARG_ENTITY: &str = "entity";
|
|||||||
struct GetEntityDataExecutor;
|
struct GetEntityDataExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for GetEntityDataExecutor {
|
impl CommandExecutor for GetEntityDataExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
_server: &'a crate::server::Server,
|
_server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let Some(Arg::Entity(entity)) = args.get(&ARG_ENTITY) else {
|
||||||
let Some(Arg::Entity(entity)) = args.get(&ARG_ENTITY) else {
|
return Err(InvalidConsumption(Some(ARG_ENTITY.into())));
|
||||||
return Err(InvalidConsumption(Some(ARG_ENTITY.into())));
|
};
|
||||||
};
|
display_data(entity.as_ref(), entity.get_display_name(), sender)
|
||||||
display_data(entity.as_ref(), entity.get_display_name(), sender).await
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -216,7 +214,7 @@ pub fn snbt_colorful_display(tag: &NbtTag, depth: usize) -> Result<TextComponent
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn display_data(
|
fn display_data(
|
||||||
entity: &dyn EntityBase,
|
entity: &dyn EntityBase,
|
||||||
target_name: TextComponent,
|
target_name: TextComponent,
|
||||||
sender: &CommandSender,
|
sender: &CommandSender,
|
||||||
@@ -228,13 +226,11 @@ async fn display_data(
|
|||||||
let result = get_i32_result(&tag)?;
|
let result = get_i32_result(&tag)?;
|
||||||
let display = snbt_colorful_display(&tag, 0)
|
let display = snbt_colorful_display(&tag, 0)
|
||||||
.map_err(|string| CommandError::CommandFailed(TextComponent::text(string)))?;
|
.map_err(|string| CommandError::CommandFailed(TextComponent::text(string)))?;
|
||||||
sender
|
sender.send_message(TextComponent::translate_cross(
|
||||||
.send_message(TextComponent::translate_cross(
|
translation::java::COMMANDS_DATA_ENTITY_QUERY,
|
||||||
translation::java::COMMANDS_DATA_ENTITY_QUERY,
|
translation::java::COMMANDS_DATA_ENTITY_QUERY,
|
||||||
translation::java::COMMANDS_DATA_ENTITY_QUERY,
|
[target_name, display],
|
||||||
[target_name, display],
|
));
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(result)
|
Ok(result)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -137,58 +137,54 @@ fn format_pack(name: &str) -> TextComponent {
|
|||||||
struct AvailablePackSuggestionProvider;
|
struct AvailablePackSuggestionProvider;
|
||||||
|
|
||||||
impl SuggestionProvider for AvailablePackSuggestionProvider {
|
impl SuggestionProvider for AvailablePackSuggestionProvider {
|
||||||
fn suggest<'a>(
|
fn suggest(
|
||||||
&'a self,
|
&self,
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
mut builder: SuggestionsBuilder,
|
mut builder: SuggestionsBuilder,
|
||||||
) -> SuggestionProviderResult<'a> {
|
) -> SuggestionProviderResult {
|
||||||
Box::pin(async move {
|
let server = context.server();
|
||||||
let server = context.server();
|
for pack in get_available_packs(server) {
|
||||||
for pack in get_available_packs(server) {
|
if pack.contains(' ') || pack.contains('/') {
|
||||||
if pack.contains(' ') || pack.contains('/') {
|
builder = builder.suggest(format!("\"{pack}\""));
|
||||||
builder = builder.suggest(format!("\"{pack}\""));
|
} else {
|
||||||
|
builder = builder.suggest(pack.clone());
|
||||||
|
}
|
||||||
|
if let Some(short) = pack.strip_prefix("file/") {
|
||||||
|
if short.contains(' ') {
|
||||||
|
builder = builder.suggest(format!("\"{short}\""));
|
||||||
} else {
|
} else {
|
||||||
builder = builder.suggest(pack.clone());
|
builder = builder.suggest(short.to_string());
|
||||||
}
|
|
||||||
if let Some(short) = pack.strip_prefix("file/") {
|
|
||||||
if short.contains(' ') {
|
|
||||||
builder = builder.suggest(format!("\"{short}\""));
|
|
||||||
} else {
|
|
||||||
builder = builder.suggest(short.to_string());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
builder.build()
|
}
|
||||||
})
|
builder.build()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct EnabledPackSuggestionProvider;
|
struct EnabledPackSuggestionProvider;
|
||||||
|
|
||||||
impl SuggestionProvider for EnabledPackSuggestionProvider {
|
impl SuggestionProvider for EnabledPackSuggestionProvider {
|
||||||
fn suggest<'a>(
|
fn suggest(
|
||||||
&'a self,
|
&self,
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
mut builder: SuggestionsBuilder,
|
mut builder: SuggestionsBuilder,
|
||||||
) -> SuggestionProviderResult<'a> {
|
) -> SuggestionProviderResult {
|
||||||
Box::pin(async move {
|
let server = context.server();
|
||||||
let server = context.server();
|
for pack in get_enabled_packs(server) {
|
||||||
for pack in get_enabled_packs(server) {
|
if pack.contains(' ') || pack.contains('/') {
|
||||||
if pack.contains(' ') || pack.contains('/') {
|
builder = builder.suggest(format!("\"{pack}\""));
|
||||||
builder = builder.suggest(format!("\"{pack}\""));
|
} else {
|
||||||
|
builder = builder.suggest(pack.clone());
|
||||||
|
}
|
||||||
|
if let Some(short) = pack.strip_prefix("file/") {
|
||||||
|
if short.contains(' ') {
|
||||||
|
builder = builder.suggest(format!("\"{short}\""));
|
||||||
} else {
|
} else {
|
||||||
builder = builder.suggest(pack.clone());
|
builder = builder.suggest(short.to_string());
|
||||||
}
|
|
||||||
if let Some(short) = pack.strip_prefix("file/") {
|
|
||||||
if short.contains(' ') {
|
|
||||||
builder = builder.suggest(format!("\"{short}\""));
|
|
||||||
} else {
|
|
||||||
builder = builder.suggest(short.to_string());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
builder.build()
|
}
|
||||||
})
|
builder.build()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -202,94 +198,80 @@ enum ListFilter {
|
|||||||
struct DatapackListExecutor(ListFilter);
|
struct DatapackListExecutor(ListFilter);
|
||||||
|
|
||||||
impl CommandExecutor for DatapackListExecutor {
|
impl CommandExecutor for DatapackListExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let server = context.server();
|
||||||
let server = context.server();
|
let enabled = get_enabled_packs(server);
|
||||||
let enabled = get_enabled_packs(server);
|
let available = get_available_packs(server);
|
||||||
let available = get_available_packs(server);
|
|
||||||
|
|
||||||
match self.0 {
|
match self.0 {
|
||||||
ListFilter::All => {
|
ListFilter::All => {
|
||||||
send_enabled_list(context, &enabled).await;
|
send_enabled_list(context, &enabled);
|
||||||
send_available_list(context, &available).await;
|
send_available_list(context, &available);
|
||||||
Ok(enabled.len() as i32)
|
Ok(enabled.len() as i32)
|
||||||
}
|
|
||||||
ListFilter::Enabled => {
|
|
||||||
send_enabled_list(context, &enabled).await;
|
|
||||||
Ok(enabled.len() as i32)
|
|
||||||
}
|
|
||||||
ListFilter::Available => {
|
|
||||||
send_available_list(context, &available).await;
|
|
||||||
Ok(available.len() as i32)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
ListFilter::Enabled => {
|
||||||
|
send_enabled_list(context, &enabled);
|
||||||
|
Ok(enabled.len() as i32)
|
||||||
|
}
|
||||||
|
ListFilter::Available => {
|
||||||
|
send_available_list(context, &available);
|
||||||
|
Ok(available.len() as i32)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_enabled_list(context: &CommandContext<'_>, enabled: &[String]) {
|
fn send_enabled_list(context: &CommandContext<'_>, enabled: &[String]) {
|
||||||
if enabled.is_empty() {
|
if enabled.is_empty() {
|
||||||
context
|
context.source.send_feedback(
|
||||||
.source
|
TextComponent::translate_cross(
|
||||||
.send_feedback(
|
translation::java::COMMANDS_DATAPACK_LIST_ENABLED_NONE,
|
||||||
TextComponent::translate_cross(
|
translation::java::COMMANDS_DATAPACK_LIST_ENABLED_NONE,
|
||||||
translation::java::COMMANDS_DATAPACK_LIST_ENABLED_NONE,
|
[],
|
||||||
translation::java::COMMANDS_DATAPACK_LIST_ENABLED_NONE,
|
),
|
||||||
[],
|
false,
|
||||||
),
|
);
|
||||||
false,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
} else {
|
} else {
|
||||||
let packs_component =
|
let packs_component =
|
||||||
TextComponent::join_with_comma(enabled.iter().map(|p| format_pack(p)).collect());
|
TextComponent::join_with_comma(enabled.iter().map(|p| format_pack(p)).collect());
|
||||||
context
|
context.source.send_feedback(
|
||||||
.source
|
TextComponent::translate_cross(
|
||||||
.send_feedback(
|
translation::java::COMMANDS_DATAPACK_LIST_ENABLED_SUCCESS,
|
||||||
TextComponent::translate_cross(
|
translation::java::COMMANDS_DATAPACK_LIST_ENABLED_SUCCESS,
|
||||||
translation::java::COMMANDS_DATAPACK_LIST_ENABLED_SUCCESS,
|
[
|
||||||
translation::java::COMMANDS_DATAPACK_LIST_ENABLED_SUCCESS,
|
TextComponent::text(enabled.len().to_string()),
|
||||||
[
|
packs_component,
|
||||||
TextComponent::text(enabled.len().to_string()),
|
],
|
||||||
packs_component,
|
),
|
||||||
],
|
false,
|
||||||
),
|
);
|
||||||
false,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_available_list(context: &CommandContext<'_>, available: &[String]) {
|
fn send_available_list(context: &CommandContext<'_>, available: &[String]) {
|
||||||
if available.is_empty() {
|
if available.is_empty() {
|
||||||
context
|
context.source.send_feedback(
|
||||||
.source
|
TextComponent::translate_cross(
|
||||||
.send_feedback(
|
translation::java::COMMANDS_DATAPACK_LIST_AVAILABLE_NONE,
|
||||||
TextComponent::translate_cross(
|
translation::java::COMMANDS_DATAPACK_LIST_AVAILABLE_NONE,
|
||||||
translation::java::COMMANDS_DATAPACK_LIST_AVAILABLE_NONE,
|
[],
|
||||||
translation::java::COMMANDS_DATAPACK_LIST_AVAILABLE_NONE,
|
),
|
||||||
[],
|
false,
|
||||||
),
|
);
|
||||||
false,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
} else {
|
} else {
|
||||||
let packs_component =
|
let packs_component =
|
||||||
TextComponent::join_with_comma(available.iter().map(|p| format_pack(p)).collect());
|
TextComponent::join_with_comma(available.iter().map(|p| format_pack(p)).collect());
|
||||||
context
|
context.source.send_feedback(
|
||||||
.source
|
TextComponent::translate_cross(
|
||||||
.send_feedback(
|
translation::java::COMMANDS_DATAPACK_LIST_AVAILABLE_SUCCESS,
|
||||||
TextComponent::translate_cross(
|
translation::java::COMMANDS_DATAPACK_LIST_AVAILABLE_SUCCESS,
|
||||||
translation::java::COMMANDS_DATAPACK_LIST_AVAILABLE_SUCCESS,
|
[
|
||||||
translation::java::COMMANDS_DATAPACK_LIST_AVAILABLE_SUCCESS,
|
TextComponent::text(available.len().to_string()),
|
||||||
[
|
packs_component,
|
||||||
TextComponent::text(available.len().to_string()),
|
],
|
||||||
packs_component,
|
),
|
||||||
],
|
false,
|
||||||
),
|
);
|
||||||
false,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -302,60 +284,55 @@ enum EnablePosition {
|
|||||||
struct DatapackEnableExecutor(EnablePosition);
|
struct DatapackEnableExecutor(EnablePosition);
|
||||||
|
|
||||||
impl CommandExecutor for DatapackEnableExecutor {
|
impl CommandExecutor for DatapackEnableExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let name_str = StringArgumentType::get(context, "name")?;
|
||||||
let name_str = StringArgumentType::get(context, "name")?;
|
let server = context.server();
|
||||||
let server = context.server();
|
|
||||||
|
|
||||||
let Some(resolved_name) = find_pack_name(server, name_str) else {
|
let Some(resolved_name) = find_pack_name(server, name_str) else {
|
||||||
return Err(ERROR_UNKNOWN_DATAPACK
|
return Err(ERROR_UNKNOWN_DATAPACK
|
||||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||||
};
|
};
|
||||||
|
|
||||||
let enabled = get_enabled_packs(server);
|
let enabled = get_enabled_packs(server);
|
||||||
if enabled.contains(&resolved_name) {
|
if enabled.contains(&resolved_name) {
|
||||||
return Err(
|
return Err(
|
||||||
ERROR_ENABLE_FAILED.create_without_context(TextComponent::text(resolved_name))
|
ERROR_ENABLE_FAILED.create_without_context(TextComponent::text(resolved_name))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let target = resolved_name.clone();
|
let target = resolved_name.clone();
|
||||||
let pos = self.0;
|
let pos = self.0;
|
||||||
server.level_info.rcu(|level_info| {
|
server.level_info.rcu(|level_info| {
|
||||||
let mut new_info = (**level_info).clone();
|
let mut new_info = (**level_info).clone();
|
||||||
new_info.data_packs.disabled.retain(|p| p != &target);
|
new_info.data_packs.disabled.retain(|p| p != &target);
|
||||||
new_info.data_packs.enabled.retain(|p| p != &target);
|
new_info.data_packs.enabled.retain(|p| p != &target);
|
||||||
match pos {
|
match pos {
|
||||||
EnablePosition::First => {
|
EnablePosition::First => {
|
||||||
new_info.data_packs.enabled.insert(0, target.clone());
|
new_info.data_packs.enabled.insert(0, target.clone());
|
||||||
}
|
}
|
||||||
EnablePosition::Last => {
|
EnablePosition::Last => {
|
||||||
new_info.data_packs.enabled.push(target.clone());
|
new_info.data_packs.enabled.push(target.clone());
|
||||||
}
|
|
||||||
}
|
}
|
||||||
new_info
|
|
||||||
});
|
|
||||||
|
|
||||||
if let Err(err) = server.save_world_info() {
|
|
||||||
error!("Failed to save world info: {err}");
|
|
||||||
}
|
}
|
||||||
|
new_info
|
||||||
|
});
|
||||||
|
|
||||||
server.reload_datapacks(server).await;
|
if let Err(err) = server.save_world_info() {
|
||||||
|
error!("Failed to save world info: {err}");
|
||||||
|
}
|
||||||
|
|
||||||
context
|
server.reload_datapacks(server);
|
||||||
.source
|
|
||||||
.send_feedback(
|
|
||||||
TextComponent::translate_cross(
|
|
||||||
translation::java::COMMANDS_DATAPACK_MODIFY_ENABLE,
|
|
||||||
translation::java::COMMANDS_DATAPACK_MODIFY_ENABLE,
|
|
||||||
[format_pack(&resolved_name)],
|
|
||||||
),
|
|
||||||
true,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(server.level_info.load().data_packs.enabled.len() as i32)
|
context.source.send_feedback(
|
||||||
})
|
TextComponent::translate_cross(
|
||||||
|
translation::java::COMMANDS_DATAPACK_MODIFY_ENABLE,
|
||||||
|
translation::java::COMMANDS_DATAPACK_MODIFY_ENABLE,
|
||||||
|
[format_pack(&resolved_name)],
|
||||||
|
),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(server.level_info.load().data_packs.enabled.len() as i32)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -368,140 +345,130 @@ enum BeforeOrAfter {
|
|||||||
struct DatapackEnableExistingExecutor(BeforeOrAfter);
|
struct DatapackEnableExistingExecutor(BeforeOrAfter);
|
||||||
|
|
||||||
impl CommandExecutor for DatapackEnableExistingExecutor {
|
impl CommandExecutor for DatapackEnableExistingExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let name_str = StringArgumentType::get(context, "name")?;
|
||||||
let name_str = StringArgumentType::get(context, "name")?;
|
let existing_str = StringArgumentType::get(context, "existing")?;
|
||||||
let existing_str = StringArgumentType::get(context, "existing")?;
|
let server = context.server();
|
||||||
let server = context.server();
|
|
||||||
|
|
||||||
let Some(target_pack) = find_pack_name(server, name_str) else {
|
let Some(target_pack) = find_pack_name(server, name_str) else {
|
||||||
return Err(ERROR_UNKNOWN_DATAPACK
|
return Err(ERROR_UNKNOWN_DATAPACK
|
||||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||||
};
|
};
|
||||||
|
|
||||||
let Some(existing_pack) = find_pack_name(server, existing_str) else {
|
let Some(existing_pack) = find_pack_name(server, existing_str) else {
|
||||||
return Err(ERROR_UNKNOWN_DATAPACK
|
return Err(ERROR_UNKNOWN_DATAPACK
|
||||||
.create_without_context(TextComponent::text(existing_str.to_string())));
|
.create_without_context(TextComponent::text(existing_str.to_string())));
|
||||||
};
|
};
|
||||||
|
|
||||||
let enabled = get_enabled_packs(server);
|
let enabled = get_enabled_packs(server);
|
||||||
if enabled.contains(&target_pack) {
|
if enabled.contains(&target_pack) {
|
||||||
return Err(
|
return Err(
|
||||||
ERROR_ENABLE_FAILED.create_without_context(TextComponent::text(target_pack))
|
ERROR_ENABLE_FAILED.create_without_context(TextComponent::text(target_pack))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if !enabled.contains(&existing_pack) {
|
if !enabled.contains(&existing_pack) {
|
||||||
return Err(
|
return Err(
|
||||||
ERROR_DISABLE_FAILED.create_without_context(TextComponent::text(existing_pack))
|
ERROR_DISABLE_FAILED.create_without_context(TextComponent::text(existing_pack))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let target = target_pack.clone();
|
let target = target_pack.clone();
|
||||||
let existing = existing_pack.clone();
|
let existing = existing_pack;
|
||||||
let before_or_after = self.0;
|
let before_or_after = self.0;
|
||||||
server.level_info.rcu(|level_info| {
|
server.level_info.rcu(|level_info| {
|
||||||
let mut new_info = (**level_info).clone();
|
let mut new_info = (**level_info).clone();
|
||||||
new_info.data_packs.disabled.retain(|p| p != &target);
|
new_info.data_packs.disabled.retain(|p| p != &target);
|
||||||
new_info.data_packs.enabled.retain(|p| p != &target);
|
new_info.data_packs.enabled.retain(|p| p != &target);
|
||||||
|
|
||||||
if let Some(idx) = new_info
|
if let Some(idx) = new_info
|
||||||
|
.data_packs
|
||||||
|
.enabled
|
||||||
|
.iter()
|
||||||
|
.position(|p| p == &existing)
|
||||||
|
{
|
||||||
|
let insert_pos = match before_or_after {
|
||||||
|
BeforeOrAfter::Before => idx,
|
||||||
|
BeforeOrAfter::After => idx + 1,
|
||||||
|
};
|
||||||
|
new_info
|
||||||
.data_packs
|
.data_packs
|
||||||
.enabled
|
.enabled
|
||||||
.iter()
|
.insert(insert_pos, target.clone());
|
||||||
.position(|p| p == &existing)
|
} else {
|
||||||
{
|
new_info.data_packs.enabled.push(target.clone());
|
||||||
let insert_pos = match before_or_after {
|
|
||||||
BeforeOrAfter::Before => idx,
|
|
||||||
BeforeOrAfter::After => idx + 1,
|
|
||||||
};
|
|
||||||
new_info
|
|
||||||
.data_packs
|
|
||||||
.enabled
|
|
||||||
.insert(insert_pos, target.clone());
|
|
||||||
} else {
|
|
||||||
new_info.data_packs.enabled.push(target.clone());
|
|
||||||
}
|
|
||||||
new_info
|
|
||||||
});
|
|
||||||
|
|
||||||
if let Err(err) = server.save_world_info() {
|
|
||||||
error!("Failed to save world info: {err}");
|
|
||||||
}
|
}
|
||||||
|
new_info
|
||||||
|
});
|
||||||
|
|
||||||
server.reload_datapacks(server).await;
|
if let Err(err) = server.save_world_info() {
|
||||||
|
error!("Failed to save world info: {err}");
|
||||||
|
}
|
||||||
|
|
||||||
context
|
server.reload_datapacks(server);
|
||||||
.source
|
|
||||||
.send_feedback(
|
|
||||||
TextComponent::translate_cross(
|
|
||||||
translation::java::COMMANDS_DATAPACK_MODIFY_ENABLE,
|
|
||||||
translation::java::COMMANDS_DATAPACK_MODIFY_ENABLE,
|
|
||||||
[format_pack(&target_pack)],
|
|
||||||
),
|
|
||||||
true,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(server.level_info.load().data_packs.enabled.len() as i32)
|
context.source.send_feedback(
|
||||||
})
|
TextComponent::translate_cross(
|
||||||
|
translation::java::COMMANDS_DATAPACK_MODIFY_ENABLE,
|
||||||
|
translation::java::COMMANDS_DATAPACK_MODIFY_ENABLE,
|
||||||
|
[format_pack(&target_pack)],
|
||||||
|
),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(server.level_info.load().data_packs.enabled.len() as i32)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct DatapackDisableExecutor;
|
struct DatapackDisableExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for DatapackDisableExecutor {
|
impl CommandExecutor for DatapackDisableExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let name_str = StringArgumentType::get(context, "name")?;
|
||||||
let name_str = StringArgumentType::get(context, "name")?;
|
let server = context.server();
|
||||||
let server = context.server();
|
|
||||||
|
|
||||||
let Some(target_pack) = find_pack_name(server, name_str) else {
|
let Some(target_pack) = find_pack_name(server, name_str) else {
|
||||||
return Err(ERROR_DISABLE_FAILED
|
return Err(ERROR_DISABLE_FAILED
|
||||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||||
};
|
};
|
||||||
|
|
||||||
let enabled = get_enabled_packs(server);
|
let enabled = get_enabled_packs(server);
|
||||||
if !enabled.contains(&target_pack) {
|
if !enabled.contains(&target_pack) {
|
||||||
return Err(ERROR_DISABLE_FAILED
|
return Err(ERROR_DISABLE_FAILED
|
||||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||||
|
}
|
||||||
|
|
||||||
|
if target_pack == "vanilla" {
|
||||||
|
return Err(ERROR_DISABLE_FAILED
|
||||||
|
.create_without_context(TextComponent::text("vanilla".to_string())));
|
||||||
|
}
|
||||||
|
|
||||||
|
let target = target_pack.clone();
|
||||||
|
server.level_info.rcu(|level_info| {
|
||||||
|
let mut new_info = (**level_info).clone();
|
||||||
|
new_info.data_packs.enabled.retain(|p| p != &target);
|
||||||
|
if !new_info.data_packs.disabled.contains(&target) {
|
||||||
|
new_info.data_packs.disabled.push(target.clone());
|
||||||
}
|
}
|
||||||
|
new_info
|
||||||
|
});
|
||||||
|
|
||||||
if target_pack == "vanilla" {
|
if let Err(err) = server.save_world_info() {
|
||||||
return Err(ERROR_DISABLE_FAILED
|
error!("Failed to save world info: {err}");
|
||||||
.create_without_context(TextComponent::text("vanilla".to_string())));
|
}
|
||||||
}
|
|
||||||
|
|
||||||
let target = target_pack.clone();
|
server.reload_datapacks(server);
|
||||||
server.level_info.rcu(|level_info| {
|
|
||||||
let mut new_info = (**level_info).clone();
|
|
||||||
new_info.data_packs.enabled.retain(|p| p != &target);
|
|
||||||
if !new_info.data_packs.disabled.contains(&target) {
|
|
||||||
new_info.data_packs.disabled.push(target.clone());
|
|
||||||
}
|
|
||||||
new_info
|
|
||||||
});
|
|
||||||
|
|
||||||
if let Err(err) = server.save_world_info() {
|
context.source.send_feedback(
|
||||||
error!("Failed to save world info: {err}");
|
TextComponent::translate_cross(
|
||||||
}
|
translation::java::COMMANDS_DATAPACK_MODIFY_DISABLE,
|
||||||
|
translation::java::COMMANDS_DATAPACK_MODIFY_DISABLE,
|
||||||
|
[format_pack(&target_pack)],
|
||||||
|
),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
|
||||||
server.reload_datapacks(server).await;
|
Ok(server.level_info.load().data_packs.enabled.len() as i32)
|
||||||
|
|
||||||
context
|
|
||||||
.source
|
|
||||||
.send_feedback(
|
|
||||||
TextComponent::translate_cross(
|
|
||||||
translation::java::COMMANDS_DATAPACK_MODIFY_DISABLE,
|
|
||||||
translation::java::COMMANDS_DATAPACK_MODIFY_DISABLE,
|
|
||||||
[format_pack(&target_pack)],
|
|
||||||
),
|
|
||||||
true,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(server.level_info.load().data_packs.enabled.len() as i32)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -518,69 +485,64 @@ fn is_valid_pack_name(name: &str) -> bool {
|
|||||||
struct DatapackCreateExecutor;
|
struct DatapackCreateExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for DatapackCreateExecutor {
|
impl CommandExecutor for DatapackCreateExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let name_str = StringArgumentType::get(context, "name")?;
|
||||||
let name_str = StringArgumentType::get(context, "name")?;
|
let description = StringArgumentType::get(context, "description").unwrap_or(name_str);
|
||||||
let description = StringArgumentType::get(context, "description").unwrap_or(name_str);
|
|
||||||
|
|
||||||
if !is_valid_pack_name(name_str) {
|
if !is_valid_pack_name(name_str) {
|
||||||
return Err(ERROR_CREATE_INVALID_NAME
|
return Err(ERROR_CREATE_INVALID_NAME
|
||||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||||
|
}
|
||||||
|
|
||||||
|
let server = context.server();
|
||||||
|
let datapacks_dir = server.basic_config.get_world_path().join("datapacks");
|
||||||
|
let pack_dir = datapacks_dir.join(name_str);
|
||||||
|
|
||||||
|
if pack_dir.exists() {
|
||||||
|
return Err(ERROR_CREATE_ALREADY_EXISTS
|
||||||
|
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||||
|
}
|
||||||
|
|
||||||
|
let data_dir = pack_dir.join("data");
|
||||||
|
if let Err(err) = fs::create_dir_all(&data_dir) {
|
||||||
|
error!("Failed to create datapack directory: {err}");
|
||||||
|
return Err(ERROR_CREATE_IO_FAILURE
|
||||||
|
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mcmeta_content = serde_json::json!({
|
||||||
|
"pack": {
|
||||||
|
"pack_format": 61,
|
||||||
|
"description": description
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
|
||||||
let server = context.server();
|
let mcmeta_path = pack_dir.join("pack.mcmeta");
|
||||||
let datapacks_dir = server.basic_config.get_world_path().join("datapacks");
|
let mcmeta_str = match serde_json::to_string_pretty(&mcmeta_content) {
|
||||||
let pack_dir = datapacks_dir.join(name_str);
|
Ok(s) => s,
|
||||||
|
Err(err) => {
|
||||||
if pack_dir.exists() {
|
error!("Failed to serialize pack.mcmeta: {err}");
|
||||||
return Err(ERROR_CREATE_ALREADY_EXISTS
|
|
||||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
|
||||||
}
|
|
||||||
|
|
||||||
let data_dir = pack_dir.join("data");
|
|
||||||
if let Err(err) = fs::create_dir_all(&data_dir) {
|
|
||||||
error!("Failed to create datapack directory: {err}");
|
|
||||||
return Err(ERROR_CREATE_IO_FAILURE
|
return Err(ERROR_CREATE_IO_FAILURE
|
||||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let mcmeta_content = serde_json::json!({
|
if let Err(err) = fs::write(&mcmeta_path, mcmeta_str) {
|
||||||
"pack": {
|
error!("Failed to write pack.mcmeta: {err}");
|
||||||
"pack_format": 61,
|
return Err(ERROR_CREATE_IO_FAILURE
|
||||||
"description": description
|
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
let mcmeta_path = pack_dir.join("pack.mcmeta");
|
context.source.send_feedback(
|
||||||
let mcmeta_str = match serde_json::to_string_pretty(&mcmeta_content) {
|
TextComponent::translate_cross(
|
||||||
Ok(s) => s,
|
translation::java::COMMANDS_DATAPACK_CREATE_SUCCESS,
|
||||||
Err(err) => {
|
translation::java::COMMANDS_DATAPACK_CREATE_SUCCESS,
|
||||||
error!("Failed to serialize pack.mcmeta: {err}");
|
[TextComponent::text(name_str.to_string())],
|
||||||
return Err(ERROR_CREATE_IO_FAILURE
|
),
|
||||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
true,
|
||||||
}
|
);
|
||||||
};
|
|
||||||
|
|
||||||
if let Err(err) = fs::write(&mcmeta_path, mcmeta_str) {
|
Ok(1)
|
||||||
error!("Failed to write pack.mcmeta: {err}");
|
|
||||||
return Err(ERROR_CREATE_IO_FAILURE
|
|
||||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
|
||||||
}
|
|
||||||
|
|
||||||
context
|
|
||||||
.source
|
|
||||||
.send_feedback(
|
|
||||||
TextComponent::translate_cross(
|
|
||||||
translation::java::COMMANDS_DATAPACK_CREATE_SUCCESS,
|
|
||||||
translation::java::COMMANDS_DATAPACK_CREATE_SUCCESS,
|
|
||||||
[TextComponent::text(name_str.to_string())],
|
|
||||||
),
|
|
||||||
true,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(1)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,70 +29,63 @@ const NOT_RUNNING_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
|||||||
struct DebugStartExecutor;
|
struct DebugStartExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for DebugStartExecutor {
|
impl CommandExecutor for DebugStartExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let server = context.server();
|
||||||
let server = context.server();
|
let current_tick = server.tick_count.load(Ordering::Relaxed);
|
||||||
let current_tick = server.tick_count.load(Ordering::Relaxed);
|
server.debug_profiler.start(current_tick).map_err(
|
||||||
server.debug_profiler.start(current_tick).map_err(
|
|StartDebugProfileError::AlreadyRunning| {
|
||||||
|StartDebugProfileError::AlreadyRunning| {
|
ALREADY_RUNNING_ERROR_TYPE.create_without_context()
|
||||||
ALREADY_RUNNING_ERROR_TYPE.create_without_context()
|
},
|
||||||
},
|
)?;
|
||||||
)?;
|
|
||||||
|
|
||||||
context
|
context.source.send_feedback(
|
||||||
.source
|
TextComponent::translate_cross(
|
||||||
.send_feedback(
|
translation::java::COMMANDS_DEBUG_STARTED,
|
||||||
TextComponent::translate_cross(
|
translation::bedrock::COMMANDS_DEBUG_START,
|
||||||
translation::java::COMMANDS_DEBUG_STARTED,
|
[],
|
||||||
translation::bedrock::COMMANDS_DEBUG_START,
|
),
|
||||||
[],
|
true,
|
||||||
),
|
);
|
||||||
true,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(1)
|
Ok(1)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct DebugStopExecutor;
|
struct DebugStopExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for DebugStopExecutor {
|
impl CommandExecutor for DebugStopExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let server = context.server();
|
||||||
let server = context.server();
|
let current_tick = server.tick_count.load(Ordering::Relaxed);
|
||||||
let current_tick = server.tick_count.load(Ordering::Relaxed);
|
let result = server.debug_profiler.stop(current_tick).map_err(
|
||||||
let result = server.debug_profiler.stop(current_tick).map_err(
|
|StopDebugProfileError::NotRunning| NOT_RUNNING_ERROR_TYPE.create_without_context(),
|
||||||
|StopDebugProfileError::NotRunning| NOT_RUNNING_ERROR_TYPE.create_without_context(),
|
)?;
|
||||||
)?;
|
|
||||||
|
|
||||||
let seconds = result.duration.as_secs_f64();
|
let seconds = result.duration.as_secs_f64();
|
||||||
let tps = result.ticks_per_second();
|
let tps = result.ticks_per_second();
|
||||||
let arguments = [
|
let arguments = [
|
||||||
TextComponent::text(format!("{seconds:.2}")),
|
TextComponent::text(format!("{seconds:.2}")),
|
||||||
TextComponent::text(result.ticks.to_string()),
|
TextComponent::text(result.ticks.to_string()),
|
||||||
TextComponent::text(format!("{tps:.2}")),
|
TextComponent::text(format!("{tps:.2}")),
|
||||||
];
|
];
|
||||||
let feedback = if matches!(context.source.output, CommandSender::Player(_)) {
|
let feedback = if matches!(context.source.output, CommandSender::Player(_)) {
|
||||||
TextComponent::translate_cross(
|
TextComponent::translate_cross(
|
||||||
translation::java::COMMANDS_DEBUG_STOPPED,
|
translation::java::COMMANDS_DEBUG_STOPPED,
|
||||||
translation::bedrock::COMMANDS_DEBUG_STOP,
|
translation::bedrock::COMMANDS_DEBUG_STOP,
|
||||||
arguments,
|
arguments,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
// Bedrock's debug-stop translation uses printf-style placeholders that the
|
// Bedrock's debug-stop translation uses printf-style placeholders that the
|
||||||
// server-side console renderer cannot resolve. Non-player command sources need
|
// server-side console renderer cannot resolve. Non-player command sources need
|
||||||
// an already-rendered message; players still receive their native translation.
|
// an already-rendered message; players still receive their native translation.
|
||||||
TextComponent::text(format!(
|
TextComponent::text(format!(
|
||||||
"Stopped tick profiling after {seconds:.2} second(s) and {} tick(s) ({tps:.2} tick(s) per second)",
|
"Stopped tick profiling after {seconds:.2} second(s) and {} tick(s) ({tps:.2} tick(s) per second)",
|
||||||
result.ticks
|
result.ticks
|
||||||
))
|
))
|
||||||
};
|
};
|
||||||
context.source.send_feedback(feedback, true).await;
|
context.source.send_feedback(feedback, true);
|
||||||
|
|
||||||
Ok(result.command_result())
|
Ok(result.command_result())
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,46 +20,43 @@ pub struct DefaultGamemode {
|
|||||||
struct DefaultGamemodeExecutor;
|
struct DefaultGamemodeExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for DefaultGamemodeExecutor {
|
impl CommandExecutor for DefaultGamemodeExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
server: &'a crate::server::Server,
|
server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let Some(Arg::GameMode(gamemode)) = args.get_cloned(&ARG_GAMEMODE) else {
|
||||||
let Some(Arg::GameMode(gamemode)) = args.get_cloned(&ARG_GAMEMODE) else {
|
return Err(InvalidConsumption(Some(ARG_GAMEMODE.into())));
|
||||||
return Err(InvalidConsumption(Some(ARG_GAMEMODE.into())));
|
};
|
||||||
};
|
|
||||||
|
|
||||||
let mut successful_changes: i32 = 0;
|
let mut successful_changes: i32 = 0;
|
||||||
if server.basic_config.force_gamemode {
|
if server.basic_config.force_gamemode {
|
||||||
for player in server.get_all_players() {
|
for player in server.get_all_players() {
|
||||||
if player.set_gamemode(gamemode).await {
|
if player.gamemode.load() != gamemode {
|
||||||
successful_changes += 1;
|
player.set_gamemode(gamemode);
|
||||||
}
|
successful_changes += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let gamemode_string = format!("{gamemode:?}").to_lowercase();
|
let gamemode_string = format!("{gamemode:?}").to_lowercase();
|
||||||
let gamemode_string = format!("gameMode.{gamemode_string}");
|
let gamemode_string = format!("gameMode.{gamemode_string}");
|
||||||
|
|
||||||
sender
|
sender.send_message(TextComponent::translate_cross(
|
||||||
.send_message(TextComponent::translate_cross(
|
pumpkin_data::translation::java::COMMANDS_DEFAULTGAMEMODE_SUCCESS,
|
||||||
pumpkin_data::translation::java::COMMANDS_DEFAULTGAMEMODE_SUCCESS,
|
pumpkin_data::translation::bedrock::COMMANDS_DEFAULTGAMEMODE_SUCCESS,
|
||||||
pumpkin_data::translation::bedrock::COMMANDS_DEFAULTGAMEMODE_SUCCESS,
|
[TextComponent::translate_cross(
|
||||||
[TextComponent::translate_cross(
|
gamemode_string.clone(),
|
||||||
gamemode_string.clone(),
|
gamemode_string,
|
||||||
gamemode_string,
|
[],
|
||||||
[],
|
)],
|
||||||
)],
|
));
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
//Change the default gamemode (not in configuration.toml)
|
//Change the default gamemode (not in configuration.toml)
|
||||||
server.defaultgamemode.lock().await.gamemode = gamemode;
|
server.defaultgamemode.lock().unwrap().gamemode = gamemode;
|
||||||
|
|
||||||
Ok(successful_changes)
|
Ok(successful_changes)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,59 +21,57 @@ const ARG_TARGETS: &str = "targets";
|
|||||||
struct Executor;
|
struct Executor;
|
||||||
|
|
||||||
impl CommandExecutor for Executor {
|
impl CommandExecutor for Executor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
server: &'a crate::server::Server,
|
server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let mut config = server.data.operator_config.write().unwrap();
|
||||||
let mut config = server.data.operator_config.write().await;
|
|
||||||
|
|
||||||
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGETS) else {
|
let Some(Arg::GameProfiles(targets)) = args.get(&ARG_TARGETS) else {
|
||||||
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
return Err(InvalidConsumption(Some(ARG_TARGETS.into())));
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut succeeded_deops: i32 = 0;
|
let mut succeeded_deops: i32 = 0;
|
||||||
for profile in targets {
|
for profile in targets {
|
||||||
if let Some(op_index) = config.ops.iter().position(|o| o.uuid == profile.id) {
|
if let Some(op_index) = config.ops.iter().position(|o| o.uuid == profile.id) {
|
||||||
config.ops.remove(op_index);
|
config.ops.remove(op_index);
|
||||||
succeeded_deops += 1;
|
succeeded_deops += 1;
|
||||||
|
|
||||||
if let Some(player) = server.get_player_by_uuid(profile.id) {
|
if let Some(player) = server.get_player_by_uuid(profile.id)
|
||||||
let command_dispatcher = server.command_dispatcher.load();
|
&& let Some(server_arc) = player.world().server.upgrade()
|
||||||
player
|
{
|
||||||
.set_permission_lvl(
|
let command_dispatcher = server_arc.command_dispatcher.load();
|
||||||
server,
|
player.set_permission_lvl(
|
||||||
pumpkin_util::PermissionLvl::Zero,
|
&server_arc,
|
||||||
&command_dispatcher,
|
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 {
|
let msg = TextComponent::translate_cross(
|
||||||
config.save();
|
pumpkin_data::translation::java::COMMANDS_DEOP_SUCCESS,
|
||||||
|
pumpkin_data::translation::bedrock::COMMANDS_DEOP_SUCCESS,
|
||||||
|
[TextComponent::text(profile.name.clone())],
|
||||||
|
);
|
||||||
|
sender.send_message(msg);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if succeeded_deops == 0 {
|
if succeeded_deops > 0 {
|
||||||
Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
config.save();
|
||||||
pumpkin_data::translation::java::COMMANDS_DEOP_FAILED,
|
}
|
||||||
pumpkin_data::translation::bedrock::COMMANDS_DEOP_FAILED,
|
|
||||||
[],
|
if succeeded_deops == 0 {
|
||||||
)))
|
Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||||
} else {
|
pumpkin_data::translation::java::COMMANDS_DEOP_FAILED,
|
||||||
Ok(succeeded_deops)
|
pumpkin_data::translation::bedrock::COMMANDS_DEOP_FAILED,
|
||||||
}
|
[],
|
||||||
})
|
)))
|
||||||
|
} else {
|
||||||
|
Ok(succeeded_deops)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,28 +21,26 @@ const ARG_DIALOG: &str = "dialog";
|
|||||||
struct DialogClearExecutor;
|
struct DialogClearExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for DialogClearExecutor {
|
impl CommandExecutor for DialogClearExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let targets = EntityArgumentType::get_players(context, ARG_TARGETS)?;
|
||||||
let targets = EntityArgumentType::get_players(context, ARG_TARGETS).await?;
|
|
||||||
|
|
||||||
let count = targets.len();
|
let count = targets.len();
|
||||||
let packet = CPlayClearDialog::new();
|
let packet = CPlayClearDialog::new();
|
||||||
for player in &targets {
|
for player in &targets {
|
||||||
player.send_client_packet(&packet).await;
|
player.try_send_client_packet(&packet);
|
||||||
}
|
}
|
||||||
|
|
||||||
let msg = if count == 1 {
|
let msg = if count == 1 {
|
||||||
TextComponent::text(format!(
|
TextComponent::text(format!(
|
||||||
"Cleared dialog for {}",
|
"Cleared dialog for {}",
|
||||||
targets[0].gameprofile.name
|
targets[0].gameprofile.name
|
||||||
))
|
))
|
||||||
} else {
|
} else {
|
||||||
TextComponent::text(format!("Cleared dialogs for {count} players"))
|
TextComponent::text(format!("Cleared dialogs for {count} players"))
|
||||||
};
|
};
|
||||||
context.source.send_feedback(msg, true).await;
|
context.source.send_feedback(msg, true);
|
||||||
|
|
||||||
Ok(count as i32)
|
Ok(count as i32)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,36 +51,31 @@ static REGISTRY_ERROR: LiteralCommandErrorType = LiteralCommandErrorType::new(
|
|||||||
struct DialogShowExecutor;
|
struct DialogShowExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for DialogShowExecutor {
|
impl CommandExecutor for DialogShowExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let targets = EntityArgumentType::get_players(context, ARG_TARGETS)?;
|
||||||
let targets = EntityArgumentType::get_players(context, ARG_TARGETS).await?;
|
let dialog_arg = DialogArgumentType::get(context, ARG_DIALOG)?;
|
||||||
let dialog_arg = DialogArgumentType::get(context, ARG_DIALOG)?;
|
|
||||||
|
|
||||||
match dialog_arg {
|
match dialog_arg {
|
||||||
DialogArg::Nbt(compound) => {
|
DialogArg::Nbt(compound) => {
|
||||||
let count = targets.len();
|
let count = targets.len();
|
||||||
let dialog_nbt = DialogNBT::from_nbt(compound);
|
let dialog_nbt = DialogNBT::from_nbt(compound);
|
||||||
let packet = CPlayShowDialog::new(IdOr::Value(dialog_nbt));
|
let packet = CPlayShowDialog::new(IdOr::Value(dialog_nbt));
|
||||||
|
|
||||||
for player in &targets {
|
for player in &targets {
|
||||||
player.send_client_packet(&packet).await;
|
player.try_send_client_packet(&packet);
|
||||||
}
|
|
||||||
|
|
||||||
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()),
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
Ok(count as i32)
|
||||||
}
|
}
|
||||||
})
|
DialogArg::Id(_id) => Err(REGISTRY_ERROR.create_without_context()),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,68 +17,58 @@ const FAILURE_ERROR_TYPE: CommandErrorType<1> =
|
|||||||
struct DifficultyQueryExecutor;
|
struct DifficultyQueryExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for DifficultyQueryExecutor {
|
impl CommandExecutor for DifficultyQueryExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let difficulty = context.server().get_difficulty();
|
||||||
let difficulty = context.server().get_difficulty();
|
|
||||||
|
|
||||||
context
|
context.source.send_feedback(
|
||||||
.source
|
TextComponent::translate_cross(
|
||||||
.send_feedback(
|
"commands.difficulty.query",
|
||||||
TextComponent::translate_cross(
|
"commands.difficulty.query",
|
||||||
"commands.difficulty.query",
|
[TextComponent::translate_cross(
|
||||||
"commands.difficulty.query",
|
difficulty.translation_key(),
|
||||||
[TextComponent::translate_cross(
|
difficulty.translation_key(),
|
||||||
difficulty.translation_key(),
|
[],
|
||||||
difficulty.translation_key(),
|
)],
|
||||||
[],
|
),
|
||||||
)],
|
false,
|
||||||
),
|
);
|
||||||
false,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(difficulty as i32)
|
Ok(difficulty as i32)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct DifficultySetExecutor(Difficulty);
|
struct DifficultySetExecutor(Difficulty);
|
||||||
|
|
||||||
impl CommandExecutor for DifficultySetExecutor {
|
impl CommandExecutor for DifficultySetExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let difficulty = self.0;
|
||||||
let difficulty = self.0;
|
let server = context.server();
|
||||||
let server = context.server();
|
|
||||||
|
|
||||||
{
|
{
|
||||||
let level_info = server.level_info.load();
|
let level_info = server.level_info.load();
|
||||||
|
|
||||||
if level_info.difficulty == difficulty {
|
if level_info.difficulty == difficulty {
|
||||||
return Err(FAILURE_ERROR_TYPE
|
return Err(FAILURE_ERROR_TYPE
|
||||||
.create_without_context(TextComponent::text(difficulty.name())));
|
.create_without_context(TextComponent::text(difficulty.name())));
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
server.set_difficulty(difficulty, true);
|
server.set_difficulty(difficulty, true);
|
||||||
|
|
||||||
context
|
context.source.send_feedback(
|
||||||
.source
|
TextComponent::translate_cross(
|
||||||
.send_feedback(
|
pumpkin_data::translation::java::COMMANDS_DIFFICULTY_SUCCESS,
|
||||||
TextComponent::translate_cross(
|
pumpkin_data::translation::bedrock::COMMANDS_DIFFICULTY_SUCCESS,
|
||||||
pumpkin_data::translation::java::COMMANDS_DIFFICULTY_SUCCESS,
|
[TextComponent::translate_cross(
|
||||||
pumpkin_data::translation::bedrock::COMMANDS_DIFFICULTY_SUCCESS,
|
difficulty.translation_key(),
|
||||||
[TextComponent::translate_cross(
|
difficulty.translation_key(),
|
||||||
difficulty.translation_key(),
|
[],
|
||||||
difficulty.translation_key(),
|
)],
|
||||||
[],
|
),
|
||||||
)],
|
true,
|
||||||
),
|
);
|
||||||
true,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(0)
|
Ok(0)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,219 +38,210 @@ enum Amplifier {
|
|||||||
struct GiveExecutor(Time, Amplifier, bool);
|
struct GiveExecutor(Time, Amplifier, bool);
|
||||||
|
|
||||||
impl CommandExecutor for GiveExecutor {
|
impl CommandExecutor for GiveExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
_server: &'a crate::server::Server,
|
_server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let Some(Arg::Players(targets)) = args.get(ARG_TARGET) else {
|
||||||
let Some(Arg::Players(targets)) = args.get(ARG_TARGET) else {
|
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||||
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
};
|
||||||
};
|
let Some(Arg::Effect(effect)) = args.get(ARG_EFFECT) else {
|
||||||
let Some(Arg::Effect(effect)) = args.get(ARG_EFFECT) else {
|
return Err(InvalidConsumption(Some(ARG_EFFECT.into())));
|
||||||
return Err(InvalidConsumption(Some(ARG_EFFECT.into())));
|
};
|
||||||
};
|
|
||||||
|
|
||||||
//duration is in tick, so * 20 (not for the infinite because -1*20 cause visual glitch)
|
//duration is in tick, so * 20 (not for the infinite because -1*20 cause visual glitch)
|
||||||
let second = match self.0 {
|
let second = match self.0 {
|
||||||
Time::Base => 30 * 20,
|
Time::Base => 30 * 20,
|
||||||
Time::Specified => {
|
Time::Specified => {
|
||||||
BoundedNumArgumentConsumer::new()
|
BoundedNumArgumentConsumer::new()
|
||||||
.name("seconds")
|
.name("seconds")
|
||||||
.min(1)
|
.min(1)
|
||||||
.max(1_000_000)
|
.max(1_000_000)
|
||||||
.find_arg_default_name(args)??
|
.find_arg_default_name(args)??
|
||||||
* 20
|
* 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;
|
|
||||||
}
|
}
|
||||||
|
Time::Infinite => -1,
|
||||||
|
};
|
||||||
|
|
||||||
let mut successes = 0;
|
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,
|
||||||
|
};
|
||||||
|
|
||||||
for target in targets {
|
let mut hide_particles = self.2;
|
||||||
let should_skip = target
|
//if false -> parameter is referred
|
||||||
.living_entity
|
if !hide_particles {
|
||||||
.get_effect(effect)
|
let Some(Arg::Bool(hide_particle)) = args.get(ARG_HIDE_PARTICLE) else {
|
||||||
.is_some_and(|existing| existing.amplifier >= amplifier);
|
return Err(InvalidConsumption(Some(ARG_HIDE_PARTICLE.into())));
|
||||||
|
};
|
||||||
|
|
||||||
if !should_skip {
|
hide_particles = *hide_particle;
|
||||||
target.add_effect(Effect {
|
}
|
||||||
effect_type: effect,
|
|
||||||
duration: second,
|
let mut successes = 0;
|
||||||
amplifier,
|
|
||||||
ambient: false, //this is not a beacon effect
|
for target in targets {
|
||||||
show_particles: !hide_particles,
|
let should_skip = target
|
||||||
show_icon: true,
|
.living_entity
|
||||||
blend: false,
|
.get_effect(effect)
|
||||||
});
|
.is_some_and(|existing| existing.amplifier >= amplifier);
|
||||||
successes += 1;
|
|
||||||
}
|
if !should_skip {
|
||||||
|
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: false,
|
||||||
|
});
|
||||||
|
successes += 1;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let translation_name = TextComponent::translate_cross(
|
let translation_name = TextComponent::translate_cross(
|
||||||
effect.translation_key.to_string(),
|
effect.translation_key.to_string(),
|
||||||
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()],
|
||||||
|
));
|
||||||
|
} 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()),
|
||||||
|
],
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
if successes == 0 {
|
Ok(successes)
|
||||||
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;
|
|
||||||
} 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
|
struct ClearExecutor(bool); //the param -> true = delete every effect, false = only one
|
||||||
|
|
||||||
impl CommandExecutor for ClearExecutor {
|
impl CommandExecutor for ClearExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
_server: &'a crate::server::Server,
|
_server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let Some(Arg::Players(targets)) = args.get(ARG_TARGET) else {
|
||||||
let Some(Arg::Players(targets)) = args.get(ARG_TARGET) else {
|
return Err(InvalidConsumption(Some(ARG_TARGET.into())));
|
||||||
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 {
|
||||||
|
let has_effects = !target
|
||||||
|
.living_entity
|
||||||
|
.active_effects
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.is_empty();
|
||||||
|
if has_effects {
|
||||||
|
target.remove_all_effects();
|
||||||
|
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()],
|
||||||
|
));
|
||||||
|
} 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())],
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(succeeded_clears)
|
||||||
|
} else {
|
||||||
|
let Some(Arg::Effect(effect_type)) = args.get(ARG_EFFECT) else {
|
||||||
|
return Err(InvalidConsumption(Some(ARG_EFFECT.into())));
|
||||||
};
|
};
|
||||||
|
|
||||||
let effect;
|
effect = *effect_type;
|
||||||
//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
|
let mut succeeded_clears: i32 = 0;
|
||||||
if succeeded_clears == 0 {
|
for target in targets {
|
||||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
if target.living_entity.has_effect(effect) {
|
||||||
"commands.effect.clear.everything.failed",
|
target.remove_effect(effect);
|
||||||
"commands.effect.clear.everything.failed",
|
succeeded_clears += 1;
|
||||||
[],
|
|
||||||
)));
|
|
||||||
}
|
}
|
||||||
//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;
|
|
||||||
} 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) {
|
|
||||||
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;
|
|
||||||
} 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)
|
|
||||||
}
|
}
|
||||||
})
|
|
||||||
|
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(),
|
||||||
|
],
|
||||||
|
));
|
||||||
|
} 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()),
|
||||||
|
],
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(succeeded_clears)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,95 +18,93 @@ const DESCRIPTION: &str = "Adds an enchantment to a player's selected item, subj
|
|||||||
struct Executor;
|
struct Executor;
|
||||||
|
|
||||||
impl CommandExecutor for Executor {
|
impl CommandExecutor for Executor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
_server: &'a crate::server::Server,
|
_server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let targets = EntitiesArgumentConsumer.find_arg_default_name(args)?;
|
||||||
let targets = EntitiesArgumentConsumer.find_arg_default_name(args)?;
|
let enchantment = EnchantmentArgumentConsumer.find_arg_default_name(args)?;
|
||||||
let enchantment = EnchantmentArgumentConsumer.find_arg_default_name(args)?;
|
let level = match enchantment_level_consumer().find_arg_default_name(args) {
|
||||||
let level = match enchantment_level_consumer().find_arg_default_name(args) {
|
Err(_) => 1,
|
||||||
Err(_) => 1,
|
Ok(Ok(level)) => level,
|
||||||
Ok(Ok(level)) => level,
|
Ok(Err(err)) => {
|
||||||
Ok(Err(err)) => {
|
let err_msg = match err {
|
||||||
let err_msg = match err {
|
NotInBounds::LowerBound(val, min) => TextComponent::translate_cross(
|
||||||
NotInBounds::LowerBound(val, min) => TextComponent::translate_cross(
|
"argument.integer.low",
|
||||||
"argument.integer.low",
|
"argument.integer.low",
|
||||||
"argument.integer.low",
|
&[
|
||||||
&[
|
TextComponent::text(min.to_string()),
|
||||||
TextComponent::text(min.to_string()),
|
TextComponent::text(val.to_string()),
|
||||||
TextComponent::text(val.to_string()),
|
],
|
||||||
],
|
),
|
||||||
),
|
NotInBounds::UpperBound(val, max) => TextComponent::translate_cross(
|
||||||
NotInBounds::UpperBound(val, max) => TextComponent::translate_cross(
|
"argument.integer.big",
|
||||||
"argument.integer.big",
|
"argument.integer.big",
|
||||||
"argument.integer.big",
|
&[
|
||||||
&[
|
TextComponent::text(max.to_string()),
|
||||||
TextComponent::text(max.to_string()),
|
TextComponent::text(val.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(),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
sender.send_message(msg).await;
|
|
||||||
Ok(1)
|
|
||||||
}
|
|
||||||
Err(e) => Err(e),
|
|
||||||
};
|
};
|
||||||
}
|
|
||||||
|
|
||||||
for target in targets {
|
return Err(CommandError::CommandFailed(err_msg));
|
||||||
if enchant_target(target, enchantment, level).await.is_ok() {
|
|
||||||
successful_targets += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if successful_targets == 0 {
|
|
||||||
return Err(commands_enchant_failed());
|
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if level > enchantment.max_level {
|
||||||
let msg = TextComponent::translate_cross(
|
let msg = TextComponent::translate_cross(
|
||||||
translation::java::COMMANDS_ENCHANT_SUCCESS_MULTIPLE,
|
translation::java::COMMANDS_ENCHANT_FAILED_LEVEL,
|
||||||
translation::bedrock::COMMANDS_ENCHANT_SUCCESS,
|
translation::bedrock::COMMANDS_ENCHANT_INVALIDLEVEL,
|
||||||
[
|
[
|
||||||
enchantment.get_fullname(level),
|
TextComponent::text(level.to_string()),
|
||||||
TextComponent::text(targets.len().to_string()),
|
TextComponent::text(enchantment.max_level.to_string()),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
sender.send_message(msg).await;
|
return Err(CommandError::CommandFailed(msg));
|
||||||
Ok(successful_targets)
|
}
|
||||||
})
|
|
||||||
|
let mut successful_targets = 0;
|
||||||
|
|
||||||
|
if targets.len() == 1 {
|
||||||
|
return match enchant_target(&targets[0], enchantment, level) {
|
||||||
|
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(),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
sender.send_message(msg);
|
||||||
|
Ok(1)
|
||||||
|
}
|
||||||
|
Err(e) => Err(e),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
for target in targets {
|
||||||
|
if enchant_target(target, enchantment, level).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);
|
||||||
|
Ok(successful_targets)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,7 +124,7 @@ fn commands_enchant_failed() -> CommandError {
|
|||||||
CommandError::CommandFailed(msg)
|
CommandError::CommandFailed(msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn enchant_target(
|
fn enchant_target(
|
||||||
target: &Arc<dyn EntityBase>,
|
target: &Arc<dyn EntityBase>,
|
||||||
enchantment: &'static Enchantment,
|
enchantment: &'static Enchantment,
|
||||||
level: i32,
|
level: i32,
|
||||||
|
|||||||
@@ -31,365 +31,316 @@ static ERROR_INVALID_DIMENSION: CommandErrorType<1> =
|
|||||||
|
|
||||||
static DIMENSION_REGISTRY: &Identifier = &Identifier::vanilla_static("dimension");
|
static DIMENSION_REGISTRY: &Identifier = &Identifier::vanilla_static("dimension");
|
||||||
|
|
||||||
fn execute_as_modifier<'a>(
|
fn execute_as_modifier(context: &CommandContext) -> crate::command::node::RedirectModifierResult {
|
||||||
context: &'a CommandContext,
|
let targets = EntityArgumentType::get_optional_entities(context, "targets")?;
|
||||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
let mut sources = Vec::new();
|
||||||
Box::pin(async move {
|
for target in targets {
|
||||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
let mut source = context.source.as_ref().clone();
|
||||||
let mut sources = Vec::new();
|
let display_name = target.get_display_name();
|
||||||
for target in targets {
|
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(context: &CommandContext) -> crate::command::node::RedirectModifierResult {
|
||||||
|
let targets = EntityArgumentType::get_optional_entities(context, "targets")?;
|
||||||
|
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(context: &CommandContext) -> crate::command::node::RedirectModifierResult {
|
||||||
|
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();
|
let mut source = context.source.as_ref().clone();
|
||||||
let display_name = target.get_display_name();
|
source.world = Some(target_world.clone());
|
||||||
let name = target.get_name().get_text();
|
Ok(vec![Arc::new(source)])
|
||||||
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>(
|
fn execute_positioned_modifier(
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
Box::pin(async move {
|
let pos = Vec3ArgumentType::get_vector3(context, "pos")?;
|
||||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
let mut source = context.source.as_ref().clone();
|
||||||
let mut sources = Vec::new();
|
source.position = pos;
|
||||||
for target in targets {
|
Ok(vec![Arc::new(source)])
|
||||||
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>(
|
fn execute_positioned_as_modifier(
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
Box::pin(async move {
|
let targets = EntityArgumentType::get_optional_entities(context, "targets")?;
|
||||||
let dimension_key = ResourceKeyArgument::get_registry_key(
|
let mut sources = Vec::new();
|
||||||
context,
|
for target in targets {
|
||||||
"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();
|
let mut source = context.source.as_ref().clone();
|
||||||
source.position = pos;
|
source.position = target.get_entity().pos.load();
|
||||||
Ok(vec![Arc::new(source)])
|
sources.push(Arc::new(source));
|
||||||
})
|
}
|
||||||
|
Ok(sources)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn execute_positioned_as_modifier<'a>(
|
fn execute_rotated_modifier(
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
Box::pin(async move {
|
let rot_coords = RotationArgumentType::get(context, "rotation")?;
|
||||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
let rot = rot_coords.rotation(&context.source);
|
||||||
let mut sources = Vec::new();
|
let mut source = context.source.as_ref().clone();
|
||||||
for target in targets {
|
source.rotation = rot;
|
||||||
let mut source = context.source.as_ref().clone();
|
Ok(vec![Arc::new(source)])
|
||||||
source.position = target.get_entity().pos.load();
|
|
||||||
sources.push(Arc::new(source));
|
|
||||||
}
|
|
||||||
Ok(sources)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn execute_rotated_modifier<'a>(
|
fn execute_rotated_as_modifier(
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
Box::pin(async move {
|
let targets = EntityArgumentType::get_optional_entities(context, "targets")?;
|
||||||
let rot_coords = RotationArgumentType::get(context, "rotation")?;
|
let mut sources = Vec::new();
|
||||||
let rot = rot_coords.rotation(&context.source);
|
for target in targets {
|
||||||
|
let entity = target.get_entity();
|
||||||
let mut source = context.source.as_ref().clone();
|
let mut source = context.source.as_ref().clone();
|
||||||
source.rotation = rot;
|
source.rotation = Vector2::new(entity.yaw.load(), entity.pitch.load());
|
||||||
Ok(vec![Arc::new(source)])
|
sources.push(Arc::new(source));
|
||||||
})
|
}
|
||||||
|
Ok(sources)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn execute_rotated_as_modifier<'a>(
|
fn execute_if_entity_modifier(
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
Box::pin(async move {
|
let targets = EntityArgumentType::get_optional_entities(context, "targets")?;
|
||||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
if targets.is_empty() {
|
||||||
let mut sources = Vec::new();
|
Ok(vec![])
|
||||||
for target in targets {
|
} else {
|
||||||
let entity = target.get_entity();
|
Ok(vec![context.source.clone()])
|
||||||
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>(
|
fn execute_unless_entity_modifier(
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
Box::pin(async move {
|
let targets = EntityArgumentType::get_optional_entities(context, "targets")?;
|
||||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
if targets.is_empty() {
|
||||||
if targets.is_empty() {
|
Ok(vec![context.source.clone()])
|
||||||
Ok(vec![])
|
} else {
|
||||||
} else {
|
Ok(vec![])
|
||||||
Ok(vec![context.source.clone()])
|
}
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn execute_unless_entity_modifier<'a>(
|
fn execute_align_modifier(
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
Box::pin(async move {
|
let axes = StringArgumentType::get(context, "axes")?;
|
||||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
let mut source = context.source.as_ref().clone();
|
||||||
if targets.is_empty() {
|
|
||||||
Ok(vec![context.source.clone()])
|
let has_x = axes.contains('x');
|
||||||
} else {
|
let has_y = axes.contains('y');
|
||||||
Ok(vec![])
|
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_align_modifier<'a>(
|
fn execute_anchored_modifier(
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
Box::pin(async move {
|
let anchor = EntityAnchorArgumentType::get(context, "anchor")?;
|
||||||
let axes = StringArgumentType::get(context, "axes")?;
|
let mut source = context.source.as_ref().clone();
|
||||||
|
source.entity_anchor = anchor;
|
||||||
|
Ok(vec![Arc::new(source)])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn execute_facing_modifier(
|
||||||
|
context: &CommandContext,
|
||||||
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
|
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(
|
||||||
|
context: &CommandContext,
|
||||||
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
|
let targets = EntityArgumentType::get_optional_entities(context, "targets")?;
|
||||||
|
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 mut source = context.source.as_ref().clone();
|
||||||
|
|
||||||
let has_x = axes.contains('x');
|
let dx = target_pos.x - source.position.x;
|
||||||
let has_y = axes.contains('y');
|
let dy = target_pos.y - source.position.y;
|
||||||
let has_z = axes.contains('z');
|
let dz = target_pos.z - source.position.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 xz_dist = dx.hypot(dz);
|
||||||
let yaw = (dz.atan2(dx).to_degrees() as f32) - 90.0;
|
let yaw = (dz.atan2(dx).to_degrees() as f32) - 90.0;
|
||||||
let pitch = -(dy.atan2(xz_dist).to_degrees() as f32);
|
let pitch = -(dy.atan2(xz_dist).to_degrees() as f32);
|
||||||
|
|
||||||
source.rotation = Vector2::new(yaw, pitch);
|
source.rotation = Vector2::new(yaw, pitch);
|
||||||
Ok(vec![Arc::new(source)])
|
sources.push(Arc::new(source));
|
||||||
})
|
}
|
||||||
|
Ok(sources)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn execute_facing_entity_modifier<'a>(
|
fn execute_if_block_modifier(
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
Box::pin(async move {
|
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||||
let targets = EntityArgumentType::get_optional_entities(context, "targets").await?;
|
let expected_block = BlockArgumentType::get(context, "block")?;
|
||||||
let anchor = EntityAnchorArgumentType::get(context, "anchor")?;
|
|
||||||
let mut sources = Vec::new();
|
|
||||||
|
|
||||||
for target in targets {
|
if let Some(ref world) = context.source.world {
|
||||||
let target_pos = anchor.position_at_entity(target.get_entity());
|
let block = world.get_block(&pos);
|
||||||
let mut source = context.source.as_ref().clone();
|
if block == expected_block {
|
||||||
|
|
||||||
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()]);
|
return Ok(vec![context.source.clone()]);
|
||||||
}
|
}
|
||||||
Ok(vec![])
|
}
|
||||||
})
|
Ok(vec![])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn execute_if_loaded_modifier<'a>(
|
fn execute_unless_block_modifier(
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
Box::pin(async move {
|
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||||
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
let expected_block = BlockArgumentType::get(context, "block")?;
|
||||||
|
|
||||||
if let Some(ref world) = context.source.world
|
if let Some(ref world) = context.source.world {
|
||||||
&& world.is_loaded(&pos)
|
let block = world.get_block(&pos);
|
||||||
{
|
if block != expected_block {
|
||||||
return Ok(vec![context.source.clone()]);
|
return Ok(vec![context.source.clone()]);
|
||||||
}
|
}
|
||||||
Ok(vec![])
|
} else {
|
||||||
})
|
return Ok(vec![context.source.clone()]);
|
||||||
|
}
|
||||||
|
Ok(vec![])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn execute_unless_loaded_modifier<'a>(
|
fn execute_if_loaded_modifier(
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
Box::pin(async move {
|
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
||||||
let pos = BlockPosArgumentType::get_block_pos(context, "pos")?;
|
|
||||||
|
|
||||||
if let Some(ref world) = context.source.world {
|
if let Some(ref world) = context.source.world
|
||||||
if !world.is_loaded(&pos) {
|
&& world.is_loaded(&pos)
|
||||||
return Ok(vec![context.source.clone()]);
|
{
|
||||||
}
|
return Ok(vec![context.source.clone()]);
|
||||||
} else {
|
}
|
||||||
|
Ok(vec![])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn execute_unless_loaded_modifier(
|
||||||
|
context: &CommandContext,
|
||||||
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
|
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()]);
|
return Ok(vec![context.source.clone()]);
|
||||||
}
|
}
|
||||||
Ok(vec![])
|
} else {
|
||||||
})
|
return Ok(vec![context.source.clone()]);
|
||||||
|
}
|
||||||
|
Ok(vec![])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn execute_if_dimension_modifier<'a>(
|
fn execute_if_dimension_modifier(
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
Box::pin(async move {
|
let dimension_key = ResourceKeyArgument::get_registry_key(
|
||||||
let dimension_key = ResourceKeyArgument::get_registry_key(
|
context,
|
||||||
context,
|
"dimension",
|
||||||
"dimension",
|
&Identifier::vanilla_static("dimension"),
|
||||||
&Identifier::vanilla_static("dimension"),
|
&ERROR_INVALID_DIMENSION,
|
||||||
&ERROR_INVALID_DIMENSION,
|
)?;
|
||||||
)?;
|
let dimension_name = dimension_key.identifier.to_string();
|
||||||
let dimension_name = dimension_key.identifier.to_string();
|
|
||||||
|
|
||||||
if let Some(ref world) = context.source.world
|
if let Some(ref world) = context.source.world
|
||||||
&& world.dimension.minecraft_name == dimension_name
|
&& world.dimension.minecraft_name == dimension_name
|
||||||
{
|
{
|
||||||
|
return Ok(vec![context.source.clone()]);
|
||||||
|
}
|
||||||
|
Ok(vec![])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn execute_unless_dimension_modifier(
|
||||||
|
context: &CommandContext,
|
||||||
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
|
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()]);
|
return Ok(vec![context.source.clone()]);
|
||||||
}
|
}
|
||||||
Ok(vec![])
|
} else {
|
||||||
})
|
return Ok(vec![context.source.clone()]);
|
||||||
|
}
|
||||||
|
Ok(vec![])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn execute_unless_dimension_modifier<'a>(
|
fn execute_summon_modifier(
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
) -> crate::command::node::RedirectModifierResult {
|
||||||
Box::pin(async move {
|
let entity_type = ResourceArgument::get_summonable_entity_type(context, "entity_type")?;
|
||||||
let dimension_key = ResourceKeyArgument::get_registry_key(
|
let entity = from_type(
|
||||||
context,
|
entity_type,
|
||||||
"dimension",
|
context.source.position,
|
||||||
&Identifier::vanilla_static("dimension"),
|
context.source.world(),
|
||||||
&ERROR_INVALID_DIMENSION,
|
Uuid::new_v4(),
|
||||||
)?;
|
);
|
||||||
let dimension_name = dimension_key.identifier.to_string();
|
context.source.world().spawn_entity(entity.clone());
|
||||||
|
let mut source = context.source.as_ref().clone();
|
||||||
if let Some(ref world) = context.source.world {
|
source.entity = Some(entity);
|
||||||
if world.dimension.minecraft_name != dimension_name {
|
Ok(vec![Arc::new(source)])
|
||||||
return Ok(vec![context.source.clone()]);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return Ok(vec![context.source.clone()]);
|
|
||||||
}
|
|
||||||
Ok(vec![])
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn execute_summon_modifier<'a>(
|
|
||||||
context: &'a CommandContext,
|
|
||||||
) -> crate::command::node::RedirectModifierResult<'a> {
|
|
||||||
Box::pin(async move {
|
|
||||||
let entity_type = ResourceArgument::get_summonable_entity_type(context, "entity_type")?;
|
|
||||||
let entity = from_type(
|
|
||||||
entity_type,
|
|
||||||
context.source.position,
|
|
||||||
context.source.world(),
|
|
||||||
Uuid::new_v4(),
|
|
||||||
);
|
|
||||||
context.source.world().spawn_entity(entity.clone());
|
|
||||||
let mut source = context.source.as_ref().clone();
|
|
||||||
source.entity = Some(entity);
|
|
||||||
Ok(vec![Arc::new(source)])
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_lines)]
|
#[allow(clippy::too_many_lines)]
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ struct Executor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Executor {
|
impl Executor {
|
||||||
async fn handle_query(&self, sender: &CommandSender, target: &Player) -> i32 {
|
fn handle_query(&self, sender: &CommandSender, target: &Player) -> i32 {
|
||||||
let (val, translation_key) = match self.exp_type {
|
let (val, translation_key) = match self.exp_type {
|
||||||
ExpType::Levels => (
|
ExpType::Levels => (
|
||||||
target.experience_level.load(Ordering::Relaxed),
|
target.experience_level.load(Ordering::Relaxed),
|
||||||
@@ -57,16 +57,14 @@ impl Executor {
|
|||||||
),
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
sender
|
sender.send_message(TextComponent::translate_cross(
|
||||||
.send_message(TextComponent::translate_cross(
|
translation_key,
|
||||||
translation_key,
|
translation_key,
|
||||||
translation_key,
|
[
|
||||||
[
|
target.get_display_name(),
|
||||||
target.get_display_name(),
|
TextComponent::text(val.to_string()),
|
||||||
TextComponent::text(val.to_string()),
|
],
|
||||||
],
|
));
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
val
|
val
|
||||||
}
|
}
|
||||||
@@ -122,7 +120,7 @@ impl Executor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Returns `true` if successful. Otherwise, there was a problem setting the points of a player.
|
/// 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 {
|
fn handle_modify(&self, target: &Arc<Player>, amount: i32) -> bool {
|
||||||
match self.exp_type {
|
match self.exp_type {
|
||||||
ExpType::Levels => {
|
ExpType::Levels => {
|
||||||
if self.mode == Mode::Add {
|
if self.mode == Mode::Add {
|
||||||
@@ -148,59 +146,57 @@ impl Executor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CommandExecutor for Executor {
|
impl CommandExecutor for Executor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
_server: &'a crate::server::Server,
|
_server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let targets = PlayersArgumentConsumer::find_arg(args, ARG_TARGETS)?;
|
||||||
let targets = PlayersArgumentConsumer::find_arg(args, ARG_TARGETS)?;
|
|
||||||
|
|
||||||
if self.mode == Mode::Query {
|
if self.mode == Mode::Query {
|
||||||
let target = targets.first().ok_or_else(|| {
|
let target = targets.first().ok_or_else(|| {
|
||||||
CommandError::CommandFailed(TextComponent::translate_cross(
|
CommandError::CommandFailed(TextComponent::translate_cross(
|
||||||
"argument.player.unknown",
|
"argument.player.unknown",
|
||||||
"argument.player.unknown",
|
"argument.player.unknown",
|
||||||
[],
|
[],
|
||||||
))
|
))
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
if targets.len() > 1 {
|
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(
|
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||||
"commands.experience.set.points.invalid",
|
"argument.player.toomany",
|
||||||
"commands.experience.set.points.invalid",
|
"argument.player.toomany",
|
||||||
[],
|
[],
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
return Ok(self.handle_query(sender, target));
|
||||||
|
}
|
||||||
|
|
||||||
// Safe to access first() because successes > 0
|
// Handle Add/Set
|
||||||
let first_name = targets[0].get_display_name();
|
let amount = BoundedNumArgumentConsumer::<i32>::find_arg(args, ARG_AMOUNT)??;
|
||||||
let msg = self.get_success_message(amount, targets, first_name);
|
|
||||||
sender.send_message(msg).await;
|
|
||||||
|
|
||||||
Ok(successes)
|
let mut successes = 0;
|
||||||
})
|
for target in targets {
|
||||||
|
if self.handle_modify(target, amount) {
|
||||||
|
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();
|
||||||
|
let msg = self.get_success_message(amount, targets, first_name);
|
||||||
|
sender.send_message(msg);
|
||||||
|
|
||||||
|
Ok(successes)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ fn format_clickable_list(items: Vec<TextComponent>) -> TextComponent {
|
|||||||
root
|
root
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn report_resolved_profile(
|
fn report_resolved_profile(
|
||||||
source: &CommandSource,
|
source: &CommandSource,
|
||||||
profile: &GameProfile,
|
profile: &GameProfile,
|
||||||
message_id: &'static str,
|
message_id: &'static str,
|
||||||
@@ -139,7 +139,7 @@ async fn report_resolved_profile(
|
|||||||
|
|
||||||
let msg = TextComponent::translate_cross(message_id, message_id, [argument, clickable]);
|
let msg = TextComponent::translate_cross(message_id, message_id, [argument, clickable]);
|
||||||
|
|
||||||
source.send_feedback(msg, false).await;
|
source.send_feedback(msg, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn fetch_profile_by_name_helper(server: &Server, name: &str) -> Option<GameProfile> {
|
async fn fetch_profile_by_name_helper(server: &Server, name: &str) -> Option<GameProfile> {
|
||||||
@@ -147,7 +147,7 @@ async fn fetch_profile_by_name_helper(server: &Server, name: &str) -> Option<Gam
|
|||||||
return Some(player.gameprofile.clone());
|
return Some(player.gameprofile.clone());
|
||||||
}
|
}
|
||||||
|
|
||||||
let cached_entry = server.data.user_cache.write().await.get_by_name(name);
|
let cached_entry = server.data.user_cache.write().unwrap().get_by_name(name);
|
||||||
|
|
||||||
let auth_config = server
|
let auth_config = server
|
||||||
.advanced_config
|
.advanced_config
|
||||||
@@ -169,7 +169,7 @@ async fn fetch_profile_by_name_helper(server: &Server, name: &str) -> Option<Gam
|
|||||||
.data
|
.data
|
||||||
.user_cache
|
.user_cache
|
||||||
.write()
|
.write()
|
||||||
.await
|
.unwrap()
|
||||||
.upsert(uuid, resolved_name.clone());
|
.upsert(uuid, resolved_name.clone());
|
||||||
let auth_config_clone = server
|
let auth_config_clone = server
|
||||||
.advanced_config
|
.advanced_config
|
||||||
@@ -214,7 +214,7 @@ async fn fetch_profile_by_name_helper(server: &Server, name: &str) -> Option<Gam
|
|||||||
.data
|
.data
|
||||||
.user_cache
|
.user_cache
|
||||||
.write()
|
.write()
|
||||||
.await
|
.unwrap()
|
||||||
.upsert(uuid, name.to_string());
|
.upsert(uuid, name.to_string());
|
||||||
return Some(profile);
|
return Some(profile);
|
||||||
}
|
}
|
||||||
@@ -244,12 +244,12 @@ async fn fetch_profile_by_id_helper(server: &Server, id: Uuid) -> Option<GamePro
|
|||||||
.data
|
.data
|
||||||
.user_cache
|
.user_cache
|
||||||
.write()
|
.write()
|
||||||
.await
|
.unwrap()
|
||||||
.upsert(profile.id, profile.name.clone());
|
.upsert(profile.id, profile.name.clone());
|
||||||
return Some(profile);
|
return Some(profile);
|
||||||
}
|
}
|
||||||
|
|
||||||
let cached_entry = server.data.user_cache.write().await.get_by_uuid(id);
|
let cached_entry = server.data.user_cache.write().unwrap().get_by_uuid(id);
|
||||||
if let Some(entry) = cached_entry {
|
if let Some(entry) = cached_entry {
|
||||||
return Some(GameProfile {
|
return Some(GameProfile {
|
||||||
id: entry.uuid,
|
id: entry.uuid,
|
||||||
@@ -265,102 +265,84 @@ async fn fetch_profile_by_id_helper(server: &Server, id: Uuid) -> Option<GamePro
|
|||||||
struct ResolveNameExecutor;
|
struct ResolveNameExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for ResolveNameExecutor {
|
impl CommandExecutor for ResolveNameExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let name = StringArgumentType::get(context, ARG_NAME)?;
|
||||||
let name = StringArgumentType::get(context, ARG_NAME)?;
|
let server = context.server();
|
||||||
let server = context.server().clone();
|
let name_owned = name.to_string();
|
||||||
let source = context.source.clone();
|
|
||||||
let name_owned = name.to_string();
|
|
||||||
|
|
||||||
tokio::spawn(async move {
|
let name_component = TextComponent::text(name_owned.clone());
|
||||||
let name_component = TextComponent::text(name_owned.clone());
|
let result = futures::executor::block_on(fetch_profile_by_name_helper(server, &name_owned));
|
||||||
let result = fetch_profile_by_name_helper(&server, &name_owned).await;
|
match result {
|
||||||
match result {
|
Some(profile) => {
|
||||||
Some(profile) => {
|
report_resolved_profile(
|
||||||
report_resolved_profile(
|
&context.source,
|
||||||
&source,
|
&profile,
|
||||||
&profile,
|
translation::java::COMMANDS_FETCHPROFILE_NAME_SUCCESS,
|
||||||
translation::java::COMMANDS_FETCHPROFILE_NAME_SUCCESS,
|
name_component,
|
||||||
name_component,
|
);
|
||||||
)
|
}
|
||||||
.await;
|
None => {
|
||||||
}
|
context.source.send_error(TextComponent::translate_cross(
|
||||||
None => {
|
translation::java::COMMANDS_FETCHPROFILE_NAME_FAILURE,
|
||||||
source
|
translation::java::COMMANDS_FETCHPROFILE_NAME_FAILURE,
|
||||||
.send_error(TextComponent::translate_cross(
|
[name_component],
|
||||||
translation::java::COMMANDS_FETCHPROFILE_NAME_FAILURE,
|
));
|
||||||
translation::java::COMMANDS_FETCHPROFILE_NAME_FAILURE,
|
}
|
||||||
[name_component],
|
}
|
||||||
))
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok(1)
|
Ok(1)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ResolveIdExecutor;
|
struct ResolveIdExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for ResolveIdExecutor {
|
impl CommandExecutor for ResolveIdExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let id = UuidArgumentType::get(context, ARG_ID)?;
|
||||||
let id = UuidArgumentType::get(context, ARG_ID)?;
|
let server = context.server();
|
||||||
let server = context.server().clone();
|
|
||||||
let source = context.source.clone();
|
|
||||||
|
|
||||||
tokio::spawn(async move {
|
let id_component = TextComponent::text(id.to_string());
|
||||||
let id_component = TextComponent::text(id.to_string());
|
let result = futures::executor::block_on(fetch_profile_by_id_helper(server, id));
|
||||||
let result = fetch_profile_by_id_helper(&server, id).await;
|
match result {
|
||||||
match result {
|
Some(profile) => {
|
||||||
Some(profile) => {
|
report_resolved_profile(
|
||||||
report_resolved_profile(
|
&context.source,
|
||||||
&source,
|
&profile,
|
||||||
&profile,
|
translation::java::COMMANDS_FETCHPROFILE_ID_SUCCESS,
|
||||||
translation::java::COMMANDS_FETCHPROFILE_ID_SUCCESS,
|
id_component,
|
||||||
id_component,
|
);
|
||||||
)
|
}
|
||||||
.await;
|
None => {
|
||||||
}
|
context.source.send_error(TextComponent::translate_cross(
|
||||||
None => {
|
translation::java::COMMANDS_FETCHPROFILE_ID_FAILURE,
|
||||||
source
|
translation::java::COMMANDS_FETCHPROFILE_ID_FAILURE,
|
||||||
.send_error(TextComponent::translate_cross(
|
[id_component],
|
||||||
translation::java::COMMANDS_FETCHPROFILE_ID_FAILURE,
|
));
|
||||||
translation::java::COMMANDS_FETCHPROFILE_ID_FAILURE,
|
}
|
||||||
[id_component],
|
}
|
||||||
))
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok(1)
|
Ok(1)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct PrintForEntityExecutor;
|
struct PrintForEntityExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for PrintForEntityExecutor {
|
impl CommandExecutor for PrintForEntityExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let entity = EntityArgumentType::get_entity(context, ARG_ENTITY)?;
|
||||||
let entity = EntityArgumentType::get_entity(context, ARG_ENTITY).await?;
|
|
||||||
|
|
||||||
if let Some(player) = entity.get_player() {
|
entity.get_player().map_or_else(
|
||||||
|
|| Err(NO_PROFILE_ERROR_TYPE.create_without_context(entity.get_display_name())),
|
||||||
|
|player| {
|
||||||
report_resolved_profile(
|
report_resolved_profile(
|
||||||
&context.source,
|
&context.source,
|
||||||
&player.gameprofile,
|
&player.gameprofile,
|
||||||
translation::java::COMMANDS_FETCHPROFILE_ENTITY_SUCCESS,
|
translation::java::COMMANDS_FETCHPROFILE_ENTITY_SUCCESS,
|
||||||
player.get_display_name(),
|
player.get_display_name(),
|
||||||
)
|
);
|
||||||
.await;
|
|
||||||
Ok(1)
|
Ok(1)
|
||||||
} else {
|
},
|
||||||
Err(NO_PROFILE_ERROR_TYPE.create_without_context(entity.get_display_name()))
|
)
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -236,96 +236,92 @@ impl Filler for StrictFiller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CommandExecutor for Executor {
|
impl CommandExecutor for Executor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
server: &'a crate::server::Server,
|
server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let block = BlockArgumentConsumer::find_arg(args, ARG_BLOCK)?;
|
||||||
let block = BlockArgumentConsumer::find_arg(args, ARG_BLOCK)?;
|
let block_state_id = block.default_state.id;
|
||||||
let block_state_id = block.default_state.id;
|
let from = BlockPosArgumentConsumer::find_arg(args, ARG_FROM)?;
|
||||||
let from = BlockPosArgumentConsumer::find_arg(args, ARG_FROM)?;
|
let to = BlockPosArgumentConsumer::find_arg(args, ARG_TO)?;
|
||||||
let to = BlockPosArgumentConsumer::find_arg(args, ARG_TO)?;
|
let mode = self.0;
|
||||||
let mode = self.0;
|
|
||||||
|
|
||||||
let mut context = Context {
|
let mut context = Context {
|
||||||
block_state_id,
|
block_state_id,
|
||||||
option_filter: BlockPredicateArgumentConsumer::find_arg(args, ARG_FILTER)?,
|
option_filter: BlockPredicateArgumentConsumer::find_arg(args, ARG_FILTER)?,
|
||||||
world: sender
|
world: sender
|
||||||
.world_or_first(server)
|
.world_or_first(server)
|
||||||
.ok_or(CommandError::InvalidRequirement)?,
|
.ok_or(CommandError::InvalidRequirement)?,
|
||||||
placed_blocks: 0,
|
placed_blocks: 0,
|
||||||
to_update: Vec::new(),
|
to_update: Vec::new(),
|
||||||
|
|
||||||
start_x: from.0.x.min(to.0.x),
|
start_x: from.0.x.min(to.0.x),
|
||||||
start_y: from.0.y.min(to.0.y),
|
start_y: from.0.y.min(to.0.y),
|
||||||
start_z: from.0.z.min(to.0.z),
|
start_z: from.0.z.min(to.0.z),
|
||||||
|
|
||||||
end_x: from.0.x.max(to.0.x),
|
end_x: from.0.x.max(to.0.x),
|
||||||
end_y: from.0.y.max(to.0.y),
|
end_y: from.0.y.max(to.0.y),
|
||||||
end_z: from.0.z.max(to.0.z),
|
end_z: from.0.z.max(to.0.z),
|
||||||
};
|
};
|
||||||
|
|
||||||
if !context.world.is_in_build_limit(from) || !context.world.is_in_build_limit(to) {
|
if !context.world.is_in_build_limit(from) || !context.world.is_in_build_limit(to) {
|
||||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||||
translation::java::ARGUMENT_POS_OUTOFBOUNDS,
|
translation::java::ARGUMENT_POS_OUTOFBOUNDS,
|
||||||
translation::java::ARGUMENT_POS_OUTOFBOUNDS,
|
translation::java::ARGUMENT_POS_OUTOFBOUNDS,
|
||||||
[],
|
[],
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
let max_block_modifications = {
|
let max_block_modifications = {
|
||||||
let level_info = server.level_info.load();
|
let level_info = server.level_info.load();
|
||||||
level_info.game_rules.max_block_modifications
|
level_info.game_rules.max_block_modifications
|
||||||
};
|
};
|
||||||
|
|
||||||
let total_blocks = (context.end_x - context.start_x + 1) as i64
|
let total_blocks = (context.end_x - context.start_x + 1) as i64
|
||||||
* (context.end_y - context.start_y + 1) as i64
|
* (context.end_y - context.start_y + 1) as i64
|
||||||
* (context.end_z - context.start_z + 1) as i64;
|
* (context.end_z - context.start_z + 1) as i64;
|
||||||
|
|
||||||
if total_blocks > max_block_modifications {
|
if total_blocks > max_block_modifications {
|
||||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||||
translation::java::COMMANDS_FILL_TOOBIG,
|
translation::java::COMMANDS_FILL_TOOBIG,
|
||||||
translation::java::COMMANDS_FILL_TOOBIG,
|
translation::java::COMMANDS_FILL_TOOBIG,
|
||||||
[
|
[
|
||||||
TextComponent::text(max_block_modifications.to_string()),
|
TextComponent::text(max_block_modifications.to_string()),
|
||||||
TextComponent::text(total_blocks.to_string()),
|
TextComponent::text(total_blocks.to_string()),
|
||||||
],
|
],
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
match mode {
|
match mode {
|
||||||
Mode::Destroy => DestroyFiller::execute_for_region(&mut context),
|
Mode::Destroy => DestroyFiller::execute_for_region(&mut context),
|
||||||
Mode::Replace => ReplaceFiller::execute_for_region(&mut context),
|
Mode::Replace => ReplaceFiller::execute_for_region(&mut context),
|
||||||
Mode::Keep => KeepFiller::execute_for_region(&mut context),
|
Mode::Keep => KeepFiller::execute_for_region(&mut context),
|
||||||
Mode::Hollow => HollowFiller::execute_for_region(&mut context),
|
Mode::Hollow => HollowFiller::execute_for_region(&mut context),
|
||||||
Mode::Outline => OutlineFiller::execute_for_region(&mut context),
|
Mode::Outline => OutlineFiller::execute_for_region(&mut context),
|
||||||
Mode::Strict => StrictFiller::execute_for_region(&mut context),
|
Mode::Strict => StrictFiller::execute_for_region(&mut context),
|
||||||
}
|
}
|
||||||
|
|
||||||
for i in context.to_update {
|
for i in context.to_update {
|
||||||
context.world.update_neighbors(&i, None);
|
context.world.update_neighbors(&i, None);
|
||||||
}
|
}
|
||||||
|
|
||||||
if context.placed_blocks == 0 {
|
if context.placed_blocks == 0 {
|
||||||
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
return Err(CommandError::CommandFailed(TextComponent::translate_cross(
|
||||||
translation::java::COMMANDS_FILL_FAILED,
|
translation::java::COMMANDS_FILL_FAILED,
|
||||||
translation::bedrock::COMMANDS_FILL_FAILED,
|
translation::bedrock::COMMANDS_FILL_FAILED,
|
||||||
[],
|
[],
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
sender
|
sender.send_message(TextComponent::translate_cross(
|
||||||
.send_message(TextComponent::translate_cross(
|
translation::java::COMMANDS_FILL_SUCCESS,
|
||||||
translation::java::COMMANDS_FILL_SUCCESS,
|
translation::bedrock::COMMANDS_FILL_SUCCESS,
|
||||||
translation::bedrock::COMMANDS_FILL_SUCCESS,
|
[TextComponent::text(context.placed_blocks.to_string())],
|
||||||
[TextComponent::text(context.placed_blocks.to_string())],
|
));
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(context.placed_blocks)
|
Ok(context.placed_blocks)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -31,96 +31,85 @@ struct FillBiomeExecutor {
|
|||||||
|
|
||||||
impl CommandExecutor for FillBiomeExecutor {
|
impl CommandExecutor for FillBiomeExecutor {
|
||||||
#[expect(clippy::too_many_lines)]
|
#[expect(clippy::too_many_lines)]
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let from_pos = BlockPosArgumentType::get_block_pos(context, "from")?;
|
||||||
let from_pos = BlockPosArgumentType::get_block_pos(context, "from")?;
|
let to_pos = BlockPosArgumentType::get_block_pos(context, "to")?;
|
||||||
let to_pos = BlockPosArgumentType::get_block_pos(context, "to")?;
|
|
||||||
|
|
||||||
let world = context.world();
|
let world = context.world();
|
||||||
if !world.is_in_build_limit(from_pos) || !world.is_in_build_limit(to_pos) {
|
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());
|
return Err(OUT_OF_BOUNDS_ERROR_TYPE.create_without_context());
|
||||||
}
|
}
|
||||||
|
|
||||||
let min_x = from_pos.0.x.min(to_pos.0.x);
|
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 max_x = from_pos.0.x.max(to_pos.0.x);
|
||||||
let min_y = from_pos.0.y.min(to_pos.0.y);
|
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 max_y = from_pos.0.y.max(to_pos.0.y);
|
||||||
let min_z = from_pos.0.z.min(to_pos.0.z);
|
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 max_z = from_pos.0.z.max(to_pos.0.z);
|
||||||
|
|
||||||
let biome_min_x = min_x >> 2;
|
let biome_min_x = min_x >> 2;
|
||||||
let biome_max_x = max_x >> 2;
|
let biome_max_x = max_x >> 2;
|
||||||
let biome_min_y = min_y >> 2;
|
let biome_min_y = min_y >> 2;
|
||||||
let biome_max_y = max_y >> 2;
|
let biome_max_y = max_y >> 2;
|
||||||
let biome_min_z = min_z >> 2;
|
let biome_min_z = min_z >> 2;
|
||||||
let biome_max_z = max_z >> 2;
|
let biome_max_z = max_z >> 2;
|
||||||
|
|
||||||
let volume = (biome_max_x - biome_min_x + 1) as i64
|
let volume = (biome_max_x - biome_min_x + 1) as i64
|
||||||
* (biome_max_y - biome_min_y + 1) as i64
|
* (biome_max_y - biome_min_y + 1) as i64
|
||||||
* (biome_max_z - biome_min_z + 1) as i64;
|
* (biome_max_z - biome_min_z + 1) as i64;
|
||||||
|
|
||||||
if volume > MAX_BIOME_BLOCKS {
|
if volume > MAX_BIOME_BLOCKS {
|
||||||
return Err(ERROR_TOOBIG.create_without_context_args_slice(&[
|
return Err(ERROR_TOOBIG.create_without_context_args_slice(&[
|
||||||
TextComponent::text(MAX_BIOME_BLOCKS.to_string()),
|
TextComponent::text(MAX_BIOME_BLOCKS.to_string()),
|
||||||
TextComponent::text(volume.to_string()),
|
TextComponent::text(volume.to_string()),
|
||||||
]));
|
]));
|
||||||
}
|
}
|
||||||
|
|
||||||
let target_biome = ResourceKeyArgument::get_biome(context, "biome")?;
|
let target_biome = ResourceKeyArgument::get_biome(context, "biome")?;
|
||||||
|
|
||||||
let replace_biome = if self.has_replace {
|
let replace_biome = if self.has_replace {
|
||||||
Some(ResourceKeyArgument::get_biome(context, "replace_biome")?)
|
Some(ResourceKeyArgument::get_biome(context, "replace_biome")?)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut chunk_modifications: HashMap<Vector2<i32>, Vec<(usize, usize, usize)>> =
|
let mut chunk_modifications: HashMap<Vector2<i32>, Vec<(usize, usize, usize)>> =
|
||||||
HashMap::new();
|
HashMap::new();
|
||||||
for y in biome_min_y..=biome_max_y {
|
for y in biome_min_y..=biome_max_y {
|
||||||
for z in biome_min_z..=biome_max_z {
|
for z in biome_min_z..=biome_max_z {
|
||||||
for x in biome_min_x..=biome_max_x {
|
for x in biome_min_x..=biome_max_x {
|
||||||
let chunk_pos = Vector2::new(x >> 2, z >> 2);
|
let chunk_pos = Vector2::new(x >> 2, z >> 2);
|
||||||
let rel_x = (x & 3) as usize;
|
let rel_x = (x & 3) as usize;
|
||||||
let rel_z = (z & 3) as usize;
|
let rel_z = (z & 3) as usize;
|
||||||
let rel_y = (y - (world.min_y >> 2)) as usize;
|
let rel_y = (y - (world.min_y >> 2)) as usize;
|
||||||
chunk_modifications
|
chunk_modifications
|
||||||
.entry(chunk_pos)
|
.entry(chunk_pos)
|
||||||
.or_default()
|
.or_default()
|
||||||
.push((rel_x, rel_y, rel_z));
|
.push((rel_x, rel_y, rel_z));
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let target_biome_id = target_biome.id;
|
let target_biome_id = target_biome.id;
|
||||||
let replace_biome_id = replace_biome.map(|b| b.id);
|
let replace_biome_id = replace_biome.map(|b| b.id);
|
||||||
let mut changed_count = 0;
|
let world = context.world().clone();
|
||||||
|
|
||||||
for (chunk_pos, mods) in chunk_modifications {
|
let mut changed_count = 0;
|
||||||
let (has_replaced, count) = world
|
for (chunk_pos, mods) in chunk_modifications {
|
||||||
.level
|
let (has_replaced, count) =
|
||||||
.get_or_fetch_chunk(chunk_pos, |chunk| {
|
futures::executor::block_on(world.level.get_or_fetch_chunk(chunk_pos, |chunk| {
|
||||||
let mut local_count = 0;
|
let mut local_count = 0;
|
||||||
let mut modified = false;
|
let mut modified = false;
|
||||||
for &(rel_x, rel_y, rel_z) in &mods {
|
for &(rel_x, rel_y, rel_z) in &mods {
|
||||||
let section_index = rel_y / 4;
|
let section_index = rel_y / 4;
|
||||||
let scale_y = rel_y % 4;
|
let scale_y = rel_y % 4;
|
||||||
if let Some(current_id) =
|
if let Some(current_id) =
|
||||||
chunk
|
chunk
|
||||||
.section
|
.section
|
||||||
.get_noise_biome(section_index, rel_x, scale_y, rel_z)
|
.get_noise_biome(section_index, rel_x, scale_y, rel_z)
|
||||||
{
|
{
|
||||||
if let Some(replace_id) = replace_biome_id {
|
if let Some(replace_id) = replace_biome_id {
|
||||||
if current_id == replace_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(
|
chunk.section.set_relative_biome(
|
||||||
rel_x,
|
rel_x,
|
||||||
rel_y,
|
rel_y,
|
||||||
@@ -130,31 +119,40 @@ impl CommandExecutor for FillBiomeExecutor {
|
|||||||
local_count += 1;
|
local_count += 1;
|
||||||
modified = true;
|
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)
|
}
|
||||||
})
|
(modified, local_count)
|
||||||
.await;
|
}));
|
||||||
|
|
||||||
if has_replaced {
|
if has_replaced {
|
||||||
changed_count += count;
|
changed_count += count;
|
||||||
let chunk = world
|
let chunk = futures::executor::block_on(
|
||||||
|
world
|
||||||
.level
|
.level
|
||||||
.get_or_fetch_chunk(chunk_pos, std::clone::Clone::clone)
|
.get_or_fetch_chunk(chunk_pos, std::clone::Clone::clone),
|
||||||
.await;
|
);
|
||||||
world.broadcast_to_chunk_except(chunk_pos, &[], &CChunkData(&chunk));
|
world.broadcast_to_chunk_except(chunk_pos, &[], &CChunkData(&chunk));
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let msg = TextComponent::translate_cross(
|
let msg = TextComponent::translate_cross(
|
||||||
translation::java::COMMANDS_FILLBIOME_SUCCESS_COUNT,
|
translation::java::COMMANDS_FILLBIOME_SUCCESS_COUNT,
|
||||||
translation::java::COMMANDS_FILLBIOME_SUCCESS_COUNT,
|
translation::java::COMMANDS_FILLBIOME_SUCCESS_COUNT,
|
||||||
[TextComponent::text(changed_count.to_string())],
|
[TextComponent::text(changed_count.to_string())],
|
||||||
);
|
);
|
||||||
context.source.send_feedback(msg, true).await;
|
context.source.send_feedback(msg, true);
|
||||||
|
|
||||||
Ok(changed_count)
|
Ok(1)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,315 +35,300 @@ static ERROR_TOO_MANY: CommandErrorType<2> = CommandErrorType::new(
|
|||||||
struct ForceloadAddExecutor;
|
struct ForceloadAddExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for ForceloadAddExecutor {
|
impl CommandExecutor for ForceloadAddExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let from_pos = ColumnPosArgumentType::get_column_pos(context, "from")?;
|
||||||
let from_pos = ColumnPosArgumentType::get_column_pos(context, "from")?;
|
|
||||||
|
|
||||||
let to_pos = if context.get_argument::<Coordinates>("to").is_ok() {
|
let to_pos = if context.get_argument::<Coordinates>("to").is_ok() {
|
||||||
ColumnPosArgumentType::get_column_pos(context, "to")?
|
ColumnPosArgumentType::get_column_pos(context, "to")?
|
||||||
} else {
|
} else {
|
||||||
from_pos
|
from_pos
|
||||||
};
|
};
|
||||||
|
|
||||||
let world = context
|
let world = context
|
||||||
.source
|
.source
|
||||||
.world
|
.world
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.ok_or_else(|| ERROR_FAILED_ADD.create_without_context())?;
|
.ok_or_else(|| ERROR_FAILED_ADD.create_without_context())?;
|
||||||
|
|
||||||
let chunk_x_start = from_pos.0.x >> 4;
|
let chunk_x_start = from_pos.0.x >> 4;
|
||||||
let chunk_z_start = from_pos.0.y >> 4;
|
let chunk_z_start = from_pos.0.y >> 4;
|
||||||
|
|
||||||
let chunk_x_end = to_pos.0.x >> 4;
|
let chunk_x_end = to_pos.0.x >> 4;
|
||||||
let chunk_z_end = to_pos.0.y >> 4;
|
let chunk_z_end = to_pos.0.y >> 4;
|
||||||
|
|
||||||
let min_x = chunk_x_start.min(chunk_x_end);
|
let min_x = chunk_x_start.min(chunk_x_end);
|
||||||
let max_x = chunk_x_start.max(chunk_x_end);
|
let max_x = chunk_x_start.max(chunk_x_end);
|
||||||
let min_z = chunk_z_start.min(chunk_z_end);
|
let min_z = chunk_z_start.min(chunk_z_end);
|
||||||
let max_z = chunk_z_start.max(chunk_z_end);
|
let max_z = chunk_z_start.max(chunk_z_end);
|
||||||
|
|
||||||
let count_x = max_x - min_x + 1;
|
let count_x = max_x - min_x + 1;
|
||||||
let count_z = max_z - min_z + 1;
|
let count_z = max_z - min_z + 1;
|
||||||
let total_chunks = count_x * count_z;
|
let total_chunks = count_x * count_z;
|
||||||
|
|
||||||
if total_chunks > 256 {
|
if total_chunks > 256 {
|
||||||
return Err(ERROR_TOO_MANY.create_without_context(
|
return Err(ERROR_TOO_MANY.create_without_context(
|
||||||
TextComponent::text("256"),
|
TextComponent::text("256"),
|
||||||
TextComponent::text(total_chunks.to_string()),
|
TextComponent::text(total_chunks.to_string()),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
let mut forced = world
|
let mut forced = world
|
||||||
.forced_chunks
|
.forced_chunks
|
||||||
.lock()
|
.lock()
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
for x in min_x..=max_x {
|
for x in min_x..=max_x {
|
||||||
for z in min_z..=max_z {
|
for z in min_z..=max_z {
|
||||||
forced.insert(Vector2::new(x, z));
|
forced.insert(Vector2::new(x, z));
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
world.update_active_chunks();
|
world.update_active_chunks();
|
||||||
|
|
||||||
let text = if total_chunks == 1 {
|
let text = if total_chunks == 1 {
|
||||||
TextComponent::translate_cross(
|
TextComponent::translate_cross(
|
||||||
translation::java::COMMANDS_FORCELOAD_ADDED_SINGLE,
|
translation::java::COMMANDS_FORCELOAD_ADDED_SINGLE,
|
||||||
translation::java::COMMANDS_FORCELOAD_ADDED_SINGLE,
|
translation::java::COMMANDS_FORCELOAD_ADDED_SINGLE,
|
||||||
[
|
[
|
||||||
TextComponent::text(min_x.to_string()),
|
TextComponent::text(min_x.to_string()),
|
||||||
TextComponent::text(min_z.to_string()),
|
TextComponent::text(min_z.to_string()),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
TextComponent::translate_cross(
|
TextComponent::translate_cross(
|
||||||
translation::java::COMMANDS_FORCELOAD_ADDED_MULTIPLE,
|
translation::java::COMMANDS_FORCELOAD_ADDED_MULTIPLE,
|
||||||
translation::java::COMMANDS_FORCELOAD_ADDED_MULTIPLE,
|
translation::java::COMMANDS_FORCELOAD_ADDED_MULTIPLE,
|
||||||
[
|
[
|
||||||
TextComponent::text(total_chunks.to_string()),
|
TextComponent::text(total_chunks.to_string()),
|
||||||
TextComponent::text(min_x.to_string()),
|
TextComponent::text(min_x.to_string()),
|
||||||
TextComponent::text(min_z.to_string()),
|
TextComponent::text(min_z.to_string()),
|
||||||
TextComponent::text(max_x.to_string()),
|
TextComponent::text(max_x.to_string()),
|
||||||
TextComponent::text(max_z.to_string()),
|
TextComponent::text(max_z.to_string()),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
context
|
context
|
||||||
.source
|
.source
|
||||||
.send_feedback(text.color(Color::Named(NamedColor::Green)), false)
|
.send_feedback(text.color(Color::Named(NamedColor::Green)), false);
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(total_chunks)
|
Ok(total_chunks)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ForceloadRemoveExecutor;
|
struct ForceloadRemoveExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for ForceloadRemoveExecutor {
|
impl CommandExecutor for ForceloadRemoveExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let from_pos = ColumnPosArgumentType::get_column_pos(context, "from")?;
|
||||||
let from_pos = ColumnPosArgumentType::get_column_pos(context, "from")?;
|
|
||||||
|
|
||||||
let to_pos = if context.get_argument::<Coordinates>("to").is_ok() {
|
let to_pos = if context.get_argument::<Coordinates>("to").is_ok() {
|
||||||
ColumnPosArgumentType::get_column_pos(context, "to")?
|
ColumnPosArgumentType::get_column_pos(context, "to")?
|
||||||
} else {
|
} else {
|
||||||
from_pos
|
from_pos
|
||||||
};
|
};
|
||||||
|
|
||||||
let world = context
|
let world = context
|
||||||
.source
|
.source
|
||||||
.world
|
.world
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.ok_or_else(|| ERROR_FAILED_REMOVE.create_without_context())?;
|
.ok_or_else(|| ERROR_FAILED_REMOVE.create_without_context())?;
|
||||||
|
|
||||||
let chunk_x_start = from_pos.0.x >> 4;
|
let chunk_x_start = from_pos.0.x >> 4;
|
||||||
let chunk_z_start = from_pos.0.y >> 4;
|
let chunk_z_start = from_pos.0.y >> 4;
|
||||||
|
|
||||||
let chunk_x_end = to_pos.0.x >> 4;
|
let chunk_x_end = to_pos.0.x >> 4;
|
||||||
let chunk_z_end = to_pos.0.y >> 4;
|
let chunk_z_end = to_pos.0.y >> 4;
|
||||||
|
|
||||||
let min_x = chunk_x_start.min(chunk_x_end);
|
let min_x = chunk_x_start.min(chunk_x_end);
|
||||||
let max_x = chunk_x_start.max(chunk_x_end);
|
let max_x = chunk_x_start.max(chunk_x_end);
|
||||||
let min_z = chunk_z_start.min(chunk_z_end);
|
let min_z = chunk_z_start.min(chunk_z_end);
|
||||||
let max_z = chunk_z_start.max(chunk_z_end);
|
let max_z = chunk_z_start.max(chunk_z_end);
|
||||||
|
|
||||||
let count_x = max_x - min_x + 1;
|
let count_x = max_x - min_x + 1;
|
||||||
let count_z = max_z - min_z + 1;
|
let count_z = max_z - min_z + 1;
|
||||||
let total_chunks = count_x * count_z;
|
let total_chunks = count_x * count_z;
|
||||||
|
|
||||||
if total_chunks > 256 {
|
if total_chunks > 256 {
|
||||||
return Err(ERROR_TOO_MANY.create_without_context(
|
return Err(ERROR_TOO_MANY.create_without_context(
|
||||||
TextComponent::text("256"),
|
TextComponent::text("256"),
|
||||||
TextComponent::text(total_chunks.to_string()),
|
TextComponent::text(total_chunks.to_string()),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
let mut forced = world
|
let mut forced = world
|
||||||
.forced_chunks
|
.forced_chunks
|
||||||
.lock()
|
.lock()
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
for x in min_x..=max_x {
|
for x in min_x..=max_x {
|
||||||
for z in min_z..=max_z {
|
for z in min_z..=max_z {
|
||||||
forced.remove(&Vector2::new(x, z));
|
forced.remove(&Vector2::new(x, z));
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
world.update_active_chunks();
|
world.update_active_chunks();
|
||||||
|
|
||||||
let text = if total_chunks == 1 {
|
let text = if total_chunks == 1 {
|
||||||
TextComponent::translate_cross(
|
TextComponent::translate_cross(
|
||||||
translation::java::COMMANDS_FORCELOAD_REMOVED_SINGLE,
|
translation::java::COMMANDS_FORCELOAD_REMOVED_SINGLE,
|
||||||
translation::java::COMMANDS_FORCELOAD_REMOVED_SINGLE,
|
translation::java::COMMANDS_FORCELOAD_REMOVED_SINGLE,
|
||||||
[
|
[
|
||||||
TextComponent::text(min_x.to_string()),
|
TextComponent::text(min_x.to_string()),
|
||||||
TextComponent::text(min_z.to_string()),
|
TextComponent::text(min_z.to_string()),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
TextComponent::translate_cross(
|
TextComponent::translate_cross(
|
||||||
translation::java::COMMANDS_FORCELOAD_REMOVED_MULTIPLE,
|
translation::java::COMMANDS_FORCELOAD_REMOVED_MULTIPLE,
|
||||||
translation::java::COMMANDS_FORCELOAD_REMOVED_MULTIPLE,
|
translation::java::COMMANDS_FORCELOAD_REMOVED_MULTIPLE,
|
||||||
[
|
[
|
||||||
TextComponent::text(total_chunks.to_string()),
|
TextComponent::text(total_chunks.to_string()),
|
||||||
TextComponent::text(min_x.to_string()),
|
TextComponent::text(min_x.to_string()),
|
||||||
TextComponent::text(min_z.to_string()),
|
TextComponent::text(min_z.to_string()),
|
||||||
TextComponent::text(max_x.to_string()),
|
TextComponent::text(max_x.to_string()),
|
||||||
TextComponent::text(max_z.to_string()),
|
TextComponent::text(max_z.to_string()),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
context
|
context
|
||||||
.source
|
.source
|
||||||
.send_feedback(text.color(Color::Named(NamedColor::Green)), false)
|
.send_feedback(text.color(Color::Named(NamedColor::Green)), false);
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(total_chunks)
|
Ok(total_chunks)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ForceloadRemoveAllExecutor;
|
struct ForceloadRemoveAllExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for ForceloadRemoveAllExecutor {
|
impl CommandExecutor for ForceloadRemoveAllExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let world = context
|
||||||
let world = context
|
.source
|
||||||
.source
|
.world
|
||||||
.world
|
.as_ref()
|
||||||
.as_ref()
|
.ok_or_else(|| ERROR_FAILED_REMOVE.create_without_context())?;
|
||||||
.ok_or_else(|| ERROR_FAILED_REMOVE.create_without_context())?;
|
|
||||||
|
|
||||||
let removed_count = {
|
let removed_count = {
|
||||||
let mut forced = world
|
let mut forced = world
|
||||||
.forced_chunks
|
.forced_chunks
|
||||||
.lock()
|
.lock()
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
let count = forced.len();
|
let count = forced.len();
|
||||||
forced.clear();
|
forced.clear();
|
||||||
count
|
count
|
||||||
};
|
};
|
||||||
|
|
||||||
world.update_active_chunks();
|
world.update_active_chunks();
|
||||||
|
|
||||||
let text = TextComponent::translate_cross(
|
let text = TextComponent::translate_cross(
|
||||||
translation::java::COMMANDS_FORCELOAD_REMOVED_ALL,
|
translation::java::COMMANDS_FORCELOAD_REMOVED_ALL,
|
||||||
translation::java::COMMANDS_FORCELOAD_REMOVED_ALL,
|
translation::java::COMMANDS_FORCELOAD_REMOVED_ALL,
|
||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
context
|
context
|
||||||
.source
|
.source
|
||||||
.send_feedback(text.color(Color::Named(NamedColor::Green)), false)
|
.send_feedback(text.color(Color::Named(NamedColor::Green)), false);
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(removed_count as i32)
|
Ok(removed_count as i32)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ForceloadQueryExecutor;
|
struct ForceloadQueryExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for ForceloadQueryExecutor {
|
impl CommandExecutor for ForceloadQueryExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let world = context
|
||||||
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_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
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
|
.source
|
||||||
.world
|
.send_feedback(text.color(Color::Named(NamedColor::Green)), false);
|
||||||
.as_ref()
|
} else {
|
||||||
.ok_or_else(|| ERROR_FAILED_QUERY.create_without_context())?;
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
let chunk_pos = if context.get_argument::<Coordinates>("pos").is_ok() {
|
let all_forced = {
|
||||||
let pos = ColumnPosArgumentType::get_column_pos(context, "pos")?;
|
let forced = world
|
||||||
Vector2::new(pos.0.x >> 4, pos.0.y >> 4)
|
.forced_chunks
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
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);
|
||||||
|
} 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 {
|
} else {
|
||||||
let block_x = context.source.position.x.floor() as i32;
|
TextComponent::translate_cross(
|
||||||
let block_z = context.source.position.z.floor() as i32;
|
translation::java::COMMANDS_FORCELOAD_LIST_MULTIPLE,
|
||||||
Vector2::new(block_x >> 4, block_z >> 4)
|
translation::java::COMMANDS_FORCELOAD_LIST_MULTIPLE,
|
||||||
|
[TextComponent::text(list_str)],
|
||||||
|
)
|
||||||
};
|
};
|
||||||
|
context
|
||||||
|
.source
|
||||||
|
.send_feedback(text.color(Color::Named(NamedColor::Gray)), false);
|
||||||
|
}
|
||||||
|
|
||||||
let is_forced = {
|
Ok(i32::from(is_forced))
|
||||||
let forced = world
|
|
||||||
.forced_chunks
|
|
||||||
.lock()
|
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
|
||||||
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_or_else(std::sync::PoisonError::into_inner);
|
|
||||||
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))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,73 +23,63 @@ static ERROR_UNKNOWN_FUNCTION: CommandErrorType<1> = CommandErrorType::new(
|
|||||||
struct FunctionSuggestionProvider;
|
struct FunctionSuggestionProvider;
|
||||||
|
|
||||||
impl SuggestionProvider for FunctionSuggestionProvider {
|
impl SuggestionProvider for FunctionSuggestionProvider {
|
||||||
fn suggest<'a>(
|
fn suggest(
|
||||||
&'a self,
|
&self,
|
||||||
context: &'a CommandContext,
|
context: &CommandContext,
|
||||||
mut builder: SuggestionsBuilder,
|
mut builder: SuggestionsBuilder,
|
||||||
) -> SuggestionProviderResult<'a> {
|
) -> SuggestionProviderResult {
|
||||||
Box::pin(async move {
|
let server = context.server();
|
||||||
let server = context.server();
|
let function_names = server.datapack_manager.get_function_names();
|
||||||
let function_names = server.datapack_manager.get_function_names().await;
|
for name in function_names {
|
||||||
for name in function_names {
|
builder = builder.suggest(name);
|
||||||
builder = builder.suggest(name);
|
}
|
||||||
}
|
builder.build()
|
||||||
builder.build()
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct FunctionExecutor;
|
struct FunctionExecutor;
|
||||||
|
|
||||||
impl CommandExecutor for FunctionExecutor {
|
impl CommandExecutor for FunctionExecutor {
|
||||||
fn execute<'a>(&'a self, context: &'a CommandContext) -> CommandExecutorResult<'a> {
|
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||||
Box::pin(async move {
|
let name_str = StringArgumentType::get(context, "name")?;
|
||||||
let name_str = StringArgumentType::get(context, "name")?;
|
let server = context.server();
|
||||||
let server = context.server();
|
|
||||||
|
|
||||||
let Ok(executed_count) = server
|
let Ok(executed_count) =
|
||||||
|
server
|
||||||
.datapack_manager
|
.datapack_manager
|
||||||
.execute_function(server, &context.source, name_str)
|
.execute_function(server, &context.source, name_str)
|
||||||
.await
|
else {
|
||||||
else {
|
return Err(ERROR_UNKNOWN_FUNCTION
|
||||||
return Err(ERROR_UNKNOWN_FUNCTION
|
.create_without_context(TextComponent::text(name_str.to_string())));
|
||||||
.create_without_context(TextComponent::text(name_str.to_string())));
|
};
|
||||||
};
|
|
||||||
|
|
||||||
if name_str.starts_with('#') {
|
if name_str.starts_with('#') {
|
||||||
context
|
context.source.send_feedback(
|
||||||
.source
|
TextComponent::translate_cross(
|
||||||
.send_feedback(
|
translation::java::COMMANDS_FUNCTION_SUCCESS_MULTIPLE,
|
||||||
TextComponent::translate_cross(
|
translation::java::COMMANDS_FUNCTION_SUCCESS_MULTIPLE,
|
||||||
translation::java::COMMANDS_FUNCTION_SUCCESS_MULTIPLE,
|
[
|
||||||
translation::java::COMMANDS_FUNCTION_SUCCESS_MULTIPLE,
|
TextComponent::text(executed_count.to_string()),
|
||||||
[
|
TextComponent::text(name_str.to_string()),
|
||||||
TextComponent::text(executed_count.to_string()),
|
],
|
||||||
TextComponent::text(name_str.to_string()),
|
),
|
||||||
],
|
true,
|
||||||
),
|
);
|
||||||
true,
|
} else {
|
||||||
)
|
context.source.send_feedback(
|
||||||
.await;
|
TextComponent::translate_cross(
|
||||||
} else {
|
translation::java::COMMANDS_FUNCTION_SUCCESS_SINGLE,
|
||||||
context
|
translation::java::COMMANDS_FUNCTION_SUCCESS_SINGLE,
|
||||||
.source
|
[
|
||||||
.send_feedback(
|
TextComponent::text(executed_count.to_string()),
|
||||||
TextComponent::translate_cross(
|
TextComponent::text(name_str.to_string()),
|
||||||
translation::java::COMMANDS_FUNCTION_SUCCESS_SINGLE,
|
],
|
||||||
translation::java::COMMANDS_FUNCTION_SUCCESS_SINGLE,
|
),
|
||||||
[
|
true,
|
||||||
TextComponent::text(executed_count.to_string()),
|
);
|
||||||
TextComponent::text(name_str.to_string()),
|
}
|
||||||
],
|
|
||||||
),
|
|
||||||
true,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(executed_count as i32)
|
Ok(executed_count as i32)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -25,72 +25,65 @@ struct TargetExecutor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CommandExecutor for TargetExecutor {
|
impl CommandExecutor for TargetExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
server: &'a crate::server::Server,
|
server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let Some(Arg::GameMode(gamemode)) = args.get_cloned(&ARG_GAMEMODE) else {
|
||||||
let Some(Arg::GameMode(gamemode)) = args.get_cloned(&ARG_GAMEMODE) else {
|
return Err(InvalidConsumption(Some(ARG_GAMEMODE.into())));
|
||||||
return Err(InvalidConsumption(Some(ARG_GAMEMODE.into())));
|
};
|
||||||
};
|
|
||||||
|
|
||||||
let targets = if self.is_self {
|
let targets = if self.is_self {
|
||||||
let Some(player) = sender.as_player() else {
|
let Some(player) = sender.as_player() else {
|
||||||
return Err(InvalidRequirement);
|
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()
|
|
||||||
};
|
};
|
||||||
|
&[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;
|
let mut succeeded: i32 = 0;
|
||||||
for target in targets {
|
for target in targets {
|
||||||
if target.set_gamemode(gamemode).await {
|
if target.gamemode.load() != gamemode {
|
||||||
succeeded += 1;
|
target.set_gamemode(gamemode);
|
||||||
let gamemode_string = format!("{gamemode:?}").to_lowercase();
|
succeeded += 1;
|
||||||
let gamemode_string = format!("gameMode.{gamemode_string}");
|
let gamemode_string = format!("{gamemode:?}").to_lowercase();
|
||||||
// Checking if the target was the sender of this command.
|
let gamemode_string = format!("gameMode.{gamemode_string}");
|
||||||
let gamemode_comp = TextComponent::translate_cross(
|
// Checking if the target was the sender of this command.
|
||||||
gamemode_string.clone(),
|
let gamemode_comp = TextComponent::translate_cross(
|
||||||
gamemode_string.clone(),
|
gamemode_string.clone(),
|
||||||
[],
|
gamemode_string.clone(),
|
||||||
);
|
[],
|
||||||
if sender.as_player().as_ref() == Some(target) {
|
);
|
||||||
target
|
if sender.as_player().as_ref() == Some(target) {
|
||||||
.send_system_message(&TextComponent::translate_cross(
|
target.send_system_message(&TextComponent::translate_cross(
|
||||||
translation::java::COMMANDS_GAMEMODE_SUCCESS_SELF,
|
translation::java::COMMANDS_GAMEMODE_SUCCESS_SELF,
|
||||||
translation::bedrock::COMMANDS_GAMEMODE_SUCCESS_SELF,
|
translation::bedrock::COMMANDS_GAMEMODE_SUCCESS_SELF,
|
||||||
[gamemode_comp],
|
[gamemode_comp],
|
||||||
))
|
));
|
||||||
.await;
|
} else {
|
||||||
} else {
|
if server.level_info.load().game_rules.send_command_feedback {
|
||||||
if server.level_info.load().game_rules.send_command_feedback {
|
target.send_system_message(&TextComponent::translate_cross(
|
||||||
target
|
translation::java::GAMEMODE_CHANGED,
|
||||||
.send_system_message(&TextComponent::translate_cross(
|
translation::bedrock::GAMEMODE_CHANGED,
|
||||||
translation::java::GAMEMODE_CHANGED,
|
[gamemode_comp.clone()],
|
||||||
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(), gamemode_comp],
|
|
||||||
))
|
|
||||||
.await;
|
|
||||||
}
|
}
|
||||||
|
sender.send_message(TextComponent::translate_cross(
|
||||||
|
translation::java::COMMANDS_GAMEMODE_SUCCESS_OTHER,
|
||||||
|
translation::bedrock::COMMANDS_GAMEMODE_SUCCESS_OTHER,
|
||||||
|
[target.get_display_name(), gamemode_comp],
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(succeeded)
|
Ok(succeeded)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,35 +20,29 @@ const ARG_NAME: &str = "value";
|
|||||||
struct QueryExecutor(GameRule);
|
struct QueryExecutor(GameRule);
|
||||||
|
|
||||||
impl CommandExecutor for QueryExecutor {
|
impl CommandExecutor for QueryExecutor {
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
server: &'a crate::server::Server,
|
server: &crate::server::Server,
|
||||||
_args: &'a ConsumedArgs<'a>,
|
_args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let key = TextComponent::text(self.0.to_string());
|
||||||
let key = TextComponent::text(self.0.to_string());
|
let level_info = server.level_info.load();
|
||||||
let level_info = server.level_info.load();
|
let game_rule = level_info.game_rules.get(&self.0);
|
||||||
let game_rule = level_info.game_rules.get(&self.0);
|
let game_rule_i32_value = match game_rule {
|
||||||
let game_rule_i32_value = match game_rule {
|
GameRuleValue::Int(value) => (*value).clamp(i32::MIN as i64, i32::MAX as i64) as i32,
|
||||||
GameRuleValue::Int(value) => {
|
GameRuleValue::Bool(value) => *value as i32,
|
||||||
(*value).clamp(i32::MIN as i64, i32::MAX as i64) as i32
|
};
|
||||||
}
|
let value = TextComponent::text(game_rule.to_string());
|
||||||
GameRuleValue::Bool(value) => *value as i32,
|
drop(level_info);
|
||||||
};
|
|
||||||
let value = TextComponent::text(game_rule.to_string());
|
|
||||||
drop(level_info);
|
|
||||||
|
|
||||||
sender
|
sender.send_message(TextComponent::translate_cross(
|
||||||
.send_message(TextComponent::translate_cross(
|
"commands.gamerule.query",
|
||||||
"commands.gamerule.query",
|
"commands.gamerule.query",
|
||||||
"commands.gamerule.query",
|
[key, value],
|
||||||
[key, value],
|
));
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(game_rule_i32_value)
|
Ok(game_rule_i32_value)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,53 +50,49 @@ struct SetExecutor(GameRule);
|
|||||||
|
|
||||||
impl CommandExecutor for SetExecutor {
|
impl CommandExecutor for SetExecutor {
|
||||||
#[expect(unused)]
|
#[expect(unused)]
|
||||||
fn execute<'a>(
|
fn execute(
|
||||||
&'a self,
|
&self,
|
||||||
sender: &'a CommandSender,
|
sender: &CommandSender,
|
||||||
server: &'a crate::server::Server,
|
server: &crate::server::Server,
|
||||||
args: &'a ConsumedArgs<'a>,
|
args: &ConsumedArgs,
|
||||||
) -> CommandResult<'a> {
|
) -> CommandResult {
|
||||||
Box::pin(async move {
|
let key = TextComponent::text(self.0.to_string());
|
||||||
let key = TextComponent::text(self.0.to_string());
|
let current_info = server.level_info.load();
|
||||||
let current_info = server.level_info.load();
|
|
||||||
|
|
||||||
let mut new_info = (**current_info).clone();
|
let mut new_info = (**current_info).clone();
|
||||||
|
|
||||||
let mut output_value = String::new();
|
let mut output_value = String::new();
|
||||||
let mut result_i32: i32;
|
let mut result_i32: i32;
|
||||||
|
|
||||||
let raw_value = new_info.game_rules.get_mut(&self.0);
|
let raw_value = new_info.game_rules.get_mut(&self.0);
|
||||||
|
|
||||||
match raw_value {
|
match raw_value {
|
||||||
GameRuleValue::Int(value) => {
|
GameRuleValue::Int(value) => {
|
||||||
let arg_value = BoundedNumArgumentConsumer::<i64>::find_arg(args, ARG_NAME)??;
|
let arg_value = BoundedNumArgumentConsumer::<i64>::find_arg(args, ARG_NAME)??;
|
||||||
*value = arg_value;
|
*value = arg_value;
|
||||||
output_value = arg_value.to_string();
|
output_value = arg_value.to_string();
|
||||||
// TODO: Should integer gamerule values be kept as a `i64` or should it be changed to an `i32`?
|
// TODO: Should integer gamerule values be kept as a `i64` or should it be changed to an `i32`?
|
||||||
// For now, we can cast it
|
// For now, we can cast it
|
||||||
result_i32 = arg_value.clamp(i32::MIN as i64, i32::MAX as i64) as i32;
|
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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
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));
|
server.level_info.store(std::sync::Arc::new(new_info));
|
||||||
|
|
||||||
let value_component = TextComponent::text(output_value);
|
let value_component = TextComponent::text(output_value);
|
||||||
sender
|
sender.send_message(TextComponent::translate_cross(
|
||||||
.send_message(TextComponent::translate_cross(
|
"commands.gamerule.set",
|
||||||
"commands.gamerule.set",
|
"commands.gamerule.set",
|
||||||
"commands.gamerule.set",
|
[key, value_component],
|
||||||
[key, value_component],
|
));
|
||||||
))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(result_i32)
|
Ok(result_i32)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loaded 100 of 222 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user