-
Notifications
You must be signed in to change notification settings - Fork 95
/
ColorLoadable.java
89 lines (79 loc) · 2.45 KB
/
ColorLoadable.java
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
86
87
88
89
package slimeknights.mantle.data.loadable.common;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSyntaxException;
import lombok.RequiredArgsConstructor;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.util.GsonHelper;
import slimeknights.mantle.data.loadable.Loadable;
/** Loadable to fetch colors from JSON */
@RequiredArgsConstructor
public enum ColorLoadable implements Loadable<Integer> {
ALPHA {
@Override
public int parseColor(String color) {
// two options, 6 character or 8 character, must not start with - sign
if (color.charAt(0) != '-') {
try {
// length of 8 must parse as long, supports transparency
int length = color.length();
if (length == 8) {
return (int)Long.parseLong(color, 16);
}
if (length == 6) {
return 0xFF000000 | Integer.parseInt(color, 16);
}
} catch (NumberFormatException ex) {
// NO-OP
}
}
throw new JsonSyntaxException("Invalid color '" + color + "'");
}
@Override
public String colorString(int color) {
return String.format("%08X", color);
}
},
NO_ALPHA {
@Override
public int parseColor(String color) {
// only consider 6 digits with no alpha, will force to full alpha
if (color.charAt(0) != '-' && color.length() == 6) {
try {
return 0xFF000000 | Integer.parseInt(color, 16);
} catch (NumberFormatException ex) {
// NO-OP
}
}
throw new JsonSyntaxException("Invalid color '" + color + "'");
}
@Override
public String colorString(int color) {
return String.format("%06X", color & 0xFFFFFF);
}
};
/**
* Parses the color from the given string
* @param color Color string
* @return Color value
*/
public abstract int parseColor(String color);
/** Writes the given color as a string */
public abstract String colorString(int color);
@Override
public Integer convert(JsonElement element, String key) {
return parseColor(GsonHelper.convertToString(element, key));
}
@Override
public JsonElement serialize(Integer color) {
return new JsonPrimitive(colorString(color));
}
@Override
public Integer fromNetwork(FriendlyByteBuf buffer) {
return buffer.readInt();
}
@Override
public void toNetwork(Integer color, FriendlyByteBuf buffer) {
buffer.writeInt(color);
}
}