Firework tooltips: flight duration and explosions (Fireworks.addToTooltip)

Rockets list their flight duration and each run of equal explosions (shape,
colours, fade colours, trail, twinkle); firework stars list their explosion.
Both honour TooltipDisplay. New harness: tools/test_firework_tooltip_parity.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-21 16:14:33 +02:00
parent 85f65a69b7
commit 8f13b2be8c
8 changed files with 264 additions and 24 deletions
@@ -0,0 +1,29 @@
//! Firework tooltip companion for tools/test_firework_tooltip_parity.py: the
//! lines `item_tooltip::firework_lines` gives each stack (SNBT, one per line;
//! the `#resources` line names the prepared resources for en_us).
use horizon_client::{item_data::parse_stack, item_tooltip::firework_lines, lang::Language};
use std::{error::Error, fmt::Write, path::PathBuf};
fn main() -> Result<(), Box<dyn Error>> {
let args: Vec<String> = std::env::args().collect();
let input = std::fs::read_to_string(&args[1])?;
let root = input
.lines()
.find_map(|l| l.strip_prefix("#resources "))
.map(PathBuf::from)
.ok_or("no #resources line")?;
let language = Language::load(&[&root], "en_us");
let translate = |key: &str| language.get(key).map(str::to_owned);
let mut output = String::new();
for line in input.lines().filter(|l| !l.starts_with('#')) {
let stack = parse_stack(line)?.ok_or("empty stack")?;
let lines = firework_lines(&stack, &translate);
if lines.is_empty() {
writeln!(output, "-")?;
} else {
writeln!(output, "{}", lines.join(" | "))?;
}
}
std::fs::write(&args[2], output)?;
Ok(())
}
+3 -9
View File
@@ -7,7 +7,7 @@ use crate::{
Result,
item_data::StackData,
items::{ItemStack, Items},
particles::{FireworkExplosion, FireworkShape},
particles::{DYE_FIREWORK_COLORS, FireworkExplosion, FireworkShape},
};
use horizon_world::nbt::Tag;
use serde_json::Value;
@@ -18,12 +18,6 @@ use std::{
sync::Arc,
};
/// `DyeColor.getFireworkColor` in dye order (white to black).
const FIREWORK_COLORS: [u32; 16] = [
15_790_320, 15_435_844, 12_801_229, 6_719_955, 14_602_026, 4_312_372, 14_188_952, 4_408_131,
11_250_603, 2_651_799, 8_073_150, 2_437_522, 5_320_730, 3_887_386, 11_743_532, 1_973_019,
];
/// A set of accepted items (expanded from an item, list or tag), and the
/// items in its `HolderSet` order (`Ingredient.display`'s `TagSlotDisplay`).
#[derive(Clone, Debug)]
@@ -965,7 +959,7 @@ impl Special {
} else if trail.test(s) {
has_trail = true;
} else if dye.test(s) {
colors.push(FIREWORK_COLORS[ctx.dye(s).unwrap_or(0)]);
colors.push(DYE_FIREWORK_COLORS[ctx.dye(s).unwrap_or(0)].1);
}
}
let mut out = result.create();
@@ -987,7 +981,7 @@ impl Special {
let mut target_stack = None;
for s in &stacks {
if dye.test(s) {
colors.push(FIREWORK_COLORS[ctx.dye(s).unwrap_or(0)]);
colors.push(DYE_FIREWORK_COLORS[ctx.dye(s).unwrap_or(0)].1);
} else if target.test(s) {
target_stack = Some(*s);
}
+1 -7
View File
@@ -204,12 +204,6 @@ impl PatrolLevel for PatrolCx<'_, '_, '_> {
}
}
/// `DyeColor.getFireworkColor`.
const FIREWORK_COLORS: [u32; 16] = [
0xF0F0F0, 0xEB8844, 0xC354CD, 0x6689D3, 0xDECF2A, 0x41CD34, 0xD88198, 0x434343, 0xABABAB,
0x287697, 0x7B2FBE, 0x253192, 0x51301A, 0x3B511A, 0xB3312C, 0x1E1B1B,
];
fn block_of(p: Vec3) -> [i32; 3] {
[p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]
}
@@ -1108,7 +1102,7 @@ impl Game<'_> {
flight,
vec![horizon_client::particles::FireworkExplosion {
shape: horizon_client::particles::FireworkShape::Burst,
colors: vec![FIREWORK_COLORS[color & 15]],
colors: vec![horizon_client::particles::DYE_FIREWORK_COLORS[color & 15].1],
fade: Vec::new(),
trail: false,
twinkle: false,
@@ -1912,6 +1912,10 @@ impl Game<'_> {
lines.push((line, u32::MAX));
}
}
// Fireworks / FireworkExplosion.addToTooltip.
for line in horizon_client::item_tooltip::firework_lines(stack, &translate) {
lines.push((line, rgba(170, 170, 170, 255)));
}
if display.shows("minecraft:potion_contents")
&& (stack.item.ends_with("potion") || &*stack.item == "minecraft:tipped_arrow")
{
+96 -8
View File
@@ -277,14 +277,6 @@ pub fn detail_lines(
);
}
let data = stack.data();
// FireworkRocketItem: the flight duration (an unset component is 1).
if path == "firework_rocket" {
let flight = data.and_then(|d| d.fireworks.as_ref()).map_or(1, |f| f.0);
lines.push(format!(
"{} {flight}",
text("item.minecraft.firework_rocket.flight")
));
}
// PotDecorations.addToTooltip.
if let Some(sherds) = data
.and_then(|d| d.pot_decorations.as_ref())
@@ -296,6 +288,7 @@ pub fn detail_lines(
lines.push(name_line(&ItemStack::new(item, 1), translate));
}
}
lines.extend(firework_lines(stack, translate));
// PotionContents.addToTooltip: the effects, then their attribute modifiers.
if is_potion_item(&stack.item) {
let scale = match path {
@@ -361,6 +354,101 @@ pub fn detail_lines(
lines
}
/// `Fireworks.addToTooltip` (a rocket's flight duration, its explosions with
/// runs of equal ones counted) and `FireworkExplosion.addToTooltip` (a
/// star's), unless the stack's tooltip display hides them. A rocket without
/// the component has the item's default: flight duration 1, no explosions.
pub fn firework_lines(
stack: &ItemStack,
translate: &dyn Fn(&str) -> Option<String>,
) -> Vec<String> {
use crate::particles::FireworkExplosion;
let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned());
let shape = |e: &FireworkExplosion| {
text(&format!(
"item.minecraft.firework_star.shape.{}",
e.shape.name()
))
};
// FireworkExplosion.appendColors: dye names (getColorName), comma-separated.
let colors = |colors: &[u32]| {
colors
.iter()
.map(|c| {
match crate::particles::DYE_FIREWORK_COLORS
.iter()
.find(|(_, firework)| firework == c)
{
Some((name, _)) => text(&format!("item.minecraft.firework_star.{name}")),
None => text("item.minecraft.firework_star.custom_color"),
}
})
.collect::<Vec<_>>()
.join(", ")
};
// FireworkExplosion.addAdditionalTooltip.
let details = |e: &FireworkExplosion, indent: &str, lines: &mut Vec<String>| {
if !e.colors.is_empty() {
lines.push(format!("{indent}{}", colors(&e.colors)));
}
if !e.fade.is_empty() {
let fade = text("item.minecraft.firework_star.fade_to");
lines.push(format!("{indent}{fade} {}", colors(&e.fade)));
}
if e.trail {
lines.push(format!(
"{indent}{}",
text("item.minecraft.firework_star.trail")
));
}
if e.twinkle {
lines.push(format!(
"{indent}{}",
text("item.minecraft.firework_star.flicker")
));
}
};
let display = TooltipDisplay::for_stack(stack);
let data = stack.data();
let mut lines = Vec::new();
let fireworks = match data.and_then(|d| d.fireworks.as_ref()) {
Some((flight, explosions)) => Some((*flight, explosions.as_slice())),
None => (&*stack.item == "minecraft:firework_rocket").then_some((1, &[][..])),
};
if let Some((flight, explosions)) = fireworks
&& display.shows("minecraft:fireworks")
{
if flight > 0 {
lines.push(
text("item.minecraft.firework_rocket.flight_duration").replacen(
"%s",
&flight.to_string(),
1,
),
);
}
// Fireworks.addExplosionTooltip for each run of equal explosions.
for run in explosions.chunk_by(|a, b| a == b) {
let e = &run[0];
lines.push(if run.len() == 1 {
text("item.minecraft.firework_rocket.single_star").replacen("%s", &shape(e), 1)
} else {
text("item.minecraft.firework_rocket.multiple_stars")
.replacen("%s", &run.len().to_string(), 1)
.replacen("%s", &shape(e), 1)
});
details(e, " ", &mut lines);
}
}
if let Some(e) = data.and_then(|d| d.firework_explosion.as_ref())
&& display.shows("minecraft:firework_explosion")
{
lines.push(shape(e));
details(e, "", &mut lines);
}
lines
}
/// `ItemContainerContents.addToTooltip`: "count x name" for the first five
/// stacks, by slot, then how many more there are (an italic line).
pub fn container_lines(
+19
View File
@@ -4013,6 +4013,25 @@ impl FireworkShape {
}
}
}
/// `DyeColor` names and `getFireworkColor`, by dye id (white to black).
pub const DYE_FIREWORK_COLORS: [(&str, u32); 16] = [
("white", 0xF0F0F0),
("orange", 0xEB8844),
("magenta", 0xC354CD),
("light_blue", 0x6689D3),
("yellow", 0xDECF2A),
("lime", 0x41CD34),
("pink", 0xD88198),
("gray", 0x434343),
("light_gray", 0xABABAB),
("cyan", 0x287697),
("purple", 0x7B2FBE),
("blue", 0x253192),
("brown", 0x51301A),
("green", 0x3B511A),
("red", 0xB3312C),
("black", 0x1E1B1B),
];
/// The `firework_explosion` component.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FireworkExplosion {
@@ -0,0 +1,40 @@
package dev.horizonlab.parity;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.core.component.DataComponents;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.item.component.TooltipDisplay;
import net.minecraft.world.item.component.TooltipProvider;
/**
* The tooltip lines of a stack's fireworks and firework_explosion components, as
* ItemStack.addDetailsToTooltip adds them (Fireworks / FireworkExplosion.addToTooltip
* unless its tooltip_display hides them), one stack (SNBT) per input line.
*/
public final class VanillaFireworkTooltipOracle {
public static void main(String[] args) throws Exception {
ParityData.init();
var context = Item.TooltipContext.of(ParityData.lookup);
List<DataComponentType<? extends TooltipProvider>> types = List.of(DataComponents.FIREWORKS, DataComponents.FIREWORK_EXPLOSION);
var output = new ArrayList<String>();
for (String line : Files.readAllLines(Path.of(args[0]))) {
if (line.startsWith("#")) continue;
var stack = ParityData.stack(line);
var display = stack.getOrDefault(DataComponents.TOOLTIP_DISPLAY, TooltipDisplay.DEFAULT);
var lines = new ArrayList<String>();
for (var type : types) {
TooltipProvider provider = stack.get(type);
if (provider != null && display.shows(type)) {
provider.addToTooltip(context, c -> lines.add(c.getString()), TooltipFlag.NORMAL, stack);
}
}
output.add(lines.isEmpty() ? "-" : String.join(" | ", lines));
}
Files.write(Path.of(args[1]), output);
}
}
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Compare firework rocket and firework star tooltips with the pinned vanilla client.
Random rockets (flight durations 0 to 3 and higher, up to six explosions, runs of equal ones) and stars, with dye and
custom colours, fade colours, trails and twinkles, some without the component (a rocket's default) and some whose
tooltip_display hides it. Vanilla prints what `Fireworks.addToTooltip` and `FireworkExplosion.addToTooltip` add
(VanillaFireworkTooltipOracle); Horizon what `item_tooltip::firework_lines` gives (examples/firework_tooltip_fixture).
"""
import random
try:
from . import lab, oracle_harness as harness
except ImportError:
import lab, oracle_harness as harness
SHAPES = ['small_ball', 'large_ball', 'star', 'creeper', 'burst']
DYES = [0xF0F0F0, 0xEB8844, 0xC354CD, 0x6689D3, 0xDECF2A, 0x41CD34, 0xD88198, 0x434343, 0xABABAB, 0x287697,
0x7B2FBE, 0x253192, 0x51301A, 0x3B511A, 0xB3312C, 0x1E1B1B]
COUNT = 3000
def explosion(rng):
def colors():
return [rng.choice(DYES) if rng.random() < 0.8 else rng.randrange(1 << 24) for _ in range(rng.choice([0, 1, 1, 2, 3]))]
fields = [f'shape:"{rng.choice(SHAPES)}"']
for key, values in (('colors', colors()), ('fade_colors', colors() if rng.random() < 0.4 else [])):
if values:
fields.append(f'{key}:[I;{",".join(map(str, values))}]')
if rng.random() < 0.4:
fields.append('has_trail:1b')
if rng.random() < 0.4:
fields.append('has_twinkle:1b')
return '{' + ','.join(fields) + '}'
def stack(rng):
components = []
if rng.random() < 0.7:
item = 'firework_rocket'
if rng.random() < 0.9:
explosions = []
for _ in range(rng.choice([0, 0, 1, 1, 2, 3, 6])):
# Runs of equal explosions are counted.
explosions.append(explosions[-1] if explosions and rng.random() < 0.4 else explosion(rng))
flight = rng.choice([0, 1, 1, 2, 3, 3, 7, 255])
components.append(f'"minecraft:fireworks":{{flight_duration:{flight},explosions:[{",".join(explosions)}]}}')
else:
item = 'firework_star'
if rng.random() < 0.9:
components.append(f'"minecraft:firework_explosion":{explosion(rng)}')
if rng.random() < 0.1:
hidden = rng.choice(['minecraft:fireworks', 'minecraft:firework_explosion'])
components.append(f'"minecraft:tooltip_display":{{hidden_components:["{hidden}"]}}')
body = f',components:{{{",".join(components)}}}' if components else ''
return f'{{id:"minecraft:{item}",count:1{body}}}'
def cases(build):
rng = random.Random(0x46495245)
path = build / 'cases.txt'
resources = lab.LOCAL / 'horizon-client' / '26.3'
path.write_text(f'#resources {resources}\n' + ''.join(stack(rng) + '\n' for _ in range(COUNT)))
return path, COUNT
if __name__ == '__main__':
harness.differential(
'firework-tooltip-parity', 'VanillaFireworkTooltipOracle', 'firework_tooltip_fixture', cases,
'Firework rocket and star tooltip lines: flight duration, explosions (counted runs), colours, fade, trail, '
'twinkle, defaults and tooltip_display',
sources=[lab.ROOT / 'crates/horizon-client/src/item_tooltip.rs', lab.ROOT / 'crates/horizon-client/src/item_data.rs',
lab.ROOT / 'crates/horizon-client/src/particles.rs'],
expected_lines=COUNT)