Archived
1
0
Fork 0

Add global incrementing tick number to scheduler

This commit is contained in:
Moritz Ruth 2021-02-28 13:19:58 +01:00
parent 58dccea7df
commit 8bfe0141bf
No known key found for this signature in database
GPG key ID: AFD57E23E753841B
4 changed files with 15 additions and 8 deletions

View file

@ -4,6 +4,13 @@ import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
interface Scheduler {
/**
* Only safe to access from the scheduler thread.
*
* Will overflow after about 5 years.
*/
val currentTickNumber: Int
/**
* Executes [block] after [delay] ticks passed.
*

View file

@ -21,6 +21,8 @@ class UranosScheduler : Scheduler {
val logger = Logger("Scheduler", false)
override var currentTickNumber = Int.MIN_VALUE
inner class Task<R : Any>(
val fn: suspend () -> R,
val interval: Long?,
@ -29,8 +31,6 @@ class UranosScheduler : Scheduler {
@Volatile
var cancelled: Boolean = false
val creationStackTrace = Thread.currentThread().stackTrace
override fun cancel() {
tasks.remove(this)
cancelled = true
@ -68,6 +68,8 @@ class UranosScheduler : Scheduler {
val duration = System.currentTimeMillis() - startTime
if (duration > interval) logger.warn("Last tick took ${duration}ms, but should only take ${interval}ms")
}
currentTickNumber += 1
}, 0, interval, TimeUnit.MILLISECONDS)
}

View file

@ -128,15 +128,12 @@ class UranosServer internal constructor() : Server() {
}
private fun startTicking() {
var index = 0
scheduler.executeRepeating(1, 0) {
runInServerThread {
players.forEach { it.container.tick() }
internalEntities.forEach { it.tick() }
sessions.forEach { it.tick(index) }
sessions.forEach { it.tick() }
}
index++
}
}

View file

@ -2,6 +2,7 @@ package space.uranos.net
import io.netty.buffer.ByteBuf
import kotlinx.coroutines.*
import space.uranos.Uranos
import space.uranos.UranosServer
import space.uranos.chat.ChatColor
import space.uranos.chat.ChatComponent
@ -169,8 +170,8 @@ class UranosSession(val channel: io.netty.channel.Channel, val server: UranosSer
fun sendKeepAlivePacket() = send(OutgoingKeepAlivePacket(System.currentTimeMillis()))
suspend fun tick(index: Int) {
if (earlyPlayer != null && index % KEEP_ALIVE_PACKET_INTERVAL == 0L) sendKeepAlivePacket()
suspend fun tick() {
if (earlyPlayer != null && Uranos.scheduler.currentTickNumber % KEEP_ALIVE_PACKET_INTERVAL == 0L) sendKeepAlivePacket()
packetsAdapter.tick()
}