Skip to content

Commit 0528c1e

Browse files
authored
feat(motd): compile and project native atlas sprites by client protocol (#114)
1 parent f8941f8 commit 0528c1e

5 files changed

Lines changed: 221 additions & 28 deletions

File tree

‎velocity/src/main/kotlin/gg/grounds/proxy/velocity/motd/CompiledMotd.kt‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ package gg.grounds.proxy.velocity.motd
33
import com.google.gson.JsonObject
44
import com.google.gson.JsonParser
55
import net.kyori.adventure.text.Component
6+
import net.kyori.adventure.text.ObjectComponent
67
import net.kyori.adventure.text.TextComponent
78
import net.kyori.adventure.text.format.Style
89
import net.kyori.adventure.text.format.TextDecoration
10+
import net.kyori.adventure.text.`object`.SpriteObjectContents
911

1012
/** Splits resolved components without carrying implicit style across independent client values. */
1113
internal fun componentLines(component: Component): List<Component> {
@@ -34,8 +36,12 @@ internal fun componentLines(component: Component): List<Component> {
3436
class CompiledMotd(document: JsonObject, private val alignments: List<String>) {
3537
private val text = CompiledServerText(document)
3638

37-
fun render(values: Map<String, String>, lineWidth: Int = 271): Component {
38-
val rendered = text.render(values)
39+
fun render(
40+
values: Map<String, String>,
41+
lineWidth: Int = 271,
42+
supportsSprites: Boolean = true,
43+
): Component {
44+
val rendered = projectNativeSprites(text.render(values), supportsSprites)
3945
if (alignments.all { it == "left" }) return rendered
4046
var result: Component = Component.empty()
4147
for ((index, line) in componentLines(rendered).withIndex()) {
@@ -54,6 +60,12 @@ class CompiledMotd(document: JsonObject, private val alignments: List<String>) {
5460
1
5561
else 0)
5662
}
63+
else if (node is ObjectComponent && node.contents() is SpriteObjectContents)
64+
width +=
65+
8 +
66+
if (style.decoration(TextDecoration.BOLD) == TextDecoration.State.TRUE)
67+
1
68+
else 0
5769
node.children().forEach { measure(it, style) }
5870
}
5971
measure(line, Style.empty())
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package gg.grounds.proxy.velocity.motd
2+
3+
import net.kyori.adventure.text.Component
4+
import net.kyori.adventure.text.ObjectComponent
5+
import net.kyori.adventure.text.`object`.SpriteObjectContents
6+
7+
/** Omit unsupported atlas objects without discarding neighboring children or inherited style. */
8+
internal fun projectNativeSprites(node: Component, supported: Boolean): Component {
9+
if (supported) return node
10+
val children = node.children().map { projectNativeSprites(it, false) }
11+
return if (node is ObjectComponent && node.contents() is SpriteObjectContents)
12+
Component.empty().style(node.style()).children(children)
13+
else node.children(children)
14+
}

‎velocity/src/main/kotlin/gg/grounds/proxy/velocity/motd/ServerListEvaluator.kt‎

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -38,19 +38,29 @@ object ServerListEvaluator {
3838
)
3939
if (compiledMotd != null)
4040
builder.description(
41-
compiledMotd.render(values, if (clientProtocol in 774..777) 267 else 271)
41+
compiledMotd.render(
42+
values,
43+
if (clientProtocol in 774..777) 267 else 271,
44+
clientProtocol >= 773,
45+
)
46+
)
47+
else if (compiledFallback != null)
48+
builder.description(
49+
projectNativeSprites(compiledFallback.render(values), clientProtocol >= 773)
4250
)
43-
else if (compiledFallback != null) builder.description(compiledFallback.render(values))
4451
else
4552
fallbackText?.let {
4653
builder.description(
47-
MiniMessage.miniMessage()
48-
.deserialize(
49-
MotdPlaceholders.render(
50-
it,
51-
MotdPlaceholders.Context(region, continent, players, max),
52-
)
53-
)
54+
projectNativeSprites(
55+
MiniMessage.miniMessage()
56+
.deserialize(
57+
MotdPlaceholders.render(
58+
it,
59+
MotdPlaceholders.Context(region, continent, players, max),
60+
)
61+
),
62+
clientProtocol >= 773,
63+
)
5464
)
5565
}
5666
template?.let {

‎velocity/src/main/kotlin/gg/grounds/proxy/velocity/motd/ServerListTemplate.kt‎

Lines changed: 48 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,18 @@ class CompiledServerText private constructor(private val source: String) {
142142
return when (n.get("type").asString) {
143143
"text" -> escape(n.get("value").asString)
144144
"newline" -> "<newline>"
145+
"sprite" -> {
146+
val atlas = n.get("atlas").asString
147+
val sprite = n.get("sprite").asString
148+
for (id in listOf(atlas, sprite)) require(
149+
id.length <= 256 &&
150+
Regex("[a-z0-9_.-]+:[a-z0-9_./-]+").matches(id) &&
151+
!id.contains("//") &&
152+
!id.substringAfter(':').startsWith('/') &&
153+
id.substringAfter(':').split('/').none { it == "." || it == ".." }
154+
)
155+
"<sprite:\"$atlas\":\"$sprite\">"
156+
}
145157
"placeholder" -> "{{${n.get("name").asString}}}"
146158
"opaque" ->
147159
when (n.get("format").asString) {
@@ -165,6 +177,10 @@ class CompiledServerText private constructor(private val source: String) {
165177
node(it.asJsonObject, depth + 1)
166178
}
167179
style.get("color")?.asString?.let { text = "<$it>$text</$it>" }
180+
style.get("shadowColor")?.asLong?.let {
181+
val argb = (it and 0xffffffffL).toString(16).padStart(8, '0')
182+
text = "<shadow:#${argb.drop(2)}${argb.take(2)}>$text</shadow>"
183+
}
168184
style.getAsJsonArray("gradient")?.let { stops ->
169185
require(stops.size() >= 2)
170186
val colors =
@@ -182,7 +198,7 @@ class CompiledServerText private constructor(private val source: String) {
182198
val rendered = MM.deserialize(text)
183199
val flat =
184200
mutableListOf<
185-
Pair<String, net.kyori.adventure.text.format.Style>
201+
Pair<Component, net.kyori.adventure.text.format.Style>
186202
>()
187203
fun flatten(
188204
c: Component,
@@ -197,20 +213,31 @@ class CompiledServerText private constructor(private val source: String) {
197213
)
198214
if (c is net.kyori.adventure.text.TextComponent)
199215
c.content().codePoints().forEach {
200-
flat.add(String(Character.toChars(it)) to effective)
216+
flat.add(
217+
Component.text(String(Character.toChars(it))) to
218+
effective
219+
)
201220
}
221+
else flat.add(c.children(emptyList()) to effective)
202222
c.children().forEach { flatten(it, effective) }
203223
}
204224
flatten(rendered, net.kyori.adventure.text.format.Style.empty())
205-
val visible = flat.count { it.first != "\n" }
225+
val visible =
226+
flat.count {
227+
(it.first as? net.kyori.adventure.text.TextComponent)
228+
?.content() != "\n"
229+
}
206230
var index = 0
207231
text =
208232
MM.serialize(
209233
flat.fold(Component.empty() as Component) {
210234
acc,
211-
(char, oldStyle) ->
212-
if (char == "\n")
213-
acc.append(Component.text(char).style(oldStyle))
235+
(part, oldStyle) ->
236+
if (
237+
part is net.kyori.adventure.text.TextComponent &&
238+
part.content() == "\n"
239+
)
240+
acc.append(part.style(oldStyle))
214241
else {
215242
val t =
216243
if (visible <= 1) 0.0
@@ -256,18 +283,22 @@ class CompiledServerText private constructor(private val source: String) {
256283
channel(0),
257284
)
258285
acc.append(
259-
Component.text(char)
260-
.style(
261-
if (
262-
oldStyle.color() == null ||
263-
oldStyle
264-
.color()
265-
?.asHexString() ==
266-
style.get("color")?.asString
267-
)
268-
oldStyle.color(color)
269-
else oldStyle
286+
part.style(
287+
if (
288+
oldStyle.color() == null ||
289+
oldStyle
290+
.color()
291+
?.asHexString()
292+
?.equals(
293+
style
294+
.get("color")
295+
?.asString,
296+
ignoreCase = true,
297+
) == true
270298
)
299+
oldStyle.color(color)
300+
else oldStyle
301+
)
271302
)
272303
}
273304
}
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
package gg.grounds.proxy.velocity.motd
2+
3+
import com.google.gson.JsonParser
4+
import com.velocitypowered.api.proxy.server.ServerPing
5+
import net.kyori.adventure.text.Component
6+
import net.kyori.adventure.text.ObjectComponent
7+
import net.kyori.adventure.text.TextComponent
8+
import net.kyori.adventure.text.format.Style
9+
import net.kyori.adventure.text.format.TextDecoration
10+
import net.kyori.adventure.text.`object`.SpriteObjectContents
11+
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer
12+
import org.junit.jupiter.api.Assertions.*
13+
import org.junit.jupiter.api.Test
14+
15+
class NativeMotdSpriteTest {
16+
private val document =
17+
JsonParser.parseString(
18+
"""{"nodes":[{"type":"group","style":{"color":"#ffffff","shadowColor":0},"children":[{"type":"text","value":"A"},{"type":"sprite","atlas":"minecraft:gui","sprite":"minecraft:icon/trial_available"},{"type":"text","value":"B"}]}]}"""
19+
)
20+
.asJsonObject
21+
22+
private fun sprites(node: Component): List<ObjectComponent> =
23+
(if (node is ObjectComponent) listOf(node) else emptyList()) +
24+
node.children().flatMap(::sprites)
25+
26+
@Test
27+
fun `typed source compiles to native sprite and preserves transparent shadow`() {
28+
val result = CompiledServerText(document).render(emptyMap())
29+
val sprite = sprites(result).single()
30+
assertTrue(sprite.contents() is SpriteObjectContents)
31+
fun shadow(c: Component, inherited: Style): Int? {
32+
val style = c.style().merge(inherited, Style.Merge.Strategy.IF_ABSENT_ON_TARGET)
33+
return if (c is ObjectComponent) style.shadowColor()?.value()
34+
else c.children().firstNotNullOfOrNull { shadow(it, style) }
35+
}
36+
assertEquals(0, shadow(result, Style.empty()))
37+
assertEquals(
38+
"minecraft:icon/trial_available",
39+
(sprite.contents() as SpriteObjectContents).sprite().asString(),
40+
)
41+
}
42+
43+
@Test
44+
fun `native sprite width participates in center alignment`() {
45+
val result = CompiledMotd(document, listOf("center")).render(emptyMap(), 100)
46+
var prefix = 0
47+
fun walk(c: Component, inherited: Style) {
48+
val style = c.style().merge(inherited, Style.Merge.Strategy.IF_ABSENT_ON_TARGET)
49+
if (c is TextComponent)
50+
for (char in c.content()) if (char == ' ')
51+
prefix +=
52+
if (style.decoration(TextDecoration.BOLD) == TextDecoration.State.TRUE) 5
53+
else 4
54+
c.children().forEach { walk(it, style) }
55+
}
56+
walk(result, Style.empty())
57+
assertEquals(40, prefix)
58+
assertEquals(1, sprites(result).size)
59+
}
60+
61+
@Test
62+
fun `older protocol omits sprites while keeping adjacent content and network counts`() {
63+
val template =
64+
ServerListTemplate.parse(
65+
JsonParser.parseString(
66+
"""{"schemaVersion":1,"motd":{"text":$document,"alignments":["left"]},"version":{"mode":"automatic"},"icon":null,"players":{"hidden":false,"online":{"mode":"inherit"},"maximum":{"mode":"inherit"}},"hover":{"mode":"inherit"}}"""
67+
)
68+
.asJsonObject
69+
)
70+
val base =
71+
ServerPing.builder()
72+
.version(ServerPing.Version(777, "26.3"))
73+
.description(Component.empty())
74+
.onlinePlayers(1)
75+
.maximumPlayers(100)
76+
.build()
77+
for ((protocol, count) in listOf(767 to 17, 777 to 29)) {
78+
val result =
79+
ServerListEvaluator.evaluate(
80+
base,
81+
template,
82+
count,
83+
protocol,
84+
null,
85+
"eu",
86+
"Europe",
87+
compiledMotd = template.motd,
88+
)
89+
assertEquals(if (protocol == 777) 1 else 0, sprites(result.descriptionComponent!!).size)
90+
assertEquals(count, result.players.get().online)
91+
fun literal(c: Component): String =
92+
(if (c is TextComponent) c.content() else "") +
93+
c.children().joinToString("") { literal(it) }
94+
assertEquals("AB", literal(result.descriptionComponent!!))
95+
if (protocol < 773)
96+
assertEquals(
97+
"AB",
98+
PlainTextComponentSerializer.plainText()
99+
.serialize(result.descriptionComponent!!),
100+
)
101+
}
102+
}
103+
104+
@Test
105+
fun `uneven gradients retain and tint native sprite objects`() {
106+
val copy = document.deepCopy()
107+
copy
108+
.getAsJsonArray("nodes")[0]
109+
.asJsonObject
110+
.getAsJsonObject("style")
111+
.add(
112+
"gradient",
113+
JsonParser.parseString(
114+
"""[{"color":"#ff0000","position":0},{"color":"#00ff00","position":0.2},{"color":"#0000ff","position":1}]"""
115+
),
116+
)
117+
val result = CompiledServerText(copy).render(emptyMap())
118+
assertEquals(1, sprites(result).size)
119+
fun color(c: Component, inherited: Style): String? {
120+
val style = c.style().merge(inherited, Style.Merge.Strategy.IF_ABSENT_ON_TARGET)
121+
return if (c is ObjectComponent) style.color()?.asHexString()?.lowercase()
122+
else c.children().firstNotNullOfOrNull { color(it, style) }
123+
}
124+
assertEquals("#009f60", color(result, Style.empty()))
125+
}
126+
}

0 commit comments

Comments
 (0)