Volver al índice
src/main/java/ar/com/companeros/world/BuildPlanTask.java
package ar.com.companeros.world;
import ar.com.companeros.action.ToolResult;
import com.google.gson.*;
import java.util.*;
import net.minecraft.core.*;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.item.*;
import net.minecraftforge.registries.ForgeRegistries;
/** El agente diseña las celdas; el servidor ejecuta una colocación física a la vez. */
public final class BuildPlanTask implements PlayerOperations.Operation {
private record Cell(BlockPos pos, Item item) { }
private final ServerPlayer player;
private final UUID invocation;
private final List<Cell> cells = new ArrayList<>();
private final Map<String, Integer> before;
private final long began = System.currentTimeMillis();
private long first = -1;
private int completed, alreadyPresent;
private PlaceTask current;
private ToolResult result;
// Formato compacto: [[dx,dy,dz,"namespace:item"],...], relativo al inicio de esta obra.
public BuildPlanTask(ServerPlayer player, UUID invocation, String plan) {
this(player, invocation, plan, player.blockPosition());
}
// El origen explícito permite retomar la misma obra aunque el jugador se haya movido.
public BuildPlanTask(ServerPlayer player, UUID invocation, String plan, BlockPos origin) {
this.player = player; this.invocation = invocation; before = PlayerCrafting.counts(player);
if (plan.length() > 4096) throw new IllegalArgumentException("Plano demasiado grande");
JsonArray array = JsonParser.parseString(plan).getAsJsonArray();
if (array.isEmpty() || array.size() > 64) throw new IllegalArgumentException("Plano de 1 a 64 colocaciones");
Set<BlockPos> unique = new HashSet<>();
for (JsonElement entry : array) {
JsonArray row = entry.getAsJsonArray(); if (row.size() != 4) throw new IllegalArgumentException("Celda inválida");
int[] offset = new int[3];
for (int axis = 0; axis < 3; axis++) {
double value = row.get(axis).getAsDouble();
if (!Double.isFinite(value) || value != Math.floor(value) || Math.abs(value) > 8)
throw new IllegalArgumentException("Desplazamiento de celda fuera de ±8");
offset[axis] = (int)value;
}
ResourceLocation id = ResourceLocation.tryParse(row.get(3).getAsString());
Item item = id == null ? null : ForgeRegistries.ITEMS.getValue(id);
if (!(item instanceof BlockItem)) throw new IllegalArgumentException("La celda requiere un bloque registrado");
BlockPos pos = origin.offset(offset[0], offset[1], offset[2]);
if (!unique.add(pos)) throw new IllegalArgumentException("Celda repetida");
cells.add(new Cell(pos, item));
}
}
public ToolResult tick(long tick) {
if (result != null) return result;
if (first < 0) first = tick;
if (!player.isAlive() || player.isRemoved()) return finish(ToolResult.Status.CANCELLED, ToolResult.Reason.CONDITIONS_CHANGED, "body_unavailable");
if (tick - first >= 4780) return finish(ToolResult.Status.BLOCKED, ToolResult.Reason.TIMEOUT, "build_interval_exhausted");
while (completed < cells.size()) {
Cell cell = cells.get(completed);
if (!PlayerOperations.loaded(player, cell.pos)) return finish(ToolResult.Status.BLOCKED, ToolResult.Reason.CONDITIONS_CHANGED, "unloaded=" + cell.pos.toShortString());
if (current == null && player.level().getBlockState(cell.pos).is(((BlockItem)cell.item).getBlock())) {
alreadyPresent++; completed++; continue;
}
if (current == null) current = new PlaceTask(player, invocation, cell.pos, cell.item);
ToolResult receipt = current.tick(tick);
if (!receipt.finished()) return report(ToolResult.Status.RUNNING, ToolResult.Reason.NONE, "placing=" + cell.pos.toShortString());
if (!receipt.succeeded()) return finish(receipt.status(), receipt.reason(), "blocked_cell=" + cell.pos.toShortString() + " evidence=" + receipt.actualEffects());
current = null; completed++; return report(ToolResult.Status.RUNNING, ToolResult.Reason.NONE, "placed=" + cell.pos.toShortString());
}
return finish(ToolResult.Status.SUCCEEDED, ToolResult.Reason.NONE, "requested_cells_complete");
}
private ToolResult finish(ToolResult.Status status, ToolResult.Reason reason, String evidence) {
if (result == null) { if (current != null) current.cancel(); result = report(status, reason, evidence); }
return result;
}
private ToolResult report(ToolResult.Status status, ToolResult.Reason reason, String evidence) {
return new ToolResult(invocation, status, reason, PlayerCrafting.delta(before, PlayerCrafting.counts(player)),
List.of("build_plan completed=" + completed + "/" + cells.size() + " previously_present=" + alreadyPresent + " " + evidence), List.of(),
GlobalPos.of(player.level().dimension(), player.blockPosition()), began, System.currentTimeMillis());
}
public void cancel() { finish(ToolResult.Status.CANCELLED, ToolResult.Reason.CANCELLED, "cancelled"); }
}