aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/moe/nea/firmament/events/CustomItemModelEvent.kt
blob: cf75144e8215b9550f64312d35acb7159604c500 (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
/*
 * SPDX-FileCopyrightText: 2023 Linnea Gräf <nea@nea.moe>
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 */

package moe.nea.firmament.events

import java.util.*
import net.minecraft.client.render.model.BakedModel
import net.minecraft.client.render.model.BakedModelManager
import net.minecraft.client.util.ModelIdentifier
import net.minecraft.item.ItemStack

data class CustomItemModelEvent(
    val itemStack: ItemStack,
    var overrideModel: ModelIdentifier? = null,
) : FirmamentEvent() {
    companion object : FirmamentEventBus<CustomItemModelEvent>() {
        private val cache = IdentityHashMap<ItemStack?, Any>()
        private val sentinelNull = Object()

        fun clearCache() {
            cache.clear()
        }

        @JvmStatic
        fun getModelIdentifier(itemStack: ItemStack?): ModelIdentifier? {
            if (itemStack == null) return null
            return publish(CustomItemModelEvent(itemStack)).overrideModel
        }

        @JvmStatic
        fun getModel(itemStack: ItemStack?, thing: BakedModelManager): BakedModel? {
            if (itemStack == null) return null
            val cachedValue = cache.getOrPut(itemStack) {
                val modelId = getModelIdentifier(itemStack) ?: return@getOrPut sentinelNull
                val bakedModel = thing.getModel(modelId)
                if (bakedModel === thing.missingModel) return@getOrPut sentinelNull
                bakedModel
            }
            if (cachedValue === sentinelNull)
                return null
            return cachedValue as BakedModel
        }
    }
}