Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/main/java/net/tfminecraft/cooking/Cooking.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import net.tfminecraft.cooking.crops.CropGrowthListener;
import net.tfminecraft.cooking.crops.CropsLoader;
import net.tfminecraft.cooking.husbandry.HusbandryLoader;
import net.tfminecraft.cooking.husbandry.HusbandryLocator;
import net.tfminecraft.cooking.husbandry.HusbandryRepository;
import net.tfminecraft.cooking.husbandry.HusbandryTickTask;
import net.tfminecraft.cooking.loader.PermissionEffectsLoader;
Expand Down Expand Up @@ -151,6 +152,7 @@ public void onEnable() {
NutritionDrainTask.start();
HusbandryLifecycleListener.resumeLoadedWorlds();
HusbandryTickTask.start();
HusbandryLocator.scanUnloaded();
});

getCommand("cooking").setExecutor(commands);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ public boolean onCommand(CommandSender sender, Command command, String label, St
rows.add(new HusbandryOwned(animal, owned.role()));
}
for (Component line : HusbandryRoster.render(
ownerName, self, rows, HusbandryConfig.maxAnimals(), System.currentTimeMillis())) {
ownerName, self, rows, HusbandryConfig.maxAnimals(), System.currentTimeMillis(),
HusbandryLocator::isMissing)) {
sender.sendMessage(line);
}
return true;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,262 @@
package net.tfminecraft.cooking.husbandry;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;

/**
* Reads saved entity chunks ({@code entities/r.X.Z.mca}) to find where unloaded animals are.
* Runs off the main thread; it only reads files.
*/
final class HusbandryEntityScan {

record WorldDir(String world, File entities) {}

record Found(String world, int x, int y, int z) {}

/** {@code complete} is false when some chunk could not be read, so a missing animal may still exist. */
record Result(Map<UUID, Found> found, boolean complete) {}

private static final Pattern REGION = Pattern.compile("r\\.(-?\\d{1,7})\\.(-?\\d{1,7})\\.mca");
private static final int SECTOR = 4096;
private static final int MAX_CHUNK_BYTES = 32 * 1024 * 1024;
private static final int MAX_REGION_BYTES = 256 * 1024 * 1024;

private HusbandryEntityScan() {}

static Result scan(List<WorldDir> worlds, Set<UUID> targets) {
Map<UUID, Found> found = new HashMap<>();
boolean complete = true;
if (targets.isEmpty()) {
return new Result(found, true);
}
for (WorldDir world : worlds) {
if (!world.entities().exists()) {
continue;
}
File[] files = world.entities().listFiles();
if (files == null) {
complete = false;
continue;
}
for (File file : files) {
Matcher name = REGION.matcher(file.getName());
if (!name.matches()) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
continue;
}
int regionX = Integer.parseInt(name.group(1));
int regionZ = Integer.parseInt(name.group(2));
complete &= scanRegion(world, file, regionX, regionZ, targets, found);
}
}
return new Result(found, complete);
}

private static boolean scanRegion(
WorldDir world, File file, int regionX, int regionZ, Set<UUID> targets, Map<UUID, Found> found) {
byte[] data;
try {
data = readBounded(file, MAX_REGION_BYTES);
} catch (IOException ex) {
return false;
}
if (data.length == 0) {
return true;
}
if (data.length < SECTOR * 2) {
return false;
}
boolean complete = true;
for (int index = 0; index < 1024; index++) {
int entry = readInt(data, index * 4);
long sectorOffset = (long) (entry >>> 8) * SECTOR;
if (sectorOffset == 0) {
continue;
}
if (sectorOffset + 5 > data.length) {
complete = false;
continue;
}
int offset = (int) sectorOffset;
try {
byte[] chunk = chunkBytes(world, data, offset, regionX * 32 + index % 32, regionZ * 32 + index / 32);
if (chunk == null) {
complete = false;
continue;
}
readEntityChunk(new DataInputStream(new ByteArrayInputStream(chunk)), world.world(), targets, found);
} catch (IOException | RuntimeException ex) {
complete = false;
}
}
return complete;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

private static byte[] chunkBytes(WorldDir world, byte[] data, int offset, int chunkX, int chunkZ)
throws IOException {
int length = readInt(data, offset);
int compression = data[offset + 4] & 0xFF;
byte[] raw;
if ((compression & 0x80) != 0) {
compression &= 0x7F;
raw = readBounded(new File(world.entities(), "c." + chunkX + "." + chunkZ + ".mcc"), MAX_CHUNK_BYTES);
} else {
if (length < 1 || (long) offset + 4 + length > data.length) {
return null;
}
raw = new byte[length - 1];
System.arraycopy(data, offset + 5, raw, 0, raw.length);
}
InputStream in = switch (compression) {
case 1 -> new GZIPInputStream(new ByteArrayInputStream(raw));
case 2 -> new InflaterInputStream(new ByteArrayInputStream(raw));
case 3 -> new ByteArrayInputStream(raw);
default -> null;
};
if (in == null) {
return null;
}
try (in) {
byte[] chunk = in.readNBytes(MAX_CHUNK_BYTES + 1);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
if (chunk.length > MAX_CHUNK_BYTES) {
throw new IOException("Entity chunk larger than " + MAX_CHUNK_BYTES + " bytes");
}
return chunk;
}
}

private static byte[] readBounded(File file, int max) throws IOException {
try (InputStream in = Files.newInputStream(file.toPath())) {
byte[] data = in.readNBytes(max + 1);
if (data.length > max) {
throw new IOException(file.getName() + " is larger than " + max + " bytes");
}
return data;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

private static int readInt(byte[] data, int at) {
return ((data[at] & 0xFF) << 24) | ((data[at + 1] & 0xFF) << 16)
| ((data[at + 2] & 0xFF) << 8) | (data[at + 3] & 0xFF);
}

// ----------------------------------------------------------------------
// NBT: only Entities[].UUID, Pos and Passengers are read, the rest is skipped
// ----------------------------------------------------------------------

private static final byte END = 0;
private static final byte DOUBLE = 6;
private static final byte LIST = 9;
private static final byte COMPOUND = 10;
private static final byte INT_ARRAY = 11;

private static void readEntityChunk(DataInputStream in, String world, Set<UUID> targets, Map<UUID, Found> found)
throws IOException {
if (in.readByte() != COMPOUND) {
return;
}
in.readUTF();
byte type;
while ((type = in.readByte()) != END) {
String key = in.readUTF();
if (type == LIST && key.equals("Entities")) {
readEntityList(in, world, targets, found);
} else {
skip(in, type);
}
}
}

private static void readEntityList(DataInputStream in, String world, Set<UUID> targets, Map<UUID, Found> found)
throws IOException {
byte element = in.readByte();
int size = in.readInt();
if (element != COMPOUND) {
for (int i = 0; i < size; i++) {
skip(in, element);
}
return;
}
for (int i = 0; i < size; i++) {
readEntity(in, world, targets, found);
}
}

private static void readEntity(DataInputStream in, String world, Set<UUID> targets, Map<UUID, Found> found)
throws IOException {
UUID uuid = null;
double[] pos = null;
byte type;
while ((type = in.readByte()) != END) {
String key = in.readUTF();
if (type == INT_ARRAY && key.equals("UUID")) {
int size = in.readInt();
if (size == 4) {
uuid = new UUID(
((long) in.readInt() << 32) | (in.readInt() & 0xFFFFFFFFL),
((long) in.readInt() << 32) | (in.readInt() & 0xFFFFFFFFL));
} else {
in.skipNBytes(4L * size);
}
} else if (type == LIST && key.equals("Pos")) {
byte element = in.readByte();
int size = in.readInt();
if (element == DOUBLE && size == 3) {
pos = new double[] {in.readDouble(), in.readDouble(), in.readDouble()};
} else {
for (int i = 0; i < size; i++) {
skip(in, element);
}
}
} else if (type == LIST && key.equals("Passengers")) {
readEntityList(in, world, targets, found);
} else {
skip(in, type);
}
}
if (uuid != null && pos != null && targets.contains(uuid)) {
found.putIfAbsent(uuid, new Found(
world, (int) Math.floor(pos[0]), (int) Math.floor(pos[1]), (int) Math.floor(pos[2])));
}
}

private static void skip(DataInputStream in, byte type) throws IOException {
switch (type) {
case 1 -> in.skipNBytes(1);
case 2 -> in.skipNBytes(2);
case 3, 5 -> in.skipNBytes(4);
case 4, 6 -> in.skipNBytes(8);
case 7 -> in.skipNBytes(in.readInt());
case 8 -> in.skipNBytes(in.readUnsignedShort());
case 9 -> {
byte element = in.readByte();
int size = in.readInt();
for (int i = 0; i < size; i++) {
skip(in, element);
}
}
case 10 -> {
byte inner;
while ((inner = in.readByte()) != END) {
in.skipNBytes(in.readUnsignedShort());
skip(in, inner);
}
}
case 11 -> in.skipNBytes(4L * in.readInt());
case 12 -> in.skipNBytes(8L * in.readInt());
default -> throw new IOException("Unknown NBT tag " + type);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ static void handleLoad(Entity entity) {
HusbandryAnimal animal = stored.get();
long now = System.currentTimeMillis();
HusbandryLocation.remember(animal, living);
HusbandryLocator.markFound(uuid);
HusbandrySimulator.catchUp(animal, now, java.util.concurrent.ThreadLocalRandom.current());
HusbandryGrowth.applyMaturity(living, animal, now);
HusbandryMounts.applyStats(living, animal);
Expand Down
Loading