From 8e700aa68362a9d9b0c377c84fbb760055a4e8e9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 01:57:06 +0200 Subject: [PATCH 01/19] Riptide: run vanilla's auto-spin attack after the launch Releasing a Riptide trident now starts LivingEntity.startAutoSpinAttack(20, 8.0): for 20 ticks the player takes the SPIN_ATTACK pose (0.6x0.6, eye height 0.4), hits the first living entity its swept box touches for the spin's damage and bounces back (velocity x -0.2), and stops on a horizontal collision. The player model spins (setupRotations: rotX(-90 - xRot), rotY(age * -75)), SpinAttackEffectLayer draws the riptide boxes, and the first-person hand uses ItemInHandRenderer's spin transform. LAN guests see the host's spin through living flag bit 4. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/first_person.rs | 8 ++ crates/horizon-client/src/game.rs | 33 ++++++++- crates/horizon-client/src/game/lan.rs | 4 +- crates/horizon-client/src/game/perspective.rs | 44 +++++++++++ crates/horizon-client/src/game/trident.rs | 35 +++++++++ crates/horizon-client/src/mobs.rs | 2 + crates/horizon-client/src/mobs/render.rs | 9 ++- crates/horizon-client/src/motion.rs | 74 +++++++++++++++++++ crates/horizon-client/src/pose.rs | 8 +- 9 files changed, 210 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/first_person.rs b/crates/horizon-client/src/first_person.rs index a25d9f537..463d51437 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -21,6 +21,8 @@ pub enum ItemPose { Trident { ticks_used: f32, }, + /// Riptide's spin (`isAutoSpinAttack`): the item held up like a fork. + SpinAttack, Bow { ticks_used: f32, }, @@ -67,6 +69,12 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) - if matches!(pose, ItemPose::Using) { return m; } + if matches!(pose, ItemPose::SpinAttack) { + return m + * Mat4::from_translation(Vec3::new(invert * -0.4, 0.8, 0.3)) + * Mat4::from_rotation_y((invert * 65.0f32).to_radians()) + * Mat4::from_rotation_z((invert * -85.0f32).to_radians()); + } let charging = match pose { ItemPose::Bow { ticks_used } => { let power = ticks_used / 20.0; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2df6aa9b0..36c16e61f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -896,6 +896,8 @@ struct WorldRest { behaviours: Behaviours, player_arm: Option, player_type: Option>, + /// `SpinAttackEffectModel` (Riptide's spinning boxes). + spin_attack: Option, stations: horizon_client::stations::StationData, } @@ -971,6 +973,9 @@ impl Resources { fn player_type(&self) -> &Option> { &self.rest().player_type } + fn spin_attack(&self) -> &Option { + &self.rest().spin_attack + } fn stations(&self) -> &horizon_client::stations::StationData { &self.rest().stations } @@ -3907,6 +3912,7 @@ impl Game<'_> { } let riding = self.riding.is_some(); let ghast_collisions = self.happy_ghast_player_collisions(); + let spin_targets = self.spin_targets(); let Some(player) = self.player.as_mut() else { // A dedicated server has no local player: the world still runs. if self.options.dedicated.is_some() { @@ -3984,6 +3990,7 @@ impl Game<'_> { .any(|s| immune.is_some_and(|t| t.contains(&*s.item))); // The dimension's FAST_LAVA: the Nether's lava pushes harder. player.fluids.fast_lava = self.dim == Dim::Nether; + player.spin_targets = spin_targets; let grounded = player.ground.on_ground; let before = ( grounded, @@ -4006,6 +4013,7 @@ impl Game<'_> { } } let events = std::mem::take(&mut player.events); + let spin_hit = player.spin_hit.take(); let glider_wear = std::mem::take(&mut player.glider_wear); if glider_wear > 0 && !self.creative @@ -4024,6 +4032,7 @@ impl Game<'_> { self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5; let crouching = player.pose == horizon_client::pose::Pose::Crouching; self.tick_avatar(before, riding); + self.end_spin_attack(spin_hit); self.record_combat(&events); for event in events { match event { @@ -6751,7 +6760,13 @@ impl Game<'_> { /// enchantments. pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool) { let hand_damage = 1.0 + self.attack_item_info().map_or(0.0, |i| i.attack_damage); - let damage = hand_damage + self.effect_attack_bonus(); + // Riptide's spin replaces the attack damage attribute. + let spin = self.player.as_ref().map_or(0.0, |p| p.auto_spin_attack_dmg); + let damage = if spin > 0.0 { + spin + } else { + hand_damage + self.effect_attack_bonus() + }; let scale = self.attack_strength_scale(); let mut amount = damage * (0.2 + scale * scale * 0.8); // Item.getAttackDamageBonus (a mace's smash), before the critical hit. @@ -6879,6 +6894,14 @@ impl Game<'_> { return false; } } + self.attack_mob(index); + // Minecraft.startAttack swings after the attack. + self.swing_arm(); + true + } + /// `Player.attack` on a mob: the damage, knockback, sweep, particles and + /// sounds. + pub(super) fn attack_mob(&mut self, index: usize) { let target_kind = self.mobs[index].kind.id.clone(); let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:")); let (amount, scale, crit) = self.melee_damage(&target_kind); @@ -6896,7 +6919,6 @@ impl Game<'_> { self.audio .play("minecraft:entity.player.attack.knockback", from, 1.0, 1.0); } - self.swing_arm(); // LivingEntity.setLastHurtMob (tamed wolves join in). self.combat.last_hurt_mob = Some((self.mobs[index].id, self.world.game_time)); let old_health = self.mobs[index].health; @@ -6989,7 +7011,6 @@ impl Game<'_> { self.audio .play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0); } - true } /// ServerExplosion: rays from a 16^3 grid lose (resistance + 0.3) * 0.3 per step. /// A mob explosion (`Level.ExplosionInteraction.MOB`: drop decay with the @@ -8489,6 +8510,10 @@ impl Game<'_> { } let shown = self.hands_to_render(); let used_hand = self.used_hand(); + let spinning = self + .player + .as_ref() + .is_some_and(|p| p.auto_spin_attack_ticks > 0); for (i, (hand, item)) in Hand::BOTH .into_iter() .zip(self.visible_hand_items()) @@ -8608,6 +8633,7 @@ impl Game<'_> { ItemPose::Using } } + _ if spinning => ItemPose::SpinAttack, _ => ItemPose::Swing, }; let m = to_world @@ -12052,6 +12078,7 @@ fn load_world_rest( player_type: perspective::player_type(root), player_arm: horizon_client::mobs::load_model(root, "minecraft:player#main") .and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")), + spin_attack: horizon_client::mobs::load_model(root, "minecraft:spin_attack#main"), }) } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index f9ea1262b..8e641b61f 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -740,7 +740,9 @@ impl Game<'_> { equipment, health: p.health.health(), attributes: horizon_client::lan::attributes::syncable(&p.attributes), - living_flags: living_flags(self.using), + // Bit 4: Riptide's spin (LivingEntity.isAutoSpinAttack). + living_flags: living_flags(self.using) + | if p.auto_spin_attack_ticks > 0 { 4 } else { 0 }, bed: self.sleeping, }) } diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index ec46120dd..bd2721648 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -312,6 +312,7 @@ impl Game<'_> { let crouching = p.pose == Pose::Crouching; let (position, flying) = (p.position, p.flying || p.fall_flying); let (fall_flying, fly_ticks, velocity) = (p.fall_flying, p.fall_fly_ticks, p.velocity); + let spinning = p.auto_spin_attack_ticks > 0; let using = self.using.map(|(_, ticks)| ticks as i32 + 1).unwrap_or(0); let using_off_hand = self .using @@ -397,6 +398,7 @@ impl Game<'_> { m.velocity = velocity; m.extra.fall_flying = fall_flying; m.extra.fall_fly_ticks = fly_ticks; + m.extra.auto_spin_attack = spinning; m.extra.main_hand_left = self.settings.main_hand_left; m.extra.using_item = using; m.extra.using_off_hand = using_off_hand; @@ -451,6 +453,7 @@ impl Game<'_> { out, ); self.player_elytra_geometry(m, camera, alpha as f32, packed, out); + self.spin_attack_geometry(m, camera, alpha as f32, packed, out); self.held_item_geometry(m, camera, alpha, packed, true, out); } /// `extractEntityInInventoryFollowsMouse`: the player in the box @@ -592,6 +595,47 @@ impl Game<'_> { out, ); } + /// `SpinAttackEffectLayer`: Riptide's two boxes turning around a spinning + /// player (`SpinAttackEffectModel.setupAnim`). + fn spin_attack_geometry( + &self, + m: &Mob, + camera: glam::DVec3, + partial: f32, + light: u32, + out: &mut Vec, + ) { + if !m.extra.auto_spin_attack { + return; + } + let (Some(model), Some(rect)) = ( + self.res.spin_attack().as_ref(), + self.gui.atlas.sprites.get("entity/trident/trident_riptide"), + ) else { + return; + }; + let age = m.age as f32 + partial; + horizon_client::mobs::render_model( + model, + horizon_client::mobs::render::base_transform(m, partial, camera), + &|part| { + let mut p = part.pose; + if let Some(i) = part + .name + .strip_prefix("box") + .and_then(|i| i.parse::().ok()) + { + let angle = age * -(45.0 + f32::from(i + 1) * 5.0); + p[4] = wrap(angle).to_radians(); + } + p + }, + [rect.u0, rect.v0, rect.u1, rect.v1], + light, + 0, + out, + ); + } } fn player_preview_quads( diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index b24f4540e..c31094596 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -122,6 +122,38 @@ impl Game<'_> { let sky = self.world.light(x, y + 1, z) >> 4 == 15; water || (self.world.weather.raining && sky) } + /// The living entities a spinning player can touch this tick, for + /// `LivingEntity.checkAutoSpinAttack` (none when not spinning). + pub(super) fn spin_targets(&self) -> Vec<(u32, Aabb)> { + let Some(p) = self + .player + .as_ref() + .filter(|p| p.auto_spin_attack_ticks > 0) + else { + return Vec::new(); + }; + // A spin moves a few blocks a tick at most. + let near = p.bounds().inflate(Vec3::new(16.0, 16.0, 16.0)); + self.mobs + .iter() + .filter(|m| m.alive() && m.bounds().intersects(near)) + .map(|m| (m.id, m.bounds())) + .collect() + } + /// `Player.doAutoAttackOnTouch`: the touched entity takes `Player.attack` + /// with the spin's damage; once the spin is over its damage is cleared. + pub(super) fn end_spin_attack(&mut self, hit: Option) { + if let Some(id) = hit + && let Some(index) = self.mobs.iter().position(|m| m.id == id) + { + self.attack_mob(index); + } + if let Some(p) = self.player.as_mut() + && p.auto_spin_attack_ticks <= 0 + { + p.auto_spin_attack_dmg = 0.0; + } + } /// `TridentItem.releaseUsing`. pub(super) fn release_trident(&mut self, ticks: u32) { if ticks < 10 { @@ -152,6 +184,9 @@ impl Game<'_> { p.velocity.y + d[1] * f64::from(strength), p.velocity.z + d[2] * f64::from(strength), ); + // Player.startAutoSpinAttack(20, 8, stack). + p.auto_spin_attack_ticks = 20; + p.auto_spin_attack_dmg = 8.0; if p.ground.on_ground { p.position.y += 1.2; } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 28bcadeed..e87032f07 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -690,6 +690,8 @@ pub struct Extra { pub blocking: bool, pub fall_flying: bool, pub fall_fly_ticks: i32, + /// `LivingEntity.isAutoSpinAttack` (Riptide). + pub auto_spin_attack: bool, pub main_hand_left: bool, pub elytra: ElytraAnimation, pub swim: SwimAnimation, diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 99548ec3f..4248f22c6 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -771,6 +771,11 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 .sqrt() .min(1.0); base *= glam::Mat4::from_rotation_z(f * flip_degrees(m).to_radians()); + } else if m.extra.auto_spin_attack { + // Riptide: lying along the look direction, spinning 75 degrees a tick. + let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha; + base *= glam::Mat4::from_rotation_x((-90.0 - pitch).to_radians()) + * glam::Mat4::from_rotation_y(((m.age as f32 + alpha) * -75.0).to_radians()); } else if matches!(m.custom_name.as_deref(), Some("Dinnerbone" | "Grumm")) { // isEntityUpsideDown base *= glam::Mat4::from_translation(glam::Vec3::new(0.0, m.height() + 0.1, 0.0)) @@ -781,7 +786,9 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 let ticks = m.extra.fall_fly_ticks as f32 + alpha; let scale = (ticks * ticks / 100.0).min(1.0); let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha; - base *= glam::Mat4::from_rotation_x((scale * (-90.0 - pitch)).to_radians()); + if !m.extra.auto_spin_attack { + base *= glam::Mat4::from_rotation_x((scale * (-90.0 - pitch)).to_radians()); + } let yaw = m.previous_head_yaw + wrap(m.head_yaw - m.previous_head_yaw) * alpha; let (look_x, look_z) = (-(yaw.to_radians()).msin(), (yaw.to_radians()).mcos()); let v = m.velocity; diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 7bdaea785..192e900a1 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -247,6 +247,14 @@ pub struct PlayerMotion { pub glide_ending: bool, /// Glider durability to take this tick (updateFallFlying). pub glider_wear: u32, + /// `LivingEntity.autoSpinAttackTicks` and `autoSpinAttackDmg`: Riptide's + /// spin. The damage stays until the game has dealt the hit. + pub auto_spin_attack_ticks: i32, + pub auto_spin_attack_dmg: f32, + /// The living entities the game put near a spinning player (id, box). + pub spin_targets: Vec<(u32, Aabb)>, + /// The entity the spin touched this tick (`doAutoAttackOnTouch`). + pub spin_hit: Option, pub sprinting: bool, pub sprint_input: crate::sprint::SprintState, pub shift_key_down: bool, @@ -409,6 +417,10 @@ impl PlayerMotion { fall_fly_ticks: 0, glide_ending: false, glider_wear: 0, + auto_spin_attack_ticks: 0, + auto_spin_attack_dmg: 0.0, + spin_targets: Vec::new(), + spin_hit: None, sprinting: false, sprint_input: crate::sprint::SprintState::default(), shift_key_down: false, @@ -919,6 +931,7 @@ impl MotionWorld<'_, '_, '_> { input.z = 0.0; } self.jump_phase()?; + let before_travel = self.player.bounds(); // Player.travel: swim steering, then LivingEntity.travel (fluids // first, then gliding, then air), keeping 0.6 of the vertical speed // while flying. @@ -973,8 +986,26 @@ impl MotionWorld<'_, '_, '_> { { self.freeze_damage()?; } + if self.player.auto_spin_attack_ticks > 0 { + self.player.auto_spin_attack_ticks -= 1; + self.check_auto_spin_attack(before_travel); + } Ok(()) } + /// `LivingEntity.checkAutoSpinAttack`: the first living entity in the + /// box swept this tick takes the hit and ends the spin, bouncing the + /// player back at a fifth of its speed; a wall ends it too. + fn check_auto_spin_attack(&mut self, before: Aabb) { + let swept = before.union_bounds(self.player.bounds()); + let p = &mut self.player; + if let Some(&(id, _)) = p.spin_targets.iter().find(|(_, b)| b.intersects(swept)) { + p.spin_hit = Some(id); + p.auto_spin_attack_ticks = 0; + p.velocity = p.velocity.scale(-0.2); + } else if p.collision.horizontal { + p.auto_spin_attack_ticks = 0; + } + } /// `hurtServer(damageSources().freeze(), 1)` for a fully frozen player. fn freeze_damage(&mut self) -> Result<()> { let id = self @@ -2659,6 +2690,49 @@ mod tests { } } #[test] + fn a_riptide_spin_lies_flat_and_ends_on_the_first_entity_it_touches() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let mut scene = World::test_scene(&assets, &render, 2).unwrap(); + let ahead = Aabb::new(Vec3::new(20.2, 9.0, 21.5), Vec3::new(20.8, 11.0, 22.1)); + for target in [None, Some(ahead)] { + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 10.0, 20.5)).unwrap(); + player.auto_spin_attack_ticks = 20; + player.auto_spin_attack_dmg = 8.0; + player.velocity = Vec3::new(0.0, 0.0, 1.0); + player.spin_targets = target.map(|b| (7, b)).into_iter().collect(); + let mut w = MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + }; + w.simulation_tick([0.0, 0.0], false).unwrap(); + if target.is_some() { + // Touched: the hit, no more spin, bounced back at a fifth. + assert_eq!(w.player.spin_hit, Some(7)); + assert_eq!(w.player.auto_spin_attack_ticks, 0); + assert!(w.player.velocity.z < 0.0, "{:?}", w.player.velocity); + assert_eq!(w.player.pose, crate::pose::Pose::Standing); + } else { + assert_eq!(w.player.spin_hit, None); + assert_eq!(w.player.auto_spin_attack_ticks, 19); + assert_eq!(w.player.pose, crate::pose::Pose::SpinAttack); + assert_eq!(w.player.dimensions.height, 0.6); + } + } + } + #[test] fn a_landing_glide_lasts_a_tick_so_a_jump_keeps_its_speed() { let root = Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../.local/horizon-client") diff --git a/crates/horizon-client/src/pose.rs b/crates/horizon-client/src/pose.rs index 9c8124b0e..e34b1f1fc 100644 --- a/crates/horizon-client/src/pose.rs +++ b/crates/horizon-client/src/pose.rs @@ -14,6 +14,7 @@ pub enum Pose { Crouching, Swimming, FallFlying, + SpinAttack, } impl Pose { pub fn name(self) -> &'static str { @@ -22,13 +23,14 @@ impl Pose { Self::Crouching => "CROUCHING", Self::Swimming => "SWIMMING", Self::FallFlying => "FALL_FLYING", + Self::SpinAttack => "SPIN_ATTACK", } } pub fn dimensions(self, scale: f32) -> Dimensions { let (height, eye_height) = match self { Self::Standing => (1.8, 1.62), Self::Crouching => (1.5, 1.27), - Self::Swimming | Self::FallFlying => (0.6, 0.4), + Self::Swimming | Self::FallFlying | Self::SpinAttack => (0.6, 0.4), }; Dimensions { width: 0.6 * scale, @@ -98,11 +100,13 @@ impl MotionWorld<'_, '_, '_> { if !self.can_fit_pose(Pose::Swimming)? { return Ok(()); } - // Player.getDesiredPose: swimming before gliding. + // Player.getDesiredPose: swimming, gliding, Riptide's spin. let desired = if self.player.swimming { Pose::Swimming } else if self.player.fall_flying { Pose::FallFlying + } else if self.player.auto_spin_attack_ticks > 0 { + Pose::SpinAttack } else if self.player.shift_key_down && !self.player.flying { Pose::Crouching } else { From c2b7f3a4ea2dc5fdb86f4aa6469eabc4b2a26e22 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:55:54 +0200 Subject: [PATCH 02/19] Slow-frame and slow-tick lines show the CPU time of each span HORIZON_SPIKES spans keep the thread's CPU time beside their wall time, and the slow-frame line gives the render thread's CPU time in the frame. A span that mostly waited (for the GPU, a lock or a core) prints both (`submit 30.2/0.1`), so a frame that waited reads apart from one that worked. Found the cause of #678's long frames: the render thread losing its core in queue.submit. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 21 +++-- crates/horizon-client/src/game/levels.rs | 7 +- crates/horizon-client/src/spans.rs | 100 ++++++++++++++++++++--- docs/graphics.md | 2 +- 4 files changed, 103 insertions(+), 27 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2df6aa9b0..518fba2db 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10933,6 +10933,10 @@ impl ApplicationHandler for Game<'_> { WindowEvent::RedrawRequested => { self.observe_fullscreen(); let now = Instant::now(); + let frame_cpu = self + .options + .spikes + .and_then(|_| horizon_client::spans::thread_cpu()); let elapsed = now.duration_since(self.previous); self.frame_ticks = elapsed.as_secs_f32() * 20.0; self.previous = now; @@ -10999,15 +11003,16 @@ impl ApplicationHandler for Game<'_> { let cpu = now.elapsed().saturating_sub(r.last_wait).as_secs_f32() * 1000.0; let spans = horizon_client::spans::take(); if cpu > threshold { - let list: Vec = spans - .iter() - .filter(|(_, ms)| *ms >= 0.5) - .map(|(n, ms)| format!("{n} {ms:.1}")) - .collect(); + // The render thread's own CPU time in the frame: + // far below the wall time, the frame waited. + let worked = horizon_client::spans::thread_cpu() + .zip(frame_cpu) + .map_or_else(String::new, |(end, start)| { + format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0) + }); log::info!( - "Horizon: slow frame {cpu:.1} ms ({} ticks): {}", - steps, - list.join(", ") + "Horizon: slow frame {cpu:.1} ms{worked} ({steps} ticks): {}", + horizon_client::spans::describe(&spans) ); } } diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 31b34a9d0..7df5541b4 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -312,15 +312,10 @@ impl Game<'_> { .map_or_else(String::new, |(end, start)| { format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0) }); - let list: Vec = spans - .iter() - .filter(|(_, ms)| *ms >= 0.5) - .map(|(n, ms)| format!("{n} {ms:.1}")) - .collect(); log::info!( "Horizon: slow tick {wall:.1} ms{cpu} ({} mobs): {}", self.mobs.len(), - list.join(", ") + horizon_client::spans::describe(&spans) ); } result diff --git a/crates/horizon-client/src/spans.rs b/crates/horizon-client/src/spans.rs index 5c37f2bfc..ce69be8ce 100644 --- a/crates/horizon-client/src/spans.rs +++ b/crates/horizon-client/src/spans.rs @@ -1,8 +1,10 @@ //! Named timings within a frame, for finding what makes a frame slow: //! `HORIZON_SPIKES=MS` prints the spans of every frame whose CPU time //! exceeds MS milliseconds, and of every server tick (dedicated or -//! integrated) longer than MS. Costs one clock read per span when enabled -//! and a relaxed load otherwise. +//! integrated) longer than MS. Each span keeps its wall time and the +//! thread's CPU time inside it, so a span that waited (for a lock, the GPU +//! or a core on a busy machine) shows apart from one that worked. Costs two +//! clock reads per span when enabled and a relaxed load otherwise. use std::{ cell::RefCell, sync::atomic::{AtomicBool, Ordering}, @@ -11,7 +13,15 @@ use std::{ static ENABLED: AtomicBool = AtomicBool::new(false); thread_local! { - static SPANS: RefCell> = const { RefCell::new(Vec::new()) }; + static SPANS: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// A named timing: wall milliseconds and the thread's CPU milliseconds in it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Span { + pub name: &'static str, + pub ms: f32, + pub cpu_ms: f32, } pub fn enable(on: bool) { @@ -23,10 +33,13 @@ pub fn time(name: &'static str, f: impl FnOnce() -> T) -> T { if !ENABLED.load(Ordering::Relaxed) { return f(); } - let started = Instant::now(); + let (started, cpu) = (Instant::now(), thread_cpu()); let out = f(); let ms = started.elapsed().as_secs_f32() * 1000.0; - SPANS.with(|s| s.borrow_mut().push((name, ms))); + let cpu_ms = thread_cpu() + .zip(cpu) + .map_or(ms, |(end, start)| (end - start).as_secs_f32() * 1000.0); + SPANS.with(|s| s.borrow_mut().push(Span { name, ms, cpu_ms })); out } /// The CPU time this thread has used, where the platform tells it: a tick @@ -42,21 +55,84 @@ pub fn thread_cpu() -> Option { None } /// The frame's spans, summed by name, slowest first; clears them. -pub fn take() -> Vec<(&'static str, f32)> { +pub fn take() -> Vec { let spans = SPANS.with(|s| std::mem::take(&mut *s.borrow_mut())); - let mut sums: Vec<(&'static str, f32)> = Vec::new(); - for (name, ms) in spans { - match sums.iter_mut().find(|(n, _)| *n == name) { - Some(entry) => entry.1 += ms, - None => sums.push((name, ms)), + let mut sums: Vec = Vec::new(); + for span in spans { + match sums.iter_mut().find(|s| s.name == span.name) { + Some(sum) => { + sum.ms += span.ms; + sum.cpu_ms += span.cpu_ms; + } + None => sums.push(span), } } - sums.sort_by(|a, b| b.1.total_cmp(&a.1)); + sums.sort_by(|a, b| b.ms.total_cmp(&a.ms)); sums } +/// `name wall` for spans of at least 0.5 ms, with `/cpu` when the thread +/// worked for less than nine tenths of it: the slow-frame and slow-tick lines. +pub fn describe(spans: &[Span]) -> String { + let list: Vec = spans + .iter() + .filter(|s| s.ms >= 0.5) + .map(|s| { + if s.cpu_ms < s.ms * 0.9 { + format!("{} {:.1}/{:.1}", s.name, s.ms, s.cpu_ms) + } else { + format!("{} {:.1}", s.name, s.ms) + } + }) + .collect(); + list.join(", ") +} #[cfg(test)] mod tests { + use super::Span; + + /// Spans of one name add up; a span the thread spent mostly waiting + /// shows its CPU time after the wall time, short ones are left out. + #[test] + fn spans_sum_by_name_and_show_waits() { + super::SPANS.with(|s| { + s.borrow_mut().extend([ + Span { + name: "tick", + ms: 2.0, + cpu_ms: 2.0, + }, + Span { + name: "submit", + ms: 30.0, + cpu_ms: 0.2, + }, + Span { + name: "tick", + ms: 3.0, + cpu_ms: 2.9, + }, + Span { + name: "hud", + ms: 0.3, + cpu_ms: 0.3, + }, + ]); + }); + let spans = super::take(); + assert_eq!( + spans[0], + Span { + name: "submit", + ms: 30.0, + cpu_ms: 0.2 + } + ); + assert_eq!((spans[1].name, spans[1].ms), ("tick", 5.0)); + assert_eq!(super::describe(&spans), "submit 30.0/0.2, tick 5.0"); + assert!(super::take().is_empty()); + } + /// The thread's CPU clock moves with work done on it, not with time /// spent asleep. #[cfg(unix)] diff --git a/docs/graphics.md b/docs/graphics.md index b1c3c0209..34032a641 100644 --- a/docs/graphics.md +++ b/docs/graphics.md @@ -64,7 +64,7 @@ python3 tools/graphics_bench.py --compare baseline-4080 mine-gpu # markdown ta vscreen is a headless compositor whose frames are software-rendered (lavapipe), so its frame times measure the CPU, rasterisation included. `--offscreen` (`horizon-client --offscreen`) renders into a texture on the most powerful GPU instead of the window, which measures the RTX 4080 under the same compositor. `--distances`, `--scenes` and `--build` pick a subset or another build. Results go to `benchmarks/graphics/