Skip to content

IML-35 Add task resolved #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,13 @@ public void onPlace(BlockState state, Level level, BlockPos pos, BlockState prev
if (!level.isClientSide && this.checkStateChanged(previousState, state)) {
var networksJoined = new HashSet<Network>();
var part = this.getPart(level, pos);
Entity<?> entity = null;

for (var dir : part.getConnectableSides(level, pos)) {
var opt = LogicNetManager.findNetwork(level, pos.relative(dir));
if (opt.isPresent()) {
var network = opt.get();
if (LogicNetManager.joinNetwork(level, network, pos, dir, part)) {
if ((entity = LogicNetManager.joinNetwork(level, network, pos, dir, part)) != null) {
networksJoined.add(network);
}
}
Expand All @@ -68,7 +69,7 @@ public void onPlace(BlockState state, Level level, BlockPos pos, BlockState prev
if (networksJoined.isEmpty()) {
LogicNetManager.registerNewNetwork(level, pos, part);
} else {
LogicNetManager.mergeNetworks(level, networksJoined);
LogicNetManager.mergeNetworks(level, entity, networksJoined);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
import info.nukepowered.impressivelogic.common.block.AbstractNetworkBlock;
import info.nukepowered.impressivelogic.common.logic.network.Network.Entity;
import info.nukepowered.impressivelogic.common.logic.network.execution.NetworkExecutionManager;
import info.nukepowered.impressivelogic.common.logic.network.execution.tasks.NetCompileTask;
import info.nukepowered.impressivelogic.common.logic.network.execution.NetworkUpdateType;
import info.nukepowered.impressivelogic.common.logic.network.execution.tasks.NetworkUpdateCompileTask;
import net.minecraft.core.BlockPos;
import net.minecraft.core.BlockPos.MutableBlockPos;
import net.minecraft.core.Direction;
Expand All @@ -17,6 +18,9 @@

import java.util.*;

import static info.nukepowered.impressivelogic.ImpressiveLogic.LOGGER;
import static info.nukepowered.impressivelogic.common.logic.network.execution.tasks.AbstractNetworkUpdateTask.COMPILE_MARKER;

/**
* Copyright (c) Nukepowered 2022.
*
Expand Down Expand Up @@ -51,7 +55,8 @@ public static Network registerNewNetwork(Level level, BlockPos partPos, INetwork
* @param part requester part
* @return true if joined to network
*/
public static boolean joinNetwork(Level level, Network network, BlockPos partPos, Direction from, INetworkPart part) {
public static Entity<?> joinNetwork(Level level, Network network, BlockPos partPos, Direction from, INetworkPart part) {
Entity<?> entity = null;
var entityOpt = network.findEntity(partPos);
var netPos = partPos.relative(from);
var netDir = from.getOpposite();
Expand All @@ -60,26 +65,22 @@ public static boolean joinNetwork(Level level, Network network, BlockPos partPos
if (partOptional.isPresent()) {
var netEntity = partOptional.get();
if (netEntity.getPart().acceptConnection(level, netPos, netDir)) {
Entity<?> entity;
if (entityOpt.isPresent()) {
entityOpt.get().getConnections().add(from);
entity = entityOpt.get();
entity.getConnections().add(from);
netEntity.getConnections().add(netDir);

return true;
} else if ((entity = network.registerPart(partPos, part)) != null) {
NETWORKS.registerPartMapping(level.dimension().location(), network, partPos);
netEntity.getConnections().add(netDir);
entity.getConnections().add(from);

return true;
}
}
}

return false;
return entity;
}

public static void mergeNetworks(Level level, Collection<Network> networks) {
public static void mergeNetworks(Level level, Entity<?> cause, Collection<Network> networks) {
var queue = new ArrayDeque<>(networks);
var first = queue.poll();

Expand All @@ -88,7 +89,11 @@ public static void mergeNetworks(Level level, Collection<Network> networks) {
NETWORKS.updateMappings(level.dimension().location(), first, net.getEntityLocations());
}

NetworkExecutionManager.instance().submit(new NetCompileTask(first));
// If we've joined only one network, update network by faster procedure
var type = queue.isEmpty() ?
NetworkUpdateType.ADD_NODE :
NetworkUpdateType.MERGE;
updateNetworkStructure(first, cause, type);
}

/**
Expand All @@ -106,7 +111,7 @@ public static void removeFromNetwork(Level level, BlockPos pos) {
if (opt.isPresent()) {
var network = opt.get();
NETWORKS.unregisterPartMapping(level.dimension().location(), pos);
network.unregisterPart(pos);
updateNetworkStructure(network, network.unregisterPart(pos), NetworkUpdateType.REMOVE_NODE);
}
}

Expand All @@ -120,11 +125,13 @@ public static void removeFromNetwork(Level level, BlockPos pos) {
* @param updatedFrom Direction update triggered from (will not check this direction)
*/
public static void validateNetwork(Level level, BlockPos updatedBlock, Direction updatedFrom) {
LOGGER.debug(COMPILE_MARKER, "Network validation run for block {}, called from: {}", updatedBlock, updatedFrom);

// If throws NPE here - you are using this method wrong
// It should be called only if Part of network notice update around
var currentNetwork = findNetwork(level, updatedBlock).get();
var part = currentNetwork.findEntity(updatedBlock).get().getPart();
final var initSides = new HashSet<>(part.getConnectableSides(level, updatedBlock));
var entityUpdated = currentNetwork.findEntity(updatedBlock).get();
final var initSides = new HashSet<>(entityUpdated.getPart().getConnectableSides(level, updatedBlock));

// Will not check for side update came from, block removal expected
initSides.remove(updatedFrom);
Expand Down Expand Up @@ -178,7 +185,7 @@ public static void validateNetwork(Level level, BlockPos updatedBlock, Direction
if (!parts.containsAll(currentNetwork.getEntityLocations())) {
var newNetwork = currentNetwork.split(parts);
NETWORKS.updateMappings(level.dimension().location(), newNetwork, parts);
NetworkExecutionManager.instance().submit(new NetCompileTask(newNetwork));
NetworkExecutionManager.instance().submit(new NetworkUpdateCompileTask(newNetwork, entityUpdated));
}
}

Expand All @@ -189,4 +196,9 @@ public static Optional<Network> findNetwork(Level level, BlockPos pos) {
public static NetworkRegistry getRegistry() {
return NETWORKS;
}

public static void updateNetworkStructure(Network network, Entity<?> cause, NetworkUpdateType updateType) {
var task = updateType.createTask(network, cause);
NetworkExecutionManager.instance().submit(task);
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package info.nukepowered.impressivelogic.common.logic.network;

import com.google.common.graph.Graph;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.Graphs;
import com.google.common.graph.ImmutableGraph;
import info.nukepowered.impressivelogic.api.logic.INetworkPart;
import info.nukepowered.impressivelogic.api.logic.INetworkPart.PartType;
import info.nukepowered.impressivelogic.api.logic.io.INetworkInput;
import info.nukepowered.impressivelogic.api.logic.io.INetworkOutput;
import info.nukepowered.impressivelogic.common.logic.network.execution.NetworkExecutionManager;
import info.nukepowered.impressivelogic.common.logic.network.execution.tasks.NetStateUpdateTask;
import info.nukepowered.impressivelogic.common.util.NetworkUtils;
Expand Down Expand Up @@ -37,7 +41,7 @@ public class Network {

private Set<Entity<?>> entities = ConcurrentHashMap.newKeySet();
private Set<Entity<INetworkInput<?>>> inputs = new HashSet<>();
private Graph<Entity<?>> connections;
private volatile Graph<Entity<?>> connections;

/**
* Will trigger network to check logic state and update outputs
Expand All @@ -60,7 +64,7 @@ public <T extends INetworkPart> Entity<T> registerPart(BlockPos pos, T part) {
return entity;
}

public void unregisterPart(BlockPos pos) {
public Entity<?> unregisterPart(BlockPos pos) {
var opt = this.findEntity(pos);
if (opt.isPresent()) {
var entity = opt.get();
Expand All @@ -78,7 +82,11 @@ public void unregisterPart(BlockPos pos) {
.filter(e -> toUpdate.containsKey(e.location))
.map(e -> Pair.of(e, toUpdate.get(e.location)))
.forEach(p -> p.getKey().connections.remove(p.getValue()));

return entity;
}

return null;
}

public void merge(Network other) {
Expand All @@ -87,7 +95,7 @@ public void merge(Network other) {
var oEntities = other.entities.stream()
.collect(Collectors.toMap(Entity::getLocation, Function.identity()));


// Merge connections of entities
for (var entry : oEntities.entrySet()) {
var oEntity = entry.getValue();
var tEntity = tEntities.get(entry.getKey());
Expand All @@ -98,12 +106,16 @@ public void merge(Network other) {
tEntities.put(entry.getKey(), oEntity);
}


// Remove and put again entities of this net, to update hash
this.entities.clear();
tEntities.values().forEach(this.entities::add);

// Merge entities itself
this.entities.addAll(other.entities);
this.inputs.addAll(other.inputs);

// Merge Graphs
this.mergeGraph(other.connections);
}

public Network split(Collection<BlockPos> parts) {
Expand Down Expand Up @@ -157,6 +169,19 @@ public boolean isEmpty() {
return this.entities.isEmpty();
}

private void mergeGraph(final Graph<Entity<?>> other) {
final var graph = this.connections != null ?
Graphs.copyOf(this.connections) :
GraphBuilder.directed().<Entity<?>>build();

if (other != null) {
other.nodes().forEach(graph::addNode);
other.edges().forEach(graph::putEdge);
}

this.connections = ImmutableGraph.copyOf(graph);
}

public CompoundTag writeToNBT() {
final var compound = new CompoundTag();
final var entities = new ListTag();
Expand Down Expand Up @@ -248,6 +273,11 @@ public boolean isInputType() {
return part.getPartType() == PartType.IO && part instanceof INetworkInput<?>;
}

public boolean isOutputType() {
var part = this.getPart();
return part.getPartType() == PartType.IO && part instanceof INetworkOutput<?>;
}

@Override
public boolean equals(Object obj) {
return obj instanceof Entity entity && this.location.equals(entity.location);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package info.nukepowered.impressivelogic.common.logic.network.execution;

import info.nukepowered.impressivelogic.common.logic.network.Network;
import info.nukepowered.impressivelogic.common.logic.network.Network.Entity;
import net.minecraft.core.BlockPos;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;

import java.util.Comparator;
import java.util.NavigableMap;
import java.util.TreeMap;

/**
* Copyright (c) Nukepowered 2022.
*
* @author TheDarkDnKTv
*/
public abstract class AbstractNetworkTask implements Runnable {

public static final Marker COMPILE_MARKER = MarkerFactory.getMarker("NET_COMPILE");

protected final Network suspect;
protected final NavigableMap<BlockPos, Entity<?>> entities;

public AbstractNetworkTask(Network suspect) {
this.suspect = suspect;
this.entities = new TreeMap<>(Comparator.naturalOrder());
}

protected abstract void execute();

@Override
public final void run() {
suspect.getEntities().forEach(e -> entities.put(e.getLocation(), e));
this.execute();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package info.nukepowered.impressivelogic.common.logic.network.execution;

import info.nukepowered.impressivelogic.common.logic.network.Network;
import info.nukepowered.impressivelogic.common.logic.network.Network.Entity;
import info.nukepowered.impressivelogic.common.logic.network.execution.tasks.*;

import java.util.function.BiFunction;

/**
* Copyright (c) Nukepowered 2022.
*
* @author TheDarkDnKTv
*/
public enum NetworkUpdateType {

COMPILE(NetworkUpdateCompileTask::new),
ADD_NODE(NetworkUpdateAddTask::new),
MERGE(NetworkUpdateMergeTask::new),
REMOVE_NODE(NetworkUpdateRemoveTask::new);

private final BiFunction<Network, Entity<?>, ? extends AbstractNetworkUpdateTask> factory;

NetworkUpdateType(BiFunction<Network, Entity<?>, ? extends AbstractNetworkUpdateTask> factory) {
this.factory = factory;
}

public AbstractNetworkUpdateTask createTask(Network network, Entity<?> cause) {
return this.factory.apply(network, cause);
}
}
Loading