perf: batch particles, drop LUNGE, fix target search, stop per-tick map copy

Measured on zern.cc with 20 mineflayer bots on SNIPE, empty world and then
with 625 entities clustered around them.

getLungeTarget searched a 120x120x120 cube to find one entity inside a 5.7
degree cone, and ran TWO raytraces per entity inside that loop. The second one,
rayTraceBlocks(eye, dir, 120), does not depend on the entity at all: eye, dir
and the distance are loop-invariant, so the same answer was recomputed once per
entity, each time walking up to 120 blocks. On a populated world that is up to
2N raytraces per call, and updatePreview calls it every 4 ticks per player
holding a knife.

Now the query is an AABB along the look direction, the block ray is computed
once before the loop, and hasLineOfSight is only called on candidates in
distance order - usually exactly once. The common case of zero or one target
allocates nothing at all; tracking the two nearest inline avoids the lists and
the sort entirely.

Honest note on the measurement: this fix did NOT show up. 10.5 ms median
before vs 10.8 ms after with 625 entities nearby. Working the numbers back,
that path costs roughly 1% of capacity in this scenario, which is below the
noise floor. The code change is correct by inspection, not by measurement, and
it would matter far more in a world with thousands of entities than 625.

LUNGE is removed. Its shockwave drew points = radius*6 and issued THREE
separate spawnParticle calls per point, so a radius-10 ring sent 180 packets
PER TICK, expanding, per cast. That is gone with the ability.

Particle batching, which is the real cost in this plugin. Every spawnParticle
is one packet per viewer. MagicListener's hit ring was 36 separate calls and
its explosion shell was 72; the OVERHEAD aiming ring was 32 packets every
tick. spawnParticle with count>1 spreads particles inside the offset volume, so
a ring of radius r becomes a filled disc of the same radius - indistinguishable
at half-block scale, and the particle count is unchanged. New Particles helper.

TensionManager.updateBar ran every tick per player: String.format, two
Component.text, and a progress packet. Now it repaints only when the whole
percent changes, and the percent is computed with integer math. At 0.25/tick
regen that is four repaints a second instead of twenty, and zero on a full
bar. The percent cache is cleared on quit and resynced on death so the bar
cannot get stuck.

tickBattle copied the entire battleEnemies map, including every nested set,
twenty times a second - purely so it could iterate and delete from the same
map. Keys are now collected into a list and dropped after the loop.

getMode now collapses an unknown stored mode onto STARS. Without that a knife
issued before LUNGE was removed could not be mode-switched at all: the index
lookup found nothing, stayed at zero, and the knife was stuck.
This commit is contained in:
SashegDev
2026-10-01 12:50:33 +00:00
parent 81e86fdc9f
commit 4890f91991
6 changed files with 248 additions and 348 deletions
@@ -0,0 +1,70 @@
package me.sashegdev.blackknife;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.Particle;
import org.bukkit.World;
/**
* Батчинг частиц.
*
* <p>Цена в плагине измеряется не в миллисекундах, а в пакетах. Каждый вызов
* {@code spawnParticle} — это отдельный пакет всем игрокам в радиусе, плюс
* сериализация и аллокация. Кольцо из 12 углов на 3 слоя было 36 вызовами с
* count=1, то есть 36 пакетами на одно попадание; во взрыве — 72.
*
* <p>Смысл в том, что {@code spawnParticle} с count больше одного раскидывает
* частицы случайно внутри объёма смещения. Поэтому кольцо радиуса r честно
* превращается в заполненный диск того же радиуса. На масштабе половины блока
* разница глазом не видна, а пакетов в разы меньше.
*
* <p>Числа частиц подобраны так, чтобы плотность осталась прежней: кольцо на
* 12x3 становится тремя дисками по 12 частиц, то есть ровно те же 36 точек.
*/
public final class Particles {
private Particles() {
}
/** Высота слоя кольца, как в исходной развёртке. */
private static final double LAYER_STEP = 0.25D;
/**
* Кольцо вокруг точки: {@code layers} вызовов вместо
* {@code segments * layers}.
*/
public static void ring(World world, Location center, double radius,
Particle.DustOptions dust, int segments, int layers) {
ring(world, center, radius, dust, segments, layers, Particle.CRIT, 10);
}
public static void ring(World world, Location center, double radius,
Particle.DustOptions dust, int segments, int layers,
Particle spark, int sparkCount) {
// Один диск на слой: offset задаёт полуразброс, поэтому частицы ложатся
// в диск радиуса radius вокруг центра слоя, а не в точку.
for (int h = 0; h < layers; h++) {
final double y = center.getY() + ((h - (layers - 1) / 2.0D) * LAYER_STEP);
final Location at = new Location(world, center.getX(), y, center.getZ());
world.spawnParticle(Particle.DUST, at, segments, radius, 0.0D, radius, 0.0D, dust);
}
if (spark != null && sparkCount > 0) {
world.spawnParticle(spark, center, sparkCount, radius, radius * 0.5D, radius, 0.1D);
}
}
/** Плоское кольцо на земле, как ударная волна. */
public static void groundRing(World world, Location center, double radius,
Particle.DustOptions dust, int count) {
world.spawnParticle(Particle.DUST, center, count, radius, 0.0D, radius, 0.0D, dust);
}
/**
* Единичная частица без аллокаций на стороне вызывающего.
* Обёртка существует только чтобы не плодить DustOptions в циклах —
* объект переиспользуется, а не создаётся на каждую частицу.
*/
public static Particle.DustOptions dust(int r, int g, int b, float size) {
return new Particle.DustOptions(Color.fromRGB(r, g, b), size);
}
}