aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/at/hannibal2/skyhanni/utils/renderables/ScrollInput.kt
blob: e47cca31c3310c58c85def38f3e9f1f8cb9585aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package at.hannibal2.skyhanni.utils.renderables

import org.lwjgl.input.Mouse

abstract class ScrollInput(
    private val scrollValue: ScrollValue,
    protected val minValue: Int,
    protected val maxValue: Int,
    protected val velocity: Double,
    protected val dragScrollMouseButton: Int?,
    startValue: Double?
) {

    init {
        scrollValue.init(startValue ?: minValue.toDouble())
        coerceInLimit()
    }

    protected var scroll
        set(value) {
            scrollValue.setValue(value)
        }
        get() = scrollValue.getValue()

    private var mouseEventTime = 0L

    fun asInt() = scroll.toInt()
    fun asDouble() = scroll

    protected fun coerceInLimit() =
        if (maxValue < minValue) {
            scroll = minValue.toDouble()
        } else {
            scroll = scroll.coerceIn(minValue.toDouble(), maxValue.toDouble())
        }

    protected fun isMouseEventValid(): Boolean {
        val mouseEvent = Mouse.getEventNanoseconds()
        val mouseEventsValid = mouseEvent - mouseEventTime > 20L
        mouseEventTime = mouseEvent
        return mouseEventsValid
    }

    abstract fun update(isValid: Boolean)

    companion object {

        class Vertical(
            scrollValue: ScrollValue,
            minHeight: Int,
            maxHeight: Int,
            velocity: Double,
            dragScrollMouseButton: Int?,
            startValue: Double? = null
        ) : ScrollInput(scrollValue, minHeight, maxHeight, velocity, dragScrollMouseButton, startValue) {
            override fun update(isValid: Boolean) {
                if (maxValue < minValue) return
                if (!isValid || !isMouseEventValid()) return
                if (dragScrollMouseButton != null && Mouse.isButtonDown(dragScrollMouseButton)) {
                    scroll += Mouse.getEventDY() * velocity
                }
                val deltaWheel = Mouse.getEventDWheel()
                scroll += -deltaWheel.coerceIn(-1, 1) * 2.5 * velocity
                coerceInLimit()
            }

        }
    }
}

class ScrollValue {
    var field: Double? = null
    fun getValue(): Double =
        field ?: throw IllegalStateException("ScrollValue should be initialized before get.")

    fun setValue(value: Double) {
        field = value
    }

    fun init(value: Double) {
        if (field != null) return
        field = value
    }

}