Merge pull request #196 from ludovic111/fix/crosshair-97

Inverting crosshair and a working attack indicator
This commit is contained in:
Ludovic Marie
2026-10-15 00:02:02 +02:00
committed by GitHub
10 changed files with 209 additions and 45 deletions
@@ -93,8 +93,9 @@ fn encode(draws: &[GuiDraw]) -> Vec<Value> {
h,
region,
color,
blend,
} => {
json!({"type": "sprite", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "region": region, "color": *color as i32})
json!({"type": "sprite", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "region": region, "color": *color as i32, "pipeline": blend.pipeline()})
}
GuiDraw::AtlasSprite {
sprite,
@@ -190,7 +191,12 @@ fn decorations(c: &Value, atlas: &HudAtlas) -> Vec<GuiDraw> {
// Spectators only see it over a spectatable target (none here).
if c["crosshair"].as_bool().unwrap_or(false) && mode != "spectator" {
let attack = (indicator == "CROSSHAIR").then(|| float("attackScale", 1.0));
draws.extend(hud_layout::crosshair(w, h, attack, false));
// crosshairPickEntity: absent, or a living entity alive or not.
let target = c["target"].as_bool();
let full = attack.is_some_and(|a| {
hud_layout::full_attack_indicator(a, float("attackDelay", 5.0), target)
});
draws.extend(hud_layout::crosshair(w, h, attack, full));
}
if mode != "spectator" {
let pop = |v: &Value| v.as_f64().map(|p| p as f32 - partial);
+8 -4
View File
@@ -3331,11 +3331,15 @@ impl Game<'_> {
self.draw_spyglass(&mut batch);
// Hud.extractCrosshair / extractItemHotbar / extractPlayerHealth /
// extractVehicleHealth and the experience bar, laid out by hud_layout.
// Horizon has no attack cooldown yet: the strength is always full.
let indicator = self.settings.attack_indicator;
let delay = horizon_client::attack_strength::delay(self.main_hand_attack_speed());
let strength = self.hand_strength.scale(0.0, self.main_hand_attack_speed());
if self.camera_type.first_person() && !spectator {
let attack = (indicator == 1).then_some(1.0);
let draws = hud_layout::crosshair(wi, hi, attack, false);
let attack = (indicator == 1).then_some(strength);
let full = attack.is_some_and(|a| {
hud_layout::full_attack_indicator(a, delay, self.crosshair_living())
});
let draws = hud_layout::crosshair(wi, hi, attack, full);
hud_layout::paint(&mut batch, &self.res.atlas, &draws);
}
if !spectator {
@@ -3345,7 +3349,7 @@ impl Game<'_> {
offhand: self.offhand.is_some(),
slots: std::array::from_fn(|i| self.inventory[i].as_ref().map(|_| 0.0)),
offhand_pop: 0.0,
attack: (indicator == 2).then_some(1.0),
attack: (indicator == 2).then_some(strength),
};
let draws = hud_layout::hotbar(wi, hi, &inputs);
hud_layout::paint(&mut batch, &self.res.atlas, &draws);
+19 -1
View File
@@ -212,8 +212,26 @@ impl Game<'_> {
}
}
}
/// `Minecraft.crosshairPickEntity` when it is a `LivingEntity`: whether
/// it is alive (the nearest entity under the crosshair, before any block).
pub(super) fn crosshair_living(&self) -> Option<bool> {
let nearest = |hits: &[Option<f64>]| hits.iter().flatten().copied().reduce(f64::min);
let living = nearest(&[
self.mob_hit().map(|h| h.1),
self.armor_stand_hit().map(|h| h.1),
self.dragon_hit().map(|h| h.1),
])?;
let other = nearest(&[
self.painting_hit().map(|h| h.1),
self.frame_hit().map(|h| h.1),
self.boat_hit().map(|h| h.1),
self.cart_hit().map(|h| h.1),
]);
// Only alive mobs are hit, so a picked living entity is alive.
(self.before_block(living) && other.is_none_or(|o| living <= o)).then_some(true)
}
/// `Attributes.ATTACK_SPEED` with the main-hand item's modifier.
fn main_hand_attack_speed(&self) -> f64 {
pub(super) fn main_hand_attack_speed(&self) -> f64 {
horizon_client::attack_strength::BASE_ATTACK_SPEED
+ self
.held()
+111 -30
View File
@@ -292,6 +292,9 @@ pub struct HudBatch {
pub height: f32,
/// Glyph pixels to upload into the atlas before drawing.
pub patches: Vec<crate::font::Patch>,
/// Vertex ranges drawn with `RenderPipelines.CROSSHAIR`'s
/// `BlendFunction.INVERT` instead of alpha blending.
pub invert: Vec<std::ops::Range<u32>>,
}
pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> u32 {
u32::from(a) << 24 | u32::from(b) << 16 | u32::from(g) << 8 | u32::from(r)
@@ -314,8 +317,37 @@ impl HudBatch {
width: (window[0] as f32 / scale as f32).ceil(),
height: (window[1] as f32 / scale as f32).ceil(),
patches: Vec::new(),
invert: Vec::new(),
}
}
/// Draw the vertices added since `start` with the inverting blend.
pub fn invert_since(&mut self, start: usize) {
let range = start as u32..self.vertices.len() as u32;
if range.is_empty() {
return;
}
match self.invert.last_mut() {
Some(last) if last.end == range.start => last.end = range.end,
_ => self.invert.push(range),
}
}
/// The vertex ranges in order, each with whether it inverts.
pub fn runs(&self) -> Vec<(std::ops::Range<u32>, bool)> {
let mut out = Vec::new();
let mut at = 0;
for r in &self.invert {
if r.start > at {
out.push((at..r.start, false));
}
out.push((r.clone(), true));
at = r.end;
}
let end = self.vertices.len() as u32;
if end > at {
out.push((at..end, false));
}
out
}
/// `AbstractContainerScreen.init`: center in integer GUI coordinates.
pub fn centered_origin(&self, width: f32, height: f32) -> (f32, f32) {
(
@@ -604,6 +636,8 @@ pub struct HudRenderer {
/// The shared atlas texture, for run-time glyph uploads.
pub atlas_texture: Option<wgpu::Texture>,
pipeline: wgpu::RenderPipeline,
/// `RenderPipelines.CROSSHAIR`.
invert_pipeline: wgpu::RenderPipeline,
group: wgpu::BindGroup,
uniform: wgpu::Buffer,
buffer: wgpu::Buffer,
@@ -684,35 +718,55 @@ impl HudRenderer {
..Default::default()
});
let attributes = wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Unorm8x4];
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("HUD"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &[Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<HudVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &attributes,
})],
let create = |label, blend| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &[Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<HudVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &attributes,
})],
},
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(blend),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
};
let pipeline = create("HUD", wgpu::BlendState::ALPHA_BLENDING);
// BlendFunction.INVERT: ONE_MINUS_DST_COLOR, ONE_MINUS_SRC_COLOR,
// ONE, ZERO.
let invert_pipeline = create(
"HUD crosshair",
wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::OneMinusDst,
dst_factor: wgpu::BlendFactor::OneMinusSrc,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::Zero,
operation: wgpu::BlendOperation::Add,
},
},
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
);
let capacity = 1 << 16;
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("HUD vertices"),
@@ -723,6 +777,7 @@ impl HudRenderer {
Ok(Self {
atlas_texture: None,
pipeline,
invert_pipeline,
group,
uniform,
buffer,
@@ -800,10 +855,16 @@ impl HudRenderer {
color_attachments: &attachments,
..Default::default()
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &self.group, &[]);
pass.set_vertex_buffer(0, self.buffer.slice(..));
pass.draw(0..count as u32, 0..1);
for (range, invert) in batch.runs() {
pass.set_pipeline(if invert {
&self.invert_pipeline
} else {
&self.pipeline
});
pass.draw(range, 0..1);
}
}
}
@@ -811,6 +872,25 @@ impl HudRenderer {
mod tests {
use super::*;
#[test]
fn inverted_ranges_split_the_draws_in_order() {
let mut batch = HudBatch::new([854, 480]);
let quad = |b: &mut HudBatch| b.quad([[0.0; 2]; 4], [[0.0; 2]; 4], 0);
quad(&mut batch);
let start = batch.vertices.len();
quad(&mut batch);
batch.invert_since(start);
let start = batch.vertices.len();
quad(&mut batch);
batch.invert_since(start);
batch.invert_since(batch.vertices.len());
quad(&mut batch);
assert_eq!(batch.invert, vec![6..18]);
assert_eq!(
batch.runs(),
vec![(0..6, false), (6..18, true), (18..24, false)]
);
}
#[test]
fn container_origins_use_java_integer_division() {
// Odd scaled dimensions, odd image sizes and an oversized panel.
@@ -821,6 +901,7 @@ mod tests {
width: width as f32,
height: height as f32,
patches: Vec::new(),
invert: Vec::new(),
};
for (image_width, image_height) in [(195, 136), (176, 166), (176, 222)] {
assert_eq!(
+37 -5
View File
@@ -44,6 +44,8 @@ pub enum Blend {
Vignette,
/// `GUI_NAUSEA_OVERLAY`: additive.
Nausea,
/// `CROSSHAIR`: `BlendFunction.INVERT`, the colour under it inverted.
Crosshair,
}
impl Blend {
pub fn pipeline(self) -> &'static str {
@@ -51,6 +53,7 @@ impl Blend {
Blend::Textured => "pipeline/gui_textured",
Blend::Vignette => "pipeline/vignette",
Blend::Nausea => "pipeline/gui_nausea_overlay",
Blend::Crosshair => "pipeline/crosshair",
}
}
}
@@ -58,8 +61,8 @@ impl Blend {
/// One `GuiGraphicsExtractor` call.
#[derive(Clone, Debug, PartialEq)]
pub enum GuiDraw {
/// `blitSprite(sprite, x, y, w, h, color)`; `region` = (spriteW,
/// spriteH, u, v) for the partial overload.
/// `blitSprite(pipeline, sprite, x, y, w, h, color)`; `region` =
/// (spriteW, spriteH, u, v) for the partial overload.
Sprite {
sprite: Cow<'static, str>,
x: i32,
@@ -68,6 +71,7 @@ pub enum GuiDraw {
h: i32,
region: Option<[i32; 4]>,
color: u32,
blend: Blend,
},
/// `blitSprite(pipeline, TextureAtlasSprite, ...)` with a block atlas
/// sprite (the nether portal overlay).
@@ -136,6 +140,7 @@ fn sprite(sprite: &'static str, x: i32, y: i32, w: i32, h: i32) -> GuiDraw {
h,
region: None,
color: WHITE,
blend: Blend::Textured,
}
}
fn region(
@@ -154,8 +159,16 @@ fn region(
h,
region: Some([size[0], size[1], uv[0], uv[1]]),
color: WHITE,
blend: Blend::Textured,
}
}
/// A draw through `RenderPipelines.CROSSHAIR`.
fn crosshair_blend(mut d: GuiDraw) -> GuiDraw {
if let GuiDraw::Sprite { blend, .. } = &mut d {
*blend = Blend::Crosshair;
}
d
}
/// `graphics.fill`: the corners are sorted.
pub fn fill(x0: i32, y0: i32, x1: i32, y1: i32, color: u32) -> GuiDraw {
GuiDraw::Fill {
@@ -365,10 +378,25 @@ pub fn hotbar(w: i32, h: i32, i: &HotbarInputs) -> Vec<GuiDraw> {
out
}
/// `Hud.extractCrosshair` (first person, not hidden for spectators):
/// `attack` is `getAttackStrengthScale(0)` in CROSSHAIR indicator mode and
/// `full` whether the full indicator shows for a target in reach.
/// `Hud.extractCrosshair`'s full attack indicator: at full strength on a
/// living, alive `crosshairPickEntity` (`target`) with a weapon slower than
/// `MIN_CROSSHAIR_ATTACK_SPEED` (`delay` is
/// `getCurrentItemAttackStrengthDelay`).
pub fn full_attack_indicator(scale: f32, delay: f32, target: Option<bool>) -> bool {
scale >= 1.0 && delay > 5.0 && target == Some(true)
}
/// `Hud.extractCrosshair` (first person, not hidden for spectators), every
/// sprite through the inverting `CROSSHAIR` pipeline: `attack` is
/// `getAttackStrengthScale(0)` in CROSSHAIR indicator mode and `full`
/// whether the full indicator shows ([`full_attack_indicator`]).
pub fn crosshair(w: i32, h: i32, attack: Option<f32>, full: bool) -> Vec<GuiDraw> {
crosshair_draws(w, h, attack, full)
.into_iter()
.map(crosshair_blend)
.collect()
}
fn crosshair_draws(w: i32, h: i32, attack: Option<f32>, full: bool) -> Vec<GuiDraw> {
let mut out = vec![sprite("hud/crosshair", (w - 15) / 2, (h - 15) / 2, 15, 15)];
if let Some(scale) = attack {
let (x, y) = (w / 2 - 8, h / 2 - 7 + 16);
@@ -760,6 +788,7 @@ pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, dra
h,
region,
color,
blend,
} => {
let Some(mut r) = atlas.sprites.get(&format!("gui/sprites/{sprite}")).copied()
else {
@@ -775,6 +804,9 @@ pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, dra
r.v0 = v0;
}
batch.rect_uv(*x as f32, *y as f32, *w as f32, *h as f32, r, abgr(*color));
if *blend == Blend::Crosshair {
batch.invert_since(start);
}
}
GuiDraw::AtlasSprite {
sprite,
@@ -160,6 +160,7 @@ pub fn effects(w: i32, demo: bool, effects: &[EffectIcon]) -> Vec<GuiDraw> {
h: 24,
region: None,
color: crate::hud_layout::WHITE,
blend: crate::hud_layout::Blend::Textured,
});
out.push(GuiDraw::Sprite {
sprite: Cow::Owned(format!("mob_effect/{}", e.id)),
@@ -169,6 +170,7 @@ pub fn effects(w: i32, demo: bool, effects: &[EffectIcon]) -> Vec<GuiDraw> {
h: 18,
region: None,
color: white(alpha),
blend: crate::hud_layout::Blend::Textured,
});
}
out
@@ -477,6 +479,7 @@ pub fn boss_overlay(w: i32, h: i32, bars: &[BossBar], font: &Font) -> Vec<GuiDra
h: 5,
region: Some([182, 5, 0, 0]),
color: crate::hud_layout::WHITE,
blend: crate::hud_layout::Blend::Textured,
};
out.push(sprite(BOSS_COLORS[bar.color].to_owned()));
if bar.overlay != 0 {
@@ -517,6 +520,7 @@ pub fn jump_bar(w: i32, h: i32, cooldown: i32, scale: f32) -> Vec<GuiDraw> {
h: 5,
region,
color: crate::hud_layout::WHITE,
blend: crate::hud_layout::Blend::Textured,
};
let mut out = vec![sprite("hud/jump_bar_background", 182, None)];
if cooldown > 0 {
+1
View File
@@ -90,6 +90,7 @@ fn sprite(name: &'static str, x: i32, y: i32, w: i32, h: i32) -> GuiDraw {
h,
region: None,
color: WHITE,
blend: crate::hud_layout::Blend::Textured,
}
}
@@ -149,6 +149,8 @@ public final class VanillaHudOracle {
@Override public ItemStack getOffhandItem() { return offhand; }
@Override public HumanoidArm getMainArm() { return b("rightHanded") ? HumanoidArm.RIGHT : HumanoidArm.LEFT; }
@Override public float getAttackStrengthScale(float a) { return f("attackScale", 1); }
@Override public float getCurrentItemAttackStrengthDelay() { return f("attackDelay", 5); }
@Override public ItemStack getActiveItem() { return ItemStack.EMPTY; }
@Override public Level level() { return level; }
@Override public boolean isSpectator() { return false; }
@Override public net.minecraft.world.entity.PlayerRideableJumping jumpableVehicle() {
@@ -179,6 +181,12 @@ public final class VanillaHudOracle {
@Override public boolean showVehicleHealth() { return true; }
}
/** Minecraft.crosshairPickEntity: a living entity, alive as the case says. */
public static final class Target extends net.minecraft.world.entity.animal.equine.Horse {
private Target() { super(null, null); }
@Override public boolean isAlive() { return b("target"); }
}
/** Records GuiGraphicsExtractor calls. */
public static final class Capture extends GuiGraphicsExtractor {
JsonArray draws;
@@ -198,7 +206,7 @@ public final class VanillaHudOracle {
draws.add(o);
return o;
}
void sprite(Identifier id, int x, int y, int w, int h, int[] region, int color) {
void sprite(RenderPipeline p, Identifier id, int x, int y, int w, int h, int[] region, int color) {
var o = new JsonObject();
o.addProperty("type", "sprite");
o.addProperty("sprite", id.getPath());
@@ -209,11 +217,12 @@ public final class VanillaHudOracle {
o.add("region", r);
}
o.addProperty("color", color);
o.addProperty("pipeline", p.getLocation().getPath());
posed(o, stack);
}
@Override public void blitSprite(RenderPipeline p, Identifier id, int x, int y, int w, int h, int color) { sprite(id, x, y, w, h, null, color); }
@Override public void blitSprite(RenderPipeline p, Identifier id, int x, int y, int w, int h, int color) { sprite(p, id, x, y, w, h, null, color); }
@Override public void blitSprite(RenderPipeline p, Identifier id, int sw, int sh, int u, int v, int x, int y, int w, int h, int color) {
sprite(id, x, y, w, h, new int[] {sw, sh, u, v}, color);
sprite(p, id, x, y, w, h, new int[] {sw, sh, u, v}, color);
}
@Override public void blitSprite(RenderPipeline p, net.minecraft.client.renderer.texture.TextureAtlasSprite s, int x, int y, int w, int h, int color) {
var o = new JsonObject();
@@ -430,6 +439,8 @@ public final class VanillaHudOracle {
var debug = alloc(net.minecraft.client.gui.components.debug.DebugScreenEntryList.class);
put(debug, net.minecraft.client.gui.components.debug.DebugScreenEntryList.class, "currentlyEnabled", new ArrayList<Identifier>());
put(mc, Minecraft.class, "debugEntries", debug);
boolean target = c.has("target") && !c.get("target").isJsonNull();
put(mc, Minecraft.class, "crosshairPickEntity", target ? alloc(Target.class) : null);
crosshair.invoke(hud, capture, delta);
}
if (mode != GameType.SPECTATOR) hotbar.invoke(hud, capture, delta);
+6
View File
@@ -15,6 +15,10 @@ def decorations(rng, n):
'crosshair': rng.random() < 0.7,
'attackIndicator': rng.choice(['OFF', 'CROSSHAIR', 'HOTBAR']),
'attackScale': rng.choice([1.0, round(rng.random(), 3), 0.0, 0.999]),
# Minecraft.crosshairPickEntity (a living entity, alive or dead) and
# getCurrentItemAttackStrengthDelay, for the full indicator.
'target': rng.choice([None, True, True, False]),
'attackDelay': rng.choice([5.0, 12.5, 4.0, 20.0, 5.0001, 10.0]),
'selected': rng.randint(0, 8), 'rightHanded': rng.random() < 0.7,
'slots': [rng.choice([None, 0, 0, 3, 5]) if rng.random() < 0.6 else None for _ in range(9)],
'offhand': rng.choice([None, None, 0, 4]), 'partial': round(rng.random(), 3),
@@ -30,6 +34,8 @@ def decorations(rng, n):
'xpProgress': rng.choice([0.0, round(rng.random(), 4), 0.999]), 'xpLevel': rng.choice([0, 1, 7, 30, 123, 4000]),
'experienceBar': rng.random() < 0.8,
}
if case['target'] and rng.random() < 0.5:
case['attackScale'] = 1.0
if case['damageCooldown'] and rng.random() < 0.5:
case['healthBlinkTime'] = case['tick'] + rng.randint(1, 20)
if rng.random() < 0.15:
+1
View File
@@ -70,6 +70,7 @@ def normal(d):
d.setdefault('matrix', IDENTITY)
if d['type'] == 'sprite':
d.setdefault('region', None)
d.setdefault('pipeline', 'pipeline/gui_textured')
if d['type'] == 'text':
d.setdefault('runs', None)
return d