Invert crosshair rendering and show attack cooldown indicators
This commit is contained in:
@@ -3292,12 +3292,19 @@ 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 attack_speed = self.main_hand_attack_speed();
|
||||
let attack_strength = self.hand_strength.scale(0.0, attack_speed);
|
||||
let indicator = self.settings.attack_indicator;
|
||||
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(attack_strength);
|
||||
let full = indicator == 1
|
||||
&& attack_strength >= 1.0
|
||||
&& horizon_client::attack_strength::delay(attack_speed) > 5.0
|
||||
&& self.crosshair_attack_ready(attack_strength, attack_speed);
|
||||
let draws = hud_layout::crosshair(wi, hi, attack, full);
|
||||
let start = batch.vertices.len();
|
||||
hud_layout::paint(&mut batch, &self.res.atlas, &draws);
|
||||
batch.invert_since(start);
|
||||
}
|
||||
if !spectator {
|
||||
let inputs = hud_layout::HotbarInputs {
|
||||
@@ -3306,7 +3313,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(attack_strength),
|
||||
};
|
||||
let draws = hud_layout::hotbar(wi, hi, &inputs);
|
||||
hud_layout::paint(&mut batch, &self.res.atlas, &draws);
|
||||
|
||||
@@ -14,6 +14,39 @@ use horizon_client::{
|
||||
/// The off hand's place in `visible_hands` (the main hand uses its hotbar slot).
|
||||
const OFFHAND: usize = usize::MAX;
|
||||
|
||||
/// `Hud.extractCrosshair`: a charged, living target before any obstruction.
|
||||
fn attack_indicator_ready(
|
||||
strength: f32,
|
||||
speed: f64,
|
||||
living: Option<f64>,
|
||||
obstruction: Option<f64>,
|
||||
range: Option<&serde_json::Value>,
|
||||
creative: bool,
|
||||
) -> bool {
|
||||
let Some(distance) = living else {
|
||||
return false;
|
||||
};
|
||||
if !(strength >= 1.0 && horizon_client::attack_strength::delay(speed) > 5.0)
|
||||
|| obstruction.is_some_and(|d| d <= distance)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let Some(range) = range else {
|
||||
return true;
|
||||
};
|
||||
let value = |key: &str, default: f32| range[key].as_f64().map_or(default, |v| v as f32);
|
||||
let (min, max) = if creative {
|
||||
(
|
||||
value("min_creative_reach", 0.0),
|
||||
value("max_creative_reach", 5.0),
|
||||
)
|
||||
} else {
|
||||
(value("min_reach", 0.0), value("max_reach", 3.0))
|
||||
};
|
||||
let margin = value("hitbox_margin", 0.3);
|
||||
distance >= f64::from(min - margin) && distance <= f64::from(max + margin)
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `LivingEntity.swing` with `getModifiedSwingDuration`.
|
||||
pub(super) fn swing_hand(&mut self, hand: Hand, animation: SwingAnimation) {
|
||||
@@ -213,13 +246,62 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// `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()
|
||||
.and_then(|h| self.res.items.get(&h.item))
|
||||
.map_or(0.0, |i| f64::from(i.attack_speed))
|
||||
}
|
||||
pub(super) fn crosshair_attack_ready(&self, strength: f32, speed: f64) -> bool {
|
||||
let living = [
|
||||
self.mob_hit().map(|h| h.1),
|
||||
self.armor_stand_hit().map(|h| h.1),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.min_by(f64::total_cmp);
|
||||
let block = self.pick().and_then(|hit| {
|
||||
let eye = self.eye_position()?;
|
||||
Some(
|
||||
(0..3)
|
||||
.map(|i| (hit.point[i] - eye[i]).powi(2))
|
||||
.sum::<f64>()
|
||||
.sqrt(),
|
||||
)
|
||||
});
|
||||
let obstruction = [
|
||||
block,
|
||||
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),
|
||||
self.dragon_hit().map(|h| h.1),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.min_by(f64::total_cmp);
|
||||
let active = self
|
||||
.using
|
||||
.and_then(|(slot, _)| self.inventory.get(slot).and_then(Option::as_ref))
|
||||
.or_else(|| self.held());
|
||||
let components = active.map(|stack| {
|
||||
self.res
|
||||
.item_renderer
|
||||
.models
|
||||
.components(&horizon_client::item_render::stack_view(stack))
|
||||
});
|
||||
attack_indicator_ready(
|
||||
strength,
|
||||
speed,
|
||||
living,
|
||||
obstruction,
|
||||
components
|
||||
.as_ref()
|
||||
.and_then(|c| c.get("minecraft:attack_range")),
|
||||
self.creative,
|
||||
)
|
||||
}
|
||||
/// The visible main- and off-hand items.
|
||||
pub(super) fn visible_hand_items(&self) -> [Option<ItemStack>; 2] {
|
||||
[
|
||||
@@ -374,3 +456,97 @@ impl HandWorld for GameHands<'_, '_> {
|
||||
}
|
||||
fn release_using(&mut self) {}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn full_attack_indicator_requires_a_charged_living_target_before_obstructions() {
|
||||
assert!(attack_indicator_ready(
|
||||
1.0,
|
||||
1.6,
|
||||
Some(2.0),
|
||||
None,
|
||||
None,
|
||||
false
|
||||
));
|
||||
for (strength, speed, living, obstruction) in [
|
||||
(0.99, 1.6, Some(2.0), None),
|
||||
(f32::NAN, 1.6, Some(2.0), None),
|
||||
(1.0, 4.0, Some(2.0), None),
|
||||
(1.0, f64::NAN, Some(2.0), None),
|
||||
(1.0, 1.6, None, None),
|
||||
(1.0, 1.6, Some(2.0), Some(1.5)),
|
||||
(1.0, 1.6, Some(2.0), Some(2.0)),
|
||||
] {
|
||||
assert!(!attack_indicator_ready(
|
||||
strength,
|
||||
speed,
|
||||
living,
|
||||
obstruction,
|
||||
None,
|
||||
false
|
||||
));
|
||||
}
|
||||
assert!(attack_indicator_ready(
|
||||
1.0,
|
||||
1.6,
|
||||
Some(2.0),
|
||||
Some(2.5),
|
||||
None,
|
||||
false
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_attack_indicator_uses_inclusive_float_attack_range_bounds() {
|
||||
let range = serde_json::json!({
|
||||
"min_reach": 2.0,
|
||||
"max_reach": 4.5,
|
||||
"min_creative_reach": 2.0,
|
||||
"max_creative_reach": 6.5,
|
||||
"hitbox_margin": 0.125,
|
||||
});
|
||||
for (creative, min, max) in [(false, 1.875, 4.625), (true, 1.875, 6.625)] {
|
||||
for distance in [min, max] {
|
||||
assert!(attack_indicator_ready(
|
||||
1.0,
|
||||
1.6,
|
||||
Some(distance),
|
||||
None,
|
||||
Some(&range),
|
||||
creative
|
||||
));
|
||||
}
|
||||
for distance in [min - 0.0001, max + 0.0001] {
|
||||
assert!(!attack_indicator_ready(
|
||||
1.0,
|
||||
1.6,
|
||||
Some(distance),
|
||||
None,
|
||||
Some(&range),
|
||||
creative
|
||||
));
|
||||
}
|
||||
}
|
||||
let defaults = serde_json::json!({});
|
||||
let max = f64::from(3.0f32 + 0.3f32);
|
||||
assert!(attack_indicator_ready(
|
||||
1.0,
|
||||
1.6,
|
||||
Some(max),
|
||||
None,
|
||||
Some(&defaults),
|
||||
false
|
||||
));
|
||||
assert!(!attack_indicator_ready(
|
||||
1.0,
|
||||
1.6,
|
||||
Some(max + 1e-8),
|
||||
None,
|
||||
Some(&defaults),
|
||||
false
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,6 +287,7 @@ pub static GUI_SCALE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU3
|
||||
/// One frame of overlay geometry in GUI pixels.
|
||||
pub struct HudBatch {
|
||||
pub vertices: Vec<HudVertex>,
|
||||
inverse_ranges: Vec<std::ops::Range<u32>>,
|
||||
pub scale: f32,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
@@ -310,12 +311,44 @@ impl HudBatch {
|
||||
}
|
||||
Self {
|
||||
vertices: Vec::new(),
|
||||
inverse_ranges: Vec::new(),
|
||||
scale: scale as f32,
|
||||
width: (window[0] as f32 / scale as f32).ceil(),
|
||||
height: (window[1] as f32 / scale as f32).ceil(),
|
||||
patches: Vec::new(),
|
||||
}
|
||||
}
|
||||
/// Use the crosshair's destination-dependent blend for vertices just emitted.
|
||||
/// Calls follow draw order, so ordinary HUD geometry keeps its own blend.
|
||||
pub fn invert_since(&mut self, start: usize) {
|
||||
let range = start as u32..self.vertices.len() as u32;
|
||||
if range.is_empty() {
|
||||
return;
|
||||
}
|
||||
if let Some(last) = self.inverse_ranges.last_mut() {
|
||||
debug_assert!(last.end <= range.start);
|
||||
if last.end == range.start {
|
||||
last.end = range.end;
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.inverse_ranges.push(range);
|
||||
}
|
||||
/// Split the shared vertex buffer without changing the order of overlays.
|
||||
fn draw_ranges(&self) -> impl Iterator<Item = (std::ops::Range<u32>, bool)> + '_ {
|
||||
let end = self.vertices.len() as u32;
|
||||
self.inverse_ranges
|
||||
.iter()
|
||||
.cloned()
|
||||
.chain(std::iter::once(end..end))
|
||||
.scan(0, |start, inverse| {
|
||||
let normal = *start..inverse.start;
|
||||
*start = inverse.end;
|
||||
Some([(normal, false), (inverse, true)])
|
||||
})
|
||||
.flatten()
|
||||
.filter(|(range, _)| !range.is_empty())
|
||||
}
|
||||
/// `AbstractContainerScreen.init`: center in integer GUI coordinates.
|
||||
pub fn centered_origin(&self, width: f32, height: f32) -> (f32, f32) {
|
||||
(
|
||||
@@ -604,6 +637,7 @@ pub struct HudRenderer {
|
||||
/// The shared atlas texture, for run-time glyph uploads.
|
||||
pub atlas_texture: Option<wgpu::Texture>,
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
inverse_pipeline: wgpu::RenderPipeline,
|
||||
group: wgpu::BindGroup,
|
||||
uniform: wgpu::Buffer,
|
||||
buffer: wgpu::Buffer,
|
||||
@@ -684,35 +718,50 @@ 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 make_pipeline = |label, blend, fragment_entry| {
|
||||
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(fragment_entry),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: Some(blend),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
let pipeline = make_pipeline("HUD", wgpu::BlendState::ALPHA_BLENDING, "fs_main");
|
||||
let inverse_pipeline = make_pipeline(
|
||||
"HUD crosshair",
|
||||
wgpu::BlendState {
|
||||
color: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::OneMinusDst,
|
||||
dst_factor: wgpu::BlendFactor::OneMinusSrc,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
alpha: wgpu::BlendComponent::REPLACE,
|
||||
},
|
||||
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,
|
||||
});
|
||||
"fs_crosshair",
|
||||
);
|
||||
let capacity = 1 << 16;
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("HUD vertices"),
|
||||
@@ -723,6 +772,7 @@ impl HudRenderer {
|
||||
Ok(Self {
|
||||
atlas_texture: None,
|
||||
pipeline,
|
||||
inverse_pipeline,
|
||||
group,
|
||||
uniform,
|
||||
buffer,
|
||||
@@ -800,10 +850,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, inverse) in batch.draw_ranges() {
|
||||
pass.set_pipeline(if inverse {
|
||||
&self.inverse_pipeline
|
||||
} else {
|
||||
&self.pipeline
|
||||
});
|
||||
pass.draw(range, 0..1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -811,12 +867,58 @@ impl HudRenderer {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hud_shader_validates_both_fragment_entries() {
|
||||
let module = naga::front::wgsl::parse_str(include_str!("hud.wgsl")).unwrap();
|
||||
naga::valid::Validator::new(
|
||||
naga::valid::ValidationFlags::all(),
|
||||
naga::valid::Capabilities::all(),
|
||||
)
|
||||
.validate(&module)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crosshair_blend_ranges_preserve_overlay_order() {
|
||||
let mut batch = HudBatch::new([640, 480]);
|
||||
assert!(batch.draw_ranges().next().is_none());
|
||||
let quad = |batch: &mut HudBatch| batch.quad([[0.0; 2]; 4], [[0.0; 2]; 4], u32::MAX);
|
||||
quad(&mut batch);
|
||||
assert_eq!(batch.draw_ranges().collect::<Vec<_>>(), [(0..6, false)]);
|
||||
// Missing sprites emit nothing and must not switch the blend.
|
||||
batch.invert_since(batch.vertices.len());
|
||||
let start = batch.vertices.len();
|
||||
quad(&mut batch);
|
||||
batch.invert_since(start);
|
||||
// Adjacent crosshair pieces use the same pipeline.
|
||||
let start = batch.vertices.len();
|
||||
quad(&mut batch);
|
||||
batch.invert_since(start);
|
||||
quad(&mut batch);
|
||||
let start = batch.vertices.len();
|
||||
quad(&mut batch);
|
||||
batch.invert_since(start);
|
||||
assert_eq!(
|
||||
batch.draw_ranges().collect::<Vec<_>>(),
|
||||
[
|
||||
(0..6, false),
|
||||
(6..18, true),
|
||||
(18..24, false),
|
||||
(24..30, true)
|
||||
]
|
||||
);
|
||||
// A later menu stays on the ordinary blend and draws over the crosshair.
|
||||
quad(&mut batch);
|
||||
assert_eq!(batch.draw_ranges().last(), Some((30..36, false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn container_origins_use_java_integer_division() {
|
||||
// Odd scaled dimensions, odd image sizes and an oversized panel.
|
||||
for (width, height) in [(640, 360), (641, 361), (456, 256), (534, 300), (100, 100)] {
|
||||
let batch = HudBatch {
|
||||
vertices: Vec::new(),
|
||||
inverse_ranges: Vec::new(),
|
||||
scale: 3.0,
|
||||
width: width as f32,
|
||||
height: height as f32,
|
||||
|
||||
@@ -26,3 +26,8 @@ struct Out {
|
||||
if c.a < 0.004 { discard; }
|
||||
return c;
|
||||
}
|
||||
@fragment fn fs_crosshair(in: Out) -> @location(0) vec4<f32> {
|
||||
let c = textureSample(atlas, atlas_sampler, in.uv) * in.color;
|
||||
if c.a == 0.0 { discard; }
|
||||
return c;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user