Skip to content

Commit

Permalink
Refactor update player resource packs
Browse files Browse the repository at this point in the history
  • Loading branch information
james58899 committed Nov 10, 2024
1 parent 048c1f0 commit bc708ba
Showing 1 changed file with 20 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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<Player, List<ResourcePackInfo>> = 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<ResourcePackInfo>()
val packsToRemove = mutableListOf<ResourcePackInfo>()

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)
}
Expand Down

0 comments on commit bc708ba

Please sign in to comment.