|
| 1 | +package me.hsgamer.bettergui.util; |
| 2 | + |
| 3 | +import me.hsgamer.hscore.common.Validate; |
| 4 | +import me.hsgamer.hscore.minecraft.gui.GUIProperties; |
| 5 | + |
| 6 | +import java.util.Locale; |
| 7 | +import java.util.Optional; |
| 8 | +import java.util.function.Function; |
| 9 | + |
| 10 | +/** |
| 11 | + * The utility class for ticks and milliseconds |
| 12 | + */ |
| 13 | +public class TickUtil { |
| 14 | + /** |
| 15 | + * Convert ticks to milliseconds |
| 16 | + * |
| 17 | + * @param ticks the ticks |
| 18 | + * |
| 19 | + * @return the milliseconds |
| 20 | + */ |
| 21 | + public static long ticksToMillis(long ticks) { |
| 22 | + return ticks * GUIProperties.getMillisPerTick(); |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * Convert FPS (Frame-per-second) to milliseconds |
| 27 | + * |
| 28 | + * @param fps the FPS |
| 29 | + * |
| 30 | + * @return the milliseconds |
| 31 | + */ |
| 32 | + public static long fpsToMillis(double fps) { |
| 33 | + return (long) (1000L / fps); |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Get the milliseconds from the input. |
| 38 | + * The input can be: |
| 39 | + * - A number (in ticks) |
| 40 | + * - A number with "t" at the end (in ticks) |
| 41 | + * - A number with "ms" at the end (in milliseconds) |
| 42 | + * - A number with "fps" at the end (in FPS) |
| 43 | + * |
| 44 | + * @param input the input |
| 45 | + * |
| 46 | + * @return the milliseconds |
| 47 | + */ |
| 48 | + public static Optional<Long> toMillis(String input) { |
| 49 | + String lowerCase = input.toLowerCase(Locale.ROOT); |
| 50 | + |
| 51 | + String number; |
| 52 | + Function<Number, Long> function; |
| 53 | + if (lowerCase.endsWith("t")) { |
| 54 | + number = input.substring(0, input.length() - 1); |
| 55 | + function = n -> ticksToMillis(n.longValue()); |
| 56 | + } else if (lowerCase.endsWith("ms")) { |
| 57 | + number = input.substring(0, input.length() - 2); |
| 58 | + function = Number::longValue; |
| 59 | + } else if (lowerCase.endsWith("fps")) { |
| 60 | + number = input.substring(0, input.length() - 3); |
| 61 | + function = n -> fpsToMillis(n.doubleValue()); |
| 62 | + } else { |
| 63 | + number = input; |
| 64 | + function = n -> ticksToMillis(n.longValue()); |
| 65 | + } |
| 66 | + |
| 67 | + return Validate.getNumber(number).map(function); |
| 68 | + } |
| 69 | +} |
0 commit comments