Utils.java 8.15 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
package emu.grasscutter.utils;

KingRainbow44's avatar
KingRainbow44 committed
3
4
5
import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
Kengxxiao's avatar
Kengxxiao committed
6
7
import java.time.*;
import java.time.temporal.TemporalAdjusters;
Melledy's avatar
Melledy committed
8
9
import java.util.Random;

KingRainbow44's avatar
KingRainbow44 committed
10
import emu.grasscutter.Config;
Melledy's avatar
Melledy committed
11
12
13
14
import emu.grasscutter.Grasscutter;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
Melledy's avatar
Melledy committed
15

KingRainbow44's avatar
KingRainbow44 committed
16
import org.slf4j.Logger;
Melledy's avatar
Melledy committed
17

18
19
import static emu.grasscutter.utils.Language.translate;

KingRainbow44's avatar
KingRainbow44 committed
20
21
@SuppressWarnings({"UnusedReturnValue", "BooleanMethodIsAlwaysInverted"})
public final class Utils {
Melledy's avatar
Melledy committed
22
23
24
25
26
27
28
29
30
31
	public static final Random random = new Random();
	
	public static int randomRange(int min, int max) {
		return random.nextInt(max - min + 1) + min;
	}
	
	public static float randomFloatRange(float min, float max) {
		return random.nextFloat() * (max - min) + min;
	}
	
Melledy's avatar
Melledy committed
32
33
34
35
36
37
38
39
40
41
42
43
44
	public static double getDist(Position pos1, Position pos2) {
		double xs = pos1.getX() - pos2.getX();
		xs = xs * xs;
		
		double ys = pos1.getY() - pos2.getY();
		ys = ys * ys;

		double zs = pos1.getZ() - pos2.getZ();
		zs = zs * zs;

		return Math.sqrt(xs + zs + ys);
	}

Melledy's avatar
Melledy committed
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
	public static int getCurrentSeconds() {
		return (int) (System.currentTimeMillis() / 1000.0);
	}
	
	public static String lowerCaseFirstChar(String s) {
		StringBuilder sb = new StringBuilder(s);
		sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
		return sb.toString();
	}
	
	public static String toString(InputStream inputStream) throws IOException {
		BufferedInputStream bis = new BufferedInputStream(inputStream);
		ByteArrayOutputStream buf = new ByteArrayOutputStream();
		for (int result = bis.read(); result != -1; result = bis.read()) {
		    buf.write((byte) result);
		}
		return buf.toString();
	}
	
	public static void logByteArray(byte[] array) {
		ByteBuf b = Unpooled.wrappedBuffer(array);
		Grasscutter.getLogger().info("\n" + ByteBufUtil.prettyHexDump(b));
		b.release();
	}
	
	private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();
	public static String bytesToHex(byte[] bytes) {
Melledy's avatar
Melledy committed
72
		if (bytes == null) return "";
Melledy's avatar
Melledy committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
	    char[] hexChars = new char[bytes.length * 2];
	    for (int j = 0; j < bytes.length; j++) {
	        int v = bytes[j] & 0xFF;
	        hexChars[j * 2] = HEX_ARRAY[v >>> 4];
	        hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
	    }
	    return new String(hexChars);
	}
	
	public static String bytesToHex(ByteBuf buf) {
	    return bytesToHex(byteBufToArray(buf));
	}
	
	public static byte[] byteBufToArray(ByteBuf buf) {
		byte[] bytes = new byte[buf.capacity()];
		buf.getBytes(0, bytes);
		return bytes;
	}
	
	public static int abilityHash(String str) {
		int v7 = 0;
		int v8 = 0;
	    while (v8 < str.length()) {
	    	v7 = str.charAt(v8++) + 131 * v7;
	    }
	    return v7;
	}
KingRainbow44's avatar
KingRainbow44 committed
100

Melledy's avatar
Melledy committed
101
102
103
104
105
106
107
108
109
	/**
	 * Creates a string with the path to a file.
	 * @param path The path to the file.
	 * @return A path using the operating system's file separator.
	 */
	public static String toFilePath(String path) {
		return path.replace("/", File.separator);
	}

KingRainbow44's avatar
KingRainbow44 committed
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
	/**
	 * Checks if a file exists on the file system.
	 * @param path The path to the file.
	 * @return True if the file exists, false otherwise.
	 */
	public static boolean fileExists(String path) {
		return new File(path).exists();
	}

	/**
	 * Creates a folder on the file system.
	 * @param path The path to the folder.
	 * @return True if the folder was created, false otherwise.
	 */
	public static boolean createFolder(String path) {
		return new File(path).mkdirs();
	}

	/**
	 * Copies a file from the archive's resources to the file system.
	 * @param resource The path to the resource.
	 * @param destination The path to copy the resource to.
	 * @return True if the file was copied, false otherwise.
	 */
	public static boolean copyFromResources(String resource, String destination) {
		try (InputStream stream = Grasscutter.class.getResourceAsStream(resource)) {
			if(stream == null) {
				Grasscutter.getLogger().warn("Could not find resource: " + resource);
				return false;
			}

			Files.copy(stream, new File(destination).toPath(), StandardCopyOption.REPLACE_EXISTING);
			return true;
		} catch (Exception e) {
			Grasscutter.getLogger().warn("Unable to copy resource " + resource + " to " + destination, e);
			return false;
		}
	}

Melledy's avatar
Melledy committed
149
150
151
152
153
154
155
156
157
158
	/**
	 * Get object with null fallback.
	 * @param nonNull The object to return if not null.
	 * @param fallback The object to return if null.
	 * @return One of the two provided objects.
	 */
	public static <T> T requireNonNullElseGet(T nonNull, T fallback) {
		return nonNull != null ? nonNull : fallback;
	}

KingRainbow44's avatar
KingRainbow44 committed
159
160
161
162
163
164
165
166
167
	/**
	 * Logs an object to the console.
	 * @param object The object to log.
	 */
	public static void logObject(Object object) {
		String asJson = Grasscutter.getGsonFactory().toJson(object);
		Grasscutter.getLogger().info(asJson);
	}
	
KingRainbow44's avatar
KingRainbow44 committed
168
169
170
171
172
173
174
175
176
177
178
179
180
	/**
	 * Checks for required files and folders before startup.
	 */
	public static void startupCheck() {
		Config config = Grasscutter.getConfig();
		Logger logger = Grasscutter.getLogger();
		boolean exit = false;

		String resourcesFolder = config.RESOURCE_FOLDER;
		String dataFolder = config.DATA_FOLDER;

		// Check for resources folder.
		if(!fileExists(resourcesFolder)) {
181
182
			logger.info(translate("messages.status.create_resources"));
			logger.info(translate("messages.status.resources_error"));
KingRainbow44's avatar
KingRainbow44 committed
183
184
185
			createFolder(resourcesFolder); exit = true;
		}

186
		// Check for BinOutput + ExcelBinOutput.
KingRainbow44's avatar
KingRainbow44 committed
187
188
		if(!fileExists(resourcesFolder + "BinOutput") ||
				!fileExists(resourcesFolder + "ExcelBinOutput")) {
189
			logger.info(translate("messages.status.resources_error"));
KingRainbow44's avatar
KingRainbow44 committed
190
191
192
193
194
195
196
197
198
			exit = true;
		}

		// Check for game data.
		if(!fileExists(dataFolder))
			createFolder(dataFolder);

		if(exit) System.exit(1);
	}
Kengxxiao's avatar
Kengxxiao committed
199

200
201
202
203
204
	/**
	 * Gets the timestamp of the next hour.
	 * @return The timestamp in UNIX seconds.
	 */
	public static int getNextTimestampOfThisHour(int hour, String timeZone, int param) {
Kengxxiao's avatar
Kengxxiao committed
205
206
207
208
209
210
211
212
		ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone));
		for (int i = 0; i < param; i ++){
			if (zonedDateTime.getHour() < hour) {
				zonedDateTime = zonedDateTime.withHour(hour).withMinute(0).withSecond(0);
			} else {
				zonedDateTime = zonedDateTime.plusDays(1).withHour(hour).withMinute(0).withSecond(0);
			}
		}
213
		return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
Kengxxiao's avatar
Kengxxiao committed
214
215
	}

216
217
218
219
220
	/**
	 * Gets the timestamp of the next hour in a week.
	 * @return The timestamp in UNIX seconds.
	 */
	public static int getNextTimestampOfThisHourInNextWeek(int hour, String timeZone, int param) {
Kengxxiao's avatar
Kengxxiao committed
221
222
223
224
225
226
227
228
		ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone));
		for (int i = 0; i < param; i++) {
			if (zonedDateTime.getDayOfWeek() == DayOfWeek.MONDAY && zonedDateTime.getHour() < hour) {
				zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone)).withHour(hour).withMinute(0).withSecond(0);
			} else {
				zonedDateTime = zonedDateTime.with(TemporalAdjusters.next(DayOfWeek.MONDAY)).withHour(hour).withMinute(0).withSecond(0);
			}
		}
229
		return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
Kengxxiao's avatar
Kengxxiao committed
230
231
	}

232
233
234
235
236
	/**
	 * Gets the timestamp of the next hour in a month.
	 * @return The timestamp in UNIX seconds.
	 */
	public static int getNextTimestampOfThisHourInNextMonth(int hour, String timeZone, int param) {
Kengxxiao's avatar
Kengxxiao committed
237
238
239
240
241
242
243
244
		ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone));
		for (int i = 0; i < param; i++) {
			if (zonedDateTime.getDayOfMonth() == 1 && zonedDateTime.getHour() < hour) {
				zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone)).withHour(hour).withMinute(0).withSecond(0);
			} else {
				zonedDateTime = zonedDateTime.with(TemporalAdjusters.firstDayOfNextMonth()).withHour(hour).withMinute(0).withSecond(0);
			}
		}
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
		return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
	}

	/**
	 * Retrieves a string from an input stream.
	 * @param stream The input stream.
	 * @return The string.
	 */
	public static String readFromInputStream(InputStream stream) {
		StringBuilder stringBuilder = new StringBuilder();
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
			String line; while ((line = reader.readLine()) != null) {
				stringBuilder.append(line);
			} stream.close();
		} catch (IOException e) {
			Grasscutter.getLogger().warn("Failed to read from input stream.");
		} return stringBuilder.toString();
Kengxxiao's avatar
Kengxxiao committed
262
	}
Melledy's avatar
Melledy committed
263
}