Skip to content

Commit

Permalink
It saves and loads! (And runs!!!)
Browse files Browse the repository at this point in the history
  • Loading branch information
Azzyypaaras committed Jan 2, 2025
1 parent fb48b1e commit f2ddccf
Show file tree
Hide file tree
Showing 6 changed files with 79 additions and 67 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public PastelNetwork joinOrCreateNetwork(PastelNodeBlockEntity node, UUID uuid)
for (int i = 0; i < this.networks.size(); i++) {
PastelNetwork network = this.networks.get(i);
if (network.getUUID().equals(uuid)) {
network.addNodeAndLoadMemory(node);
network.addNode(node);
foundNetwork = network;
} else {
if (network.removeNode(node, NodeRemovalReason.MOVED)) {
Expand All @@ -42,7 +42,7 @@ public PastelNetwork joinOrCreateNetwork(PastelNodeBlockEntity node, UUID uuid)
}

PastelNetwork network = createNetwork(node.getWorld(), uuid);
network.addNodeAndLoadMemory(node);
network.addNode(node);
return network;
}

Expand Down Expand Up @@ -97,7 +97,7 @@ public void removeNode(PastelNodeBlockEntity node, NodeRemovalReason reason) {
PastelNetwork network = node.getParentNetwork();
if (network != null) {
network.removeNode(node, reason);
if (network.loadedNodes.size() == 0) {
if (network.loadedNodes.isEmpty()) {
this.networks.remove(network);
}
}
Expand All @@ -113,23 +113,23 @@ public void renderLines(WorldRenderContext context) {
MinecraftClient client = MinecraftClient.getInstance();
for (PastelNetwork network : this.networks) {
if (network.getWorld().getDimension() != context.world().getDimension()) continue;
Graph<PastelNodeBlockEntity, DefaultEdge> graph = network.getGraph();
Graph<BlockPos, DefaultEdge> graph = network.getGraph();
int color = network.getColor();
float[] colors = PastelRenderHelper.unpackNormalizedColor(color);

for (DefaultEdge edge : graph.edgeSet()) {
PastelNodeBlockEntity source = graph.getEdgeSource(edge);
PastelNodeBlockEntity target = graph.getEdgeTarget(edge);
BlockPos source = graph.getEdgeSource(edge);
BlockPos target = graph.getEdgeTarget(edge);

final MatrixStack matrices = context.matrixStack();
final Vec3d pos = context.camera().getPos();
matrices.push();
matrices.translate(-pos.x, -pos.y, -pos.z);
PastelRenderHelper.renderLineTo(context.matrixStack(), context.consumers(), colors, source.getPos(), target.getPos());
PastelRenderHelper.renderLineTo(context.matrixStack(), context.consumers(), colors, source, target);
// PastelRenderHelper.renderLineTo(context.matrixStack(), context.consumers(), colors, target.getPos(), source.getPos());

if (client.options.debugEnabled) {
Vec3d offset = Vec3d.ofCenter(target.getPos()).subtract(Vec3d.of(source.getPos()));
Vec3d offset = Vec3d.ofCenter(target).subtract(Vec3d.of(source));
Vec3d normalized = offset.normalize();
Matrix4f positionMatrix = context.matrixStack().peek().getPositionMatrix();
PastelRenderHelper.renderDebugLine(context.consumers(), color, offset, normalized, positionMatrix);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,17 @@ public World getWorld() {
}

public void addNode(PastelNodeBlockEntity node) {
if (addNodeOrReturn(node))
return;

this.graph.addVertex(node.getPos());
//If this node already has a vertex, then all we are doing it is loading it
if (graph.containsVertex(node.getPos())) {
loadedNodes.get(node.getNodeType()).add(node);

}
else {
if (addNodeOrReturn(node))
return;

this.graph.addVertex(node.getPos());
}
addPriorityNode(node);
}

Expand All @@ -86,6 +93,11 @@ public void addNodeAndConnect(PastelNodeBlockEntity newNode, PastelNodeBlockEnti
// check for priority
addPriorityNode(newNode);
}

public void addEdge(PastelNodeBlockEntity node, PastelNodeBlockEntity parent) {
if (!hasEdge(node, parent))
graph.addEdge(node.getPos(), parent.getPos());
}

public void removeEdge(PastelNodeBlockEntity node, PastelNodeBlockEntity parent) {
graph.removeEdge(node.getPos(), parent.getPos());
Expand Down Expand Up @@ -124,8 +136,9 @@ protected boolean removeNode(PastelNodeBlockEntity node, NodeRemovalReason reaso
return false;
}

// delete the now removed node from this networks graph
graph.removeVertex(node.getPos());
// delete the now removed node from this networks graph - IF IT WASN'T UNLOADED
if (reason != NodeRemovalReason.UNLOADED)
graph.removeVertex(node.getPos());

removePriorityNode(node, node.getPriority());

Expand Down Expand Up @@ -254,6 +267,8 @@ public String getNodeDebugText() {

public NbtCompound toNbt() {
NbtCompound compound = new NbtCompound();
compound.putUuid("UUID", this.uuid);
compound.putString("World", this.getWorld().getRegistryKey().getValue().toString());

var vertices = new ArrayList<>(graph.vertexSet());
var graphStorage = new NbtCompound();
Expand Down Expand Up @@ -294,38 +309,27 @@ public NbtCompound toNbt() {
return compound;
}

public static PastelNetwork fromNbt(NbtCompound compound) {
World world = SpectrumCommon.minecraftServer.getWorld(RegistryKey.of(RegistryKeys.WORLD, Identifier.tryParse(compound.getString("World"))));
UUID uuid = compound.getUuid("UUID");

PastelNetwork network = new PastelNetwork(world, uuid);
public void fromNbt(NbtCompound compound) {
if (compound.contains("Graph")) {
var graphStorage = compound.getCompound("Graph");
var size = graphStorage.getInt("Size");
var vertices = IntStream.of(size)
.mapToObj(i -> BlockPos.fromLong(graphStorage.getLong("Vertex" + i)))
.toList();

vertices.forEach(network.graph::addVertex);
var vertices = new ArrayList<BlockPos>();
for (int i = 0; i < size; i++) {
var vertex = BlockPos.fromLong(graphStorage.getLong("Vertex" + i));
vertices.add(vertex);
graph.addVertex(vertex);
}

for (int i = 0; i < size; i++) {
var edgeIndexes = graphStorage.getIntArray("EdgeIndexes" + i);
var source = vertices.get(edgeIndexes[0]);
for (int targetIndex = 1; targetIndex < edgeIndexes.length; targetIndex++) {
var target = vertices.get(targetIndex);
if (!network.graph.containsEdge(source, target))
network.graph.addEdge(source, target);
if (!graph.containsEdge(source, target) && !source.equals(target))
graph.addEdge(source, target);
}
}
}

for (NbtElement e : compound.getList("Transmissions", NbtElement.COMPOUND_TYPE)) {
NbtCompound t = (NbtCompound) e;
int delay = t.getInt("Delay");
PastelTransmission transmission = PastelTransmission.fromNbt(t.getCompound("Transmission"));
network.addTransmission(transmission, delay);
}
return network;
}

public PastelNodeBlockEntity getNodeAt(BlockPos blockPos) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ default boolean tryAddEdge(PastelNodeBlockEntity node, PastelNodeBlockEntity oth
if (node == otherNode || node.getParentNetwork().hasEdge(node, otherNode))
return false;

node.getParentNetwork().addAndRememberEdge(node, otherNode);
node.getParentNetwork().addEdge(node, otherNode);
return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ private enum TransferMode {
public static final int DEFAULT_TRANSFER_TICKS_PER_NODE = 30;
private final ServerPastelNetwork network;

private DijkstraShortestPath<PastelNodeBlockEntity, DefaultEdge> dijkstra;
private Map<PastelNodeBlockEntity, Map<PastelNodeBlockEntity, GraphPath<PastelNodeBlockEntity, DefaultEdge>>> pathCache = new HashMap<>();
private DijkstraShortestPath<BlockPos, DefaultEdge> dijkstra;
private Map<BlockPos, Map<BlockPos, GraphPath<BlockPos, DefaultEdge>>> pathCache = new HashMap<>();


public PastelTransmissionLogic(ServerPastelNetwork network) {
Expand All @@ -41,28 +41,28 @@ public void invalidateCache() {
this.pathCache = new HashMap<>();
}

public @Nullable GraphPath<PastelNodeBlockEntity, DefaultEdge> getPath(Graph<PastelNodeBlockEntity, DefaultEdge> graph, PastelNodeBlockEntity source, PastelNodeBlockEntity destination) {
public @Nullable GraphPath<BlockPos, DefaultEdge> getPath(Graph<BlockPos, DefaultEdge> graph, PastelNodeBlockEntity source, PastelNodeBlockEntity destination) {
if (this.dijkstra == null) {
this.dijkstra = new DijkstraShortestPath<>(graph);
}

// cache hit?
Map<PastelNodeBlockEntity, GraphPath<PastelNodeBlockEntity, DefaultEdge>> e = this.pathCache.getOrDefault(source, null);
Map<BlockPos, GraphPath<BlockPos, DefaultEdge>> e = this.pathCache.getOrDefault(source.getPos(), null);
if (e != null) {
if (e.containsKey(destination)) {
return e.get(destination);
if (e.containsKey(destination.getPos())) {
return e.get(destination.getPos());
}
}

// calculate and cache
ShortestPathAlgorithm.SingleSourcePaths<PastelNodeBlockEntity, DefaultEdge> paths = this.dijkstra.getPaths(source);
GraphPath<PastelNodeBlockEntity, DefaultEdge> path = paths.getPath(destination);
if (this.pathCache.containsKey(source)) {
this.pathCache.get(source).put(destination, path);
ShortestPathAlgorithm.SingleSourcePaths<BlockPos, DefaultEdge> paths = this.dijkstra.getPaths(source.getPos());
GraphPath<BlockPos, DefaultEdge> path = paths.getPath(destination.getPos());
if (this.pathCache.containsKey(source.getPos())) {
this.pathCache.get(source.getPos()).put(destination.getPos(), path);
} else {
Map<PastelNodeBlockEntity, GraphPath<PastelNodeBlockEntity, DefaultEdge>> newMap = new HashMap<>();
newMap.put(destination, path);
this.pathCache.put(source, newMap);
Map<BlockPos, GraphPath<BlockPos, DefaultEdge>> newMap = new HashMap<>();
newMap.put(destination.getPos(), path);
this.pathCache.put(source.getPos(), newMap);
}

return path;
Expand Down Expand Up @@ -173,12 +173,9 @@ private boolean transferBetween(PastelNodeBlockEntity sourceNode, Storage<ItemVa
}

public Optional<PastelTransmission> createTransmissionOnValidPath(PastelNodeBlockEntity source, PastelNodeBlockEntity destination, ItemVariant variant, long amount, int vertexTime) {
GraphPath<PastelNodeBlockEntity, DefaultEdge> graphPath = getPath(this.network.getGraph(), source, destination);
GraphPath<BlockPos, DefaultEdge> graphPath = getPath(this.network.getGraph(), source, destination);
if (graphPath != null) {
List<BlockPos> vertexPositions = new ArrayList<>();
for (PastelNodeBlockEntity vertex : graphPath.getVertexList()) {
vertexPositions.add(vertex.getPos());
}
List<BlockPos> vertexPositions = new ArrayList<>(graphPath.getVertexList());

SpectrumS2CPacketSender.sendPastelNodeStatusUpdate(List.of(source), true);
return Optional.of(new PastelTransmission(vertexPositions, variant, amount, vertexTime));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,22 +114,19 @@ public NbtCompound toNbt() {
compound.put("Looper", this.transferLooper.toNbt());
return compound;
}

public static ServerPastelNetwork fromNbtServer(NbtCompound compound) {
World world = SpectrumCommon.minecraftServer.getWorld(RegistryKey.of(RegistryKeys.WORLD, Identifier.tryParse(compound.getString("World"))));
UUID uuid = compound.getUuid("UUID");

ServerPastelNetwork network = new ServerPastelNetwork(world, uuid);

@Override
public void fromNbt(NbtCompound compound) {
super.fromNbt(compound);
if (compound.contains("Looper", NbtElement.COMPOUND_TYPE)) {
network.transferLooper.readNbt(compound.getCompound("Looper"));
transferLooper.readNbt(compound.getCompound("Looper"));
}

for (NbtElement e : compound.getList("Transmissions", NbtElement.COMPOUND_TYPE)) {
NbtCompound t = (NbtCompound) e;
int delay = t.getInt("Delay");
PastelTransmission transmission = PastelTransmission.fromNbt(t.getCompound("Transmission"));
network.addTransmission(transmission, delay);
addTransmission(transmission, delay);
}
return network;
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package de.dafuqs.spectrum.blocks.pastel_network.network;

import de.dafuqs.spectrum.*;
import de.dafuqs.spectrum.blocks.pastel_network.nodes.*;
import net.minecraft.nbt.*;
import net.minecraft.registry.*;
import net.minecraft.server.world.*;
import net.minecraft.util.*;
import net.minecraft.util.math.*;
import net.minecraft.world.*;
import org.jetbrains.annotations.*;
Expand Down Expand Up @@ -51,7 +54,12 @@ public NbtCompound writeNbt(NbtCompound nbt) {
public static ServerPastelNetworkManager fromNbt(NbtCompound nbt) {
ServerPastelNetworkManager manager = new ServerPastelNetworkManager();
for (NbtElement element : nbt.getList("Networks", NbtElement.COMPOUND_TYPE)) {
manager.networks.add(ServerPastelNetwork.fromNbtServer((NbtCompound) element));
var compound = (NbtCompound) element;
World world = SpectrumCommon.minecraftServer.getWorld(RegistryKey.of(RegistryKeys.WORLD, Identifier.tryParse(compound.getString("World"))));
UUID uuid = compound.getUuid("UUID");
var network = new ServerPastelNetwork(world, uuid);
network.fromNbt(compound);
manager.networks.add(network);
}
return manager;
}
Expand Down Expand Up @@ -146,6 +154,9 @@ public void removeNode(PastelNodeBlockEntity node, NodeRemovalReason reason) {
if (network != null) {
network.removeNode(node, reason);

if (reason == NodeRemovalReason.UNLOADED)
return;

if (network.hasNodes()) {
// check if the removed node split the network into subnetworks
checkForNetworkSplit(network);
Expand All @@ -163,10 +174,13 @@ private void checkForNetworkSplit(ServerPastelNetwork network) {
Set<BlockPos> disconnectedNodes = connectedSets.get(i);
PastelNetwork newNetwork = createNetwork(network.world, null);
for (BlockPos disconnectedNode : disconnectedNodes) {
network.loadedNodes.get(disconnectedNode.getNodeType()).remove(disconnectedNode);
var switchedNode = network.getWorld().getBlockEntity(disconnectedNode);
network.getGraph().removeVertex(disconnectedNode);
newNetwork.addNodeAndLoadMemory(disconnectedNode);
disconnectedNode.setParentNetwork(newNetwork);
if (switchedNode instanceof PastelNodeBlockEntity pastelNode) {
network.loadedNodes.get(pastelNode.getNodeType()).remove(pastelNode);
newNetwork.addNode(pastelNode);
pastelNode.setParentNetwork(newNetwork);
}
}
}
}
Expand Down

0 comments on commit f2ddccf

Please sign in to comment.