Update Color replacement to be actually useful

This commit is contained in:
DBotThePony 2024-05-22 19:01:27 +07:00
parent b41d45b3e9
commit 69e0a8737e
Signed by: DBot
GPG Key ID: DCC23B5715498507

View File

@ -1,13 +1,17 @@
package ru.dbotthepony.kstarbound.defs
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.TypeAdapter
import com.google.gson.annotations.JsonAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap
import ru.dbotthepony.kommons.gson.consumeNull
import ru.dbotthepony.kommons.math.RGBAColor
@JsonAdapter(ColorReplacements.Adapter::class)
class ColorReplacements private constructor(private val mapping: Int2IntOpenHashMap) {
constructor(mapping: Map<Int, Int>) : this(Int2IntOpenHashMap(mapping))
@ -15,9 +19,11 @@ class ColorReplacements private constructor(private val mapping: Int2IntOpenHash
return mapping.getOrDefault(color, color)
}
companion object : TypeAdapter<ColorReplacements>() {
val EMPTY = ColorReplacements(Int2IntOpenHashMap())
fun toImageOperator(): String {
return "replace;${mapping.int2IntEntrySet().joinToString { "${RGBAColor.rgb(it.intKey).toHexStringRGB()}=${RGBAColor.rgb(it.intValue).toHexStringRGB()}" }}"
}
class Adapter(gson: Gson) : TypeAdapter<ColorReplacements>() {
override fun write(out: JsonWriter, value: ColorReplacements?) {
if (value == null)
out.nullValue()
@ -25,8 +31,8 @@ class ColorReplacements private constructor(private val mapping: Int2IntOpenHash
out.beginObject()
for ((k, v) in value.mapping) {
out.name(k.toString(16))
out.value(v.toString(16))
out.name(RGBAColor.rgb(k).toHexStringRGB())
out.value(RGBAColor.rgb(v).toHexStringRGB())
}
out.endObject()
@ -40,7 +46,7 @@ class ColorReplacements private constructor(private val mapping: Int2IntOpenHash
if (`in`.nextString() != "")
throw JsonSyntaxException("Invalid color replacement definition near ${`in`.path}")
return ColorReplacements.EMPTY
return EMPTY
}
val mapping = Int2IntOpenHashMap()
@ -48,10 +54,20 @@ class ColorReplacements private constructor(private val mapping: Int2IntOpenHash
`in`.beginObject()
while (`in`.peek() != JsonToken.END_OBJECT) {
val k = `in`.nextName()
val v = `in`.nextString()
val kGet = `in`.nextName()
val vGet = `in`.nextString()
val k = RGBAColor.fromHexStringRGB(kGet)
val v = RGBAColor.fromHexStringRGB(vGet)
mapping[k.toInt(16)] = v.toInt(16)
if (k == null) {
throw JsonSyntaxException("Not a valid Hex color: $kGet")
}
if (v == null) {
throw JsonSyntaxException("Not a valid Hex color: $vGet")
}
mapping[k.toRGBA()] = v.toRGBA()
}
`in`.endObject()
@ -59,4 +75,8 @@ class ColorReplacements private constructor(private val mapping: Int2IntOpenHash
return ColorReplacements(mapping)
}
}
companion object {
val EMPTY = ColorReplacements(Int2IntOpenHashMap())
}
}