From bc708bad81b94fe2bb7ea3571a378cf932d57c89 Mon Sep 17 00:00:00 2001 From: James58899 Date: Sun, 10 Nov 2024 18:56:33 +0800 Subject: [PATCH] Refactor update player resource packs --- .../proxy/resourcepack/ResourcePackManager.kt | 40 +++++++++---------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/main/kotlin/one/oktw/galaxy/proxy/resourcepack/ResourcePackManager.kt b/src/main/kotlin/one/oktw/galaxy/proxy/resourcepack/ResourcePackManager.kt index ad328e7..81a10bb 100644 --- a/src/main/kotlin/one/oktw/galaxy/proxy/resourcepack/ResourcePackManager.kt +++ b/src/main/kotlin/one/oktw/galaxy/proxy/resourcepack/ResourcePackManager.kt @@ -3,35 +3,35 @@ package one.oktw.galaxy.proxy.resourcepack import com.velocitypowered.api.proxy.Player import com.velocitypowered.api.proxy.player.ResourcePackInfo import one.oktw.galaxy.proxy.Main.Companion.main -import kotlin.math.max +import kotlin.math.min class ResourcePackManager { private val appliedPacks: MutableMap> = mutableMapOf() fun updatePlayerResourcePacks(player: Player, galaxy: String) { - val targetResourcePacks = main.config.galaxies[galaxy]?.ResourcePacks?.distinct()?.mapNotNull { main.config.resourcePacks[it]?.packInfo() } ?: return - val appliedResourcePacks = this.appliedPacks.getOrPut(player) { listOf() } - - var skipFurtherCheck = false - val packsToQueue = mutableListOf() - val packsToRemove = mutableListOf() - - for (index in 0..max(targetResourcePacks.size, appliedResourcePacks.size)) { - // Skip applied pack on same position - val targetPack = targetResourcePacks.getOrNull(index) - val appliedPack = appliedResourcePacks.getOrNull(index) - if (targetPack?.id == appliedPack?.id && !skipFurtherCheck) continue - - skipFurtherCheck = true - if (index < appliedResourcePacks.size) packsToRemove.add(appliedResourcePacks[index]) - if (index < targetResourcePacks.size) packsToQueue.add(targetResourcePacks[index]) + val new = main.config.galaxies[galaxy]?.ResourcePacks?.mapNotNull { main.config.resourcePacks[it]?.packInfo() } ?: emptyList() + val old = this.appliedPacks.getOrElse(player) { listOf() } + + // Matching new resource packs + var updateIndex = old.lastIndex + for (i in 0..min(old.size, new.size)) { + if (old.getOrNull(i)?.hash != new.getOrNull(i)?.hash) { + updateIndex = i + break + } } - packsToRemove.forEach { pack -> player.removeResourcePacks(pack) } - packsToQueue.forEach { pack -> player.sendResourcePacks(pack) } - appliedPacks[player] = targetResourcePacks.toList() + // Remove not match resource packs + old.subList(updateIndex, old.size).forEach(player::removeResourcePacks) + + // Add new resource packs + new.subList(updateIndex, new.size).forEach(player::sendResourcePacks) + + // Save player resource packs state + appliedPacks[player] = new.toList() } + // Remove player resource packs state fun removePlayer(player: Player) { appliedPacks.remove(player) }