repo_id
stringclasses 383
values | file_path
stringlengths 7
168
| content
stringlengths 0
1.75M
|
|---|---|---|
alternate-current
|
src\main\java\alternate\current\command\AlternateCurrentCommand.java
|
package alternate.current.command;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import alternate.current.AlternateCurrentMod;
import alternate.current.interfaces.mixin.IServerLevel;
import alternate.current.util.profiler.ProfilerResults;
import alternate.current.wire.UpdateOrder;
import alternate.current.wire.WireHandler;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.permissions.Permissions;
public class AlternateCurrentCommand {
private static final DynamicCommandExceptionType NO_SUCH_UPDATE_ORDER = new DynamicCommandExceptionType(value -> Component.literal("no such update order: " + value));
private static final String[] UPDATE_ORDERS;
static {
UpdateOrder[] updateOrders = UpdateOrder.values();
UPDATE_ORDERS = new String[updateOrders.length];
for (int i = 0; i < updateOrders.length; i++) {
UPDATE_ORDERS[i] = updateOrders[i].id();
}
}
public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
LiteralArgumentBuilder<CommandSourceStack> builder = Commands.
literal("alternatecurrent").
requires(source -> source.permissions().hasPermission(Permissions.COMMANDS_MODERATOR)).
executes(context -> queryEnabled(context.getSource())).
then(Commands.
literal("on").
executes(context -> setEnabled(context.getSource(), true))).
then(Commands.
literal("off").
executes(context -> setEnabled(context.getSource(), false))).
then(Commands.
literal("updateOrder").
executes(context -> queryUpdateOrder(context.getSource())).
then(Commands.
argument("updateOrder", StringArgumentType.word()).
suggests((context, suggestionBuilder) -> SharedSuggestionProvider.suggest(UPDATE_ORDERS, suggestionBuilder)).
executes(context -> setUpdateOrder(context.getSource(), parseUpdateOrder(context, "updateOrder"))))).
then(Commands.
literal("resetProfiler").
requires(source -> AlternateCurrentMod.DEBUG).
executes(context -> resetProfiler(context.getSource())));
dispatcher.register(builder);
}
private static UpdateOrder parseUpdateOrder(CommandContext<CommandSourceStack> context, String name) throws CommandSyntaxException {
String value = StringArgumentType.getString(context, name);
try {
return UpdateOrder.byId(value);
} catch (Exception e) {
throw NO_SUCH_UPDATE_ORDER.create(name);
}
}
private static int queryEnabled(CommandSourceStack source) {
ServerLevel level = source.getLevel();
WireHandler wireHandler = ((IServerLevel) level).alternate_current$getWireHandler();
String state = wireHandler.getConfig().getEnabled() ? "enabled" : "disabled";
source.sendSuccess(() -> Component.literal(String.format("Alternate Current is currently %s", state)), false);
return Command.SINGLE_SUCCESS;
}
private static int setEnabled(CommandSourceStack source, boolean on) {
ServerLevel level = source.getLevel();
WireHandler wireHandler = ((IServerLevel) level).alternate_current$getWireHandler();
wireHandler.getConfig().setEnabled(on);
String state = wireHandler.getConfig().getEnabled() ? "enabled" : "disabled";
source.sendSuccess(() -> Component.literal(String.format("Alternate Current has been %s!", state)), true);
return Command.SINGLE_SUCCESS;
}
private static int queryUpdateOrder(CommandSourceStack source) {
ServerLevel level = source.getLevel();
WireHandler wireHandler = ((IServerLevel) level).alternate_current$getWireHandler();
String value = wireHandler.getConfig().getUpdateOrder().id();
source.sendSuccess(() -> Component.literal(String.format("Update order is currently %s", value)), false);
return Command.SINGLE_SUCCESS;
}
private static int setUpdateOrder(CommandSourceStack source, UpdateOrder updateOrder) {
ServerLevel level = source.getLevel();
WireHandler wireHandler = ((IServerLevel) level).alternate_current$getWireHandler();
wireHandler.getConfig().setUpdateOrder(updateOrder);
String value = wireHandler.getConfig().getUpdateOrder().id();
source.sendSuccess(() -> Component.literal(String.format("update order has been set to %s!", value)), true);
return Command.SINGLE_SUCCESS;
}
private static int resetProfiler(CommandSourceStack source) {
source.sendSuccess(() -> Component.literal("profiler results have been cleared!"), true);
ProfilerResults.log();
ProfilerResults.clear();
return Command.SINGLE_SUCCESS;
}
}
|
alternate-current
|
src\main\java\alternate\current\mixin\CommandsMixin.java
|
package alternate.current.mixin;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.At.Shift;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.mojang.brigadier.CommandDispatcher;
import alternate.current.command.AlternateCurrentCommand;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.Commands.CommandSelection;
@Mixin(Commands.class)
public class CommandsMixin {
@Shadow @Final private CommandDispatcher<CommandSourceStack> dispatcher;
@Inject(
method="<init>",
at = @At(
value = "INVOKE",
shift = Shift.BEFORE,
target = "Lcom/mojang/brigadier/CommandDispatcher;setConsumer(Lcom/mojang/brigadier/ResultConsumer;)V"
)
)
private void alternate_current$registerCommands(CommandSelection selection, CommandBuildContext context, CallbackInfo ci) {
AlternateCurrentCommand.register(dispatcher);
}
}
|
alternate-current
|
src\main\java\alternate\current\mixin\ExperimentalRedstoneUtilsMixin.java
|
package alternate.current.mixin;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import alternate.current.AlternateCurrentMod;
import net.minecraft.core.Direction;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.redstone.ExperimentalRedstoneUtils;
import net.minecraft.world.level.redstone.Orientation;
@Mixin(ExperimentalRedstoneUtils.class)
public class ExperimentalRedstoneUtilsMixin {
@Inject(
method = "initialOrientation",
cancellable = true,
at = @At(
value = "RETURN",
ordinal = 0
)
)
private static void noRandomOrientation(Level level, Direction front, Direction up, CallbackInfoReturnable<Orientation> cir) {
// if the given front is null, a random front is chosen - use default value instead
if (AlternateCurrentMod.on && front == null) {
cir.setReturnValue(cir.getReturnValue().withFront(Direction.WEST));
}
}
}
|
alternate-current
|
src\main\java\alternate\current\mixin\MinecraftServerMixin.java
|
package alternate.current.mixin;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import alternate.current.interfaces.mixin.IServerLevel;
import alternate.current.wire.WireHandler;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
@Mixin(MinecraftServer.class)
public class MinecraftServerMixin {
@Inject(
method = "saveAllChunks",
at = @At(
value = "HEAD"
)
)
private void alternate_current$save(boolean silent, boolean bl2, boolean bl3, CallbackInfoReturnable<Boolean> cir) {
ServerLevel overworld = ((MinecraftServer) (Object) this).overworld();
WireHandler wireHandler = ((IServerLevel) overworld).alternate_current$getWireHandler();
wireHandler.getConfig().save(silent);
}
}
|
alternate-current
|
src\main\java\alternate\current\mixin\RedStoneWireBlockMixin.java
|
package alternate.current.mixin;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import alternate.current.AlternateCurrentMod;
import alternate.current.interfaces.mixin.IServerLevel;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.RedStoneWireBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.redstone.Orientation;
@Mixin(RedStoneWireBlock.class)
public class RedStoneWireBlockMixin {
@Inject(
method = "updatePowerStrength",
cancellable = true,
at = @At(
value = "HEAD"
)
)
private void alternate_current$onUpdate(Level level, BlockPos pos, BlockState state, Orientation orientation, boolean added, CallbackInfo ci) {
if (AlternateCurrentMod.on) {
// Using redirects for calls to this method makes conflicts with
// other mods more likely, so we inject-cancel instead.
ci.cancel();
}
}
@Inject(
method = "onPlace",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/world/level/block/RedStoneWireBlock;updatePowerStrength(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/redstone/Orientation;Z)V"
)
)
private void alternate_current$onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean movedByPiston, CallbackInfo ci) {
if (AlternateCurrentMod.on) {
((IServerLevel)level).alternate_current$getWireHandler().onWireAdded(pos, state);
}
}
@Inject(
method = "affectNeighborsAfterRemoval",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/world/level/block/RedStoneWireBlock;updatePowerStrength(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/redstone/Orientation;Z)V"
)
)
private void alternate_current$onRemove(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston, CallbackInfo ci) {
if (AlternateCurrentMod.on) {
((IServerLevel)level).alternate_current$getWireHandler().onWireRemoved(pos, state);
}
}
@Inject(
method = "neighborChanged",
cancellable = true,
at = @At(
value = "HEAD"
)
)
private void alternate_current$onNeighborChanged(BlockState state, Level level, BlockPos pos, Block neighborBlock, Orientation orientation, boolean movedByPiston, CallbackInfo ci) {
if (AlternateCurrentMod.on) {
if (((IServerLevel)level).alternate_current$getWireHandler().onWireUpdated(pos, state, orientation)) {
ci.cancel(); // needed to fix duplication bugs
}
}
}
}
|
alternate-current
|
src\main\java\alternate\current\mixin\ServerLevelMixin.java
|
package alternate.current.mixin;
import java.util.List;
import java.util.concurrent.Executor;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import alternate.current.interfaces.mixin.IServerLevel;
import alternate.current.wire.WireHandler;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.RandomSequences;
import net.minecraft.world.level.CustomSpawner;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.ServerLevelData;
@Mixin(ServerLevel.class)
public class ServerLevelMixin implements IServerLevel {
private WireHandler wireHandler;
@Inject(
method = "<init>",
at = @At(
value = "TAIL"
)
)
private void alternate_current$parseConfig(MinecraftServer server, Executor executor, LevelStorageSource.LevelStorageAccess storage, ServerLevelData data, ResourceKey<Level> key, LevelStem stem, boolean clientSide, long seed, List<CustomSpawner> customSpawners, boolean tickTime, RandomSequences randomSequences, CallbackInfo ci) {
this.wireHandler = new WireHandler((ServerLevel)(Object)this, storage);
}
@Override
public WireHandler alternate_current$getWireHandler() {
return wireHandler;
}
}
|
alternate-current
|
src\main\java\alternate\current\wire\Config.java
|
package alternate.current.wire;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import alternate.current.AlternateCurrentMod;
import alternate.current.interfaces.mixin.IServerLevel;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.storage.LevelResource;
import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess;
public interface Config {
static Config forLevel(ServerLevel level, LevelStorageAccess storage) {
if (level.dimension() == Level.OVERWORLD) {
return new Primary(storage);
} else {
return new Derived(((IServerLevel) level.getServer().overworld()).alternate_current$getWireHandler().getConfig());
}
}
boolean getEnabled();
void setEnabled(boolean enabled);
UpdateOrder getUpdateOrder();
void setUpdateOrder(UpdateOrder updateOrder);
void load();
void save(boolean silent);
public static class Primary implements Config {
private final Path path;
private boolean enabled = true;
private UpdateOrder updateOrder = UpdateOrder.HORIZONTAL_FIRST_OUTWARD;
private boolean modified;
public Primary(LevelStorageAccess storage) {
this.path = storage.getLevelPath(LevelResource.ROOT).resolve("alternate-current.conf");
}
@Override
public boolean getEnabled() {
return enabled;
}
@Override
public void setEnabled(boolean enabled) {
this.enabled = enabled;
AlternateCurrentMod.on = enabled;
this.modified = true;
}
@Override
public UpdateOrder getUpdateOrder() {
return updateOrder;
}
@Override
public void setUpdateOrder(UpdateOrder updateOrder) {
this.updateOrder = Objects.requireNonNull(updateOrder);
this.modified = true;
}
@Override
public void load() {
if (Files.exists(path)) {
try (BufferedReader br = Files.newBufferedReader(path)) {
String line;
while ((line = br.readLine()) != null) {
if (!line.startsWith("#")) {
String[] parts = line.split("[=]");
if (parts.length == 2) {
String key = parts[0];
String value = parts[1];
try {
switch (key) {
case "enabled":
setEnabled(Boolean.parseBoolean(value));
break;
case "update-order":
setUpdateOrder(UpdateOrder.byId(value));
break;
default:
AlternateCurrentMod.LOGGER.info("skipping unknown option \'" + key + "\' in Alternate Current config");
}
} catch (Exception e) {
AlternateCurrentMod.LOGGER.info("skipping bad value \'" + value + "\' for option \'" + key + "\' in Alternate Current config!", e);
}
}
}
}
modified = false;
} catch (IOException e) {
AlternateCurrentMod.LOGGER.info("unable to load Alternate Current config!", e);
modified = true;
}
} else {
modified = true;
}
}
@Override
public void save(boolean silent) {
if (modified) {
if (!silent) {
AlternateCurrentMod.LOGGER.info("saving Alternate Current config");
}
try (BufferedWriter bw = Files.newBufferedWriter(path)) {
bw.write("enabled");
bw.write('=');
bw.write(Boolean.toString(enabled));
bw.newLine();
bw.write("update-order");
bw.write('=');
bw.write(updateOrder.id());
bw.newLine();
} catch (IOException e) {
AlternateCurrentMod.LOGGER.info("unable to save Alternate Current config!", e);
} finally {
modified = false;
}
}
}
}
public static class Derived implements Config {
private final Config delegate;
public Derived(Config delegate) {
this.delegate = delegate;
}
@Override
public boolean getEnabled() {
return delegate.getEnabled();
}
@Override
public void setEnabled(boolean enabled) {
delegate.setEnabled(enabled);
}
@Override
public UpdateOrder getUpdateOrder() {
return delegate.getUpdateOrder();
}
@Override
public void setUpdateOrder(UpdateOrder updateOrder) {
delegate.setUpdateOrder(updateOrder);
}
@Override
public void load() {
}
@Override
public void save(boolean silent) {
}
}
}
|
alternate-current
|
src\main\java\alternate\current\wire\LevelHelper.java
|
package alternate.current.wire;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.world.level.chunk.status.ChunkStatus;
class LevelHelper {
/**
* An optimized version of {@link net.minecraft.world.level.Level#setBlock
* Level.setBlock}. Since this method is only used to update redstone wire block
* states, lighting checks, height map updates, and block entity updates are
* omitted.
*/
static boolean setWireState(ServerLevel level, BlockPos pos, BlockState state, boolean updateNeighborShapes) {
int y = pos.getY();
if (y < level.getMinY() || y > level.getMaxY()) {
return false;
}
int x = pos.getX();
int z = pos.getZ();
int index = level.getSectionIndex(y);
ChunkAccess chunk = level.getChunk(x >> 4, z >> 4, ChunkStatus.FULL, true);
LevelChunkSection section = chunk.getSections()[index];
if (section == null) {
return false; // we should never get here
}
BlockState prevState = section.setBlockState(x & 15, y & 15, z & 15, state);
if (state == prevState) {
return false;
}
// notify clients of the BlockState change
level.getChunkSource().blockChanged(pos);
// mark the chunk for saving
chunk.markUnsaved();
if (updateNeighborShapes) {
prevState.updateIndirectNeighbourShapes(level, pos, Block.UPDATE_CLIENTS);
state.updateNeighbourShapes(level, pos, Block.UPDATE_CLIENTS);
state.updateIndirectNeighbourShapes(level, pos, Block.UPDATE_CLIENTS);
}
return true;
}
}
|
alternate-current
|
src\main\java\alternate\current\wire\Node.java
|
package alternate.current.wire;
import java.util.Arrays;
import alternate.current.wire.WireHandler.Directions;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
/**
* A Node represents a block in the world. It also holds a few other pieces of
* information that speed up the calculations in the WireHandler class.
*
* @author Space Walker
*/
public class Node {
// flags that encode the Node type
private static final int CONDUCTOR = 0b01;
private static final int SOURCE = 0b10;
final ServerLevel level;
final Node[] neighbors;
BlockPos pos;
BlockState state;
boolean invalid;
private int flags;
/** The previous node in the priority queue. */
Node prev_node;
/** The next node in the priority queue. */
Node next_node;
/** The priority with which this node was queued. */
int priority;
/** The wire that queued this node for an update. */
WireNode neighborWire;
Node(ServerLevel level) {
this.level = level;
this.neighbors = new Node[Directions.ALL.length];
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Node)) {
return false;
}
Node node = (Node)obj;
return level == node.level && pos.equals(node.pos);
}
@Override
public int hashCode() {
return pos.hashCode();
}
Node set(BlockPos pos, BlockState state, boolean clearNeighbors) {
if (state.is(Blocks.REDSTONE_WIRE)) {
throw new IllegalStateException("Cannot update a regular Node to a WireNode!");
}
if (clearNeighbors) {
Arrays.fill(neighbors, null);
}
this.pos = pos.immutable();
this.state = state;
this.invalid = false;
this.flags = 0;
if (this.state.isRedstoneConductor(this.level, this.pos)) {
this.flags |= CONDUCTOR;
}
if (this.state.isSignalSource()) {
this.flags |= SOURCE;
}
return this;
}
/**
* Determine the priority with which this node should be queued.
*/
int priority() {
return neighborWire.priority;
}
public boolean isWire() {
return false;
}
public boolean isConductor() {
return (flags & CONDUCTOR) != 0;
}
public boolean isSignalSource() {
return (flags & SOURCE) != 0;
}
public WireNode asWire() {
throw new UnsupportedOperationException("Not a WireNode!");
}
}
|
alternate-current
|
src\main\java\alternate\current\wire\PriorityQueue.java
|
package alternate.current.wire;
import java.util.AbstractQueue;
import java.util.Arrays;
import java.util.Iterator;
import net.minecraft.world.level.redstone.Redstone;
public class PriorityQueue extends AbstractQueue<Node> {
private static final int OFFSET = -Redstone.SIGNAL_MIN;
/** The last node for each priority value. */
private final Node[] tails;
private Node head;
private Node tail;
private int size;
PriorityQueue() {
this.tails = new Node[(Redstone.SIGNAL_MAX + OFFSET) + 1];
}
@Override
public boolean offer(Node node) {
if (node == null) {
throw new NullPointerException();
}
int priority = node.priority();
if (contains(node)) {
if (node.priority == priority) {
// already queued with this priority; exit
return false;
} else {
// already queued with different priority; move it
move(node, priority);
}
} else {
insert(node, priority);
}
return true;
}
@Override
public Node poll() {
if (head == null) {
return null;
}
Node node = head;
Node next = node.next_node;
if (next == null) {
clear(); // reset the tails array
} else {
if (node.priority != next.priority) {
// If the head is also a tail, its entry in the array
// can be cleared; there is no previous node with the
// same priority to take its place.
tails[node.priority + OFFSET] = null;
}
node.next_node = null;
next.prev_node = null;
head = next;
size--;
}
return node;
}
@Override
public Node peek() {
return head;
}
@Override
public void clear() {
for (Node node = head; node != null; ) {
Node n = node;
node = node.next_node;
n.prev_node = null;
n.next_node = null;
}
Arrays.fill(tails, null);
head = null;
tail = null;
size = 0;
}
@Override
public Iterator<Node> iterator() {
throw new UnsupportedOperationException();
}
@Override
public int size() {
return size;
}
public boolean contains(Node node) {
return node == head || node.prev_node != null;
}
private void move(Node node, int priority) {
remove(node);
insert(node, priority);
}
private void remove(Node node) {
Node prev = node.prev_node;
Node next = node.next_node;
if (node == tail || node.priority != next.priority) {
// assign a new tail for this node's priority
if (node == head || node.priority != prev.priority) {
// there is no other node with the same priority; clear
tails[node.priority + OFFSET] = null;
} else {
// the previous node in the queue becomes the tail
tails[node.priority + OFFSET] = prev;
}
}
if (node == head) {
head = next;
} else {
prev.next_node = next;
}
if (node == tail) {
tail = prev;
} else {
next.prev_node = prev;
}
node.prev_node = null;
node.next_node = null;
size--;
}
private void insert(Node node, int priority) {
node.priority = priority;
// nodes are sorted by priority (highest to lowest)
// nodes with the same priority are ordered FIFO
if (head == null) {
// first element in this queue \o/
head = tail = node;
} else if (priority > head.priority) {
linkHead(node);
} else if (priority <= tail.priority) {
linkTail(node);
} else {
// since the node is neither the head nor the tail
// findPrev is guaranteed to find a non-null element
linkAfter(findPrev(node), node);
}
tails[priority + OFFSET] = node;
size++;
}
private void linkHead(Node node) {
node.next_node = head;
head.prev_node = node;
head = node;
}
private void linkTail(Node node) {
tail.next_node = node;
node.prev_node = tail;
tail = node;
}
private void linkAfter(Node prev, Node node) {
linkBetween(prev, node, prev.next_node);
}
private void linkBetween(Node prev, Node node, Node next) {
prev.next_node = node;
node.prev_node = prev;
node.next_node = next;
next.prev_node = node;
}
private Node findPrev(Node node) {
Node prev = null;
for (int i = node.priority + OFFSET; i < tails.length; i++) {
prev = tails[i];
if (prev != null) {
break;
}
}
return prev;
}
}
|
alternate-current
|
src\main\java\alternate\current\wire\SimpleQueue.java
|
package alternate.current.wire;
import java.util.AbstractQueue;
import java.util.Iterator;
public class SimpleQueue extends AbstractQueue<WireNode> {
private WireNode head;
private WireNode tail;
private int size;
SimpleQueue() {
}
@Override
public boolean offer(WireNode node) {
if (node == null) {
throw new NullPointerException();
}
if (tail == null) {
head = tail = node;
} else {
tail.next_wire = node;
tail = node;
}
size++;
return true;
}
@Override
public WireNode poll() {
if (head == null) {
return null;
}
WireNode node = head;
WireNode next = node.next_wire;
if (next == null) {
head = tail = null;
} else {
node.next_wire = null;
head = next;
}
size--;
return node;
}
@Override
public WireNode peek() {
return head;
}
@Override
public void clear() {
for (WireNode node = head; node != null; ) {
WireNode n = node;
node = node.next_wire;
n.next_wire = null;
}
head = null;
tail = null;
size = 0;
}
@Override
public Iterator<WireNode> iterator() {
return new SimpleIterator();
}
@Override
public int size() {
return size;
}
private class SimpleIterator implements Iterator<WireNode> {
private WireNode curr;
private WireNode next;
private SimpleIterator() {
next = head;
}
@Override
public boolean hasNext() {
if (next == null && curr != null) {
next = curr.next_wire;
}
return next != null;
}
@Override
public WireNode next() {
curr = next;
next = curr.next_wire;
return curr;
}
}
}
|
alternate-current
|
src\main\java\alternate\current\wire\UpdateOrder.java
|
package alternate.current.wire;
import java.util.Locale;
import java.util.function.Consumer;
import alternate.current.wire.WireHandler.Directions;
import alternate.current.wire.WireHandler.NodeProvider;
public enum UpdateOrder {
HORIZONTAL_FIRST_OUTWARD(
new int[][] {
new int[] { Directions.WEST , Directions.EAST , Directions.NORTH, Directions.SOUTH, Directions.DOWN, Directions.UP },
new int[] { Directions.NORTH, Directions.SOUTH, Directions.EAST , Directions.WEST , Directions.DOWN, Directions.UP },
new int[] { Directions.EAST , Directions.WEST , Directions.SOUTH, Directions.NORTH, Directions.DOWN, Directions.UP },
new int[] { Directions.SOUTH, Directions.NORTH, Directions.WEST , Directions.EAST , Directions.DOWN, Directions.UP }
},
new int[][] {
new int[] { Directions.WEST , Directions.EAST , Directions.NORTH, Directions.SOUTH },
new int[] { Directions.NORTH, Directions.SOUTH, Directions.EAST , Directions.WEST },
new int[] { Directions.EAST , Directions.WEST , Directions.SOUTH, Directions.NORTH },
new int[] { Directions.SOUTH, Directions.NORTH, Directions.WEST , Directions.EAST }
}
) {
@Override
public void forEachNeighbor(NodeProvider nodes, Node source, int forward, Consumer<Node> action) {
/*
* This iteration order is designed to be an extension of the Vanilla shape
* update order, and is determined as follows:
* <br>
* 1. Each neighbor is identified by the step(s) you must take, starting at the
* source, to reach it. Each step is 1 block, thus the position of a neighbor is
* encoded by the direction(s) of the step(s), e.g. (right), (down), (up, left),
* etc.
* <br>
* 2. Neighbors are iterated over in pairs that lie on opposite sides of the
* source.
* <br>
* 3. Neighbors are iterated over in order of their distance from the source,
* moving outward. This means they are iterated over in 3 groups: direct
* neighbors first, then diagonal neighbors, and last are the far neighbors that
* are 2 blocks directly out.
* <br>
* 4. The order within each group is determined using the following basic order:
* { front, back, right, left, down, up }. This order was chosen because it
* converts to the following order of absolute directions when west is said to
* be 'forward': { west, east, north, south, down, up } - this is the order of
* shape updates.
*/
int rightward = (forward + 1) & 0b11;
int backward = (forward + 2) & 0b11;
int leftward = (forward + 3) & 0b11;
int downward = Directions.DOWN;
int upward = Directions.UP;
Node front = nodes.getNeighbor(source, forward);
Node right = nodes.getNeighbor(source, rightward);
Node back = nodes.getNeighbor(source, backward);
Node left = nodes.getNeighbor(source, leftward);
Node below = nodes.getNeighbor(source, downward);
Node above = nodes.getNeighbor(source, upward);
// direct neighbors (6)
action.accept(front);
action.accept(back);
action.accept(right);
action.accept(left);
action.accept(below);
action.accept(above);
// diagonal neighbors (12)
action.accept(nodes.getNeighbor(front, rightward));
action.accept(nodes.getNeighbor(back, leftward));
action.accept(nodes.getNeighbor(front, leftward));
action.accept(nodes.getNeighbor(back, rightward));
action.accept(nodes.getNeighbor(front, downward));
action.accept(nodes.getNeighbor(back, upward));
action.accept(nodes.getNeighbor(front, upward));
action.accept(nodes.getNeighbor(back, downward));
action.accept(nodes.getNeighbor(right, downward));
action.accept(nodes.getNeighbor(left, upward));
action.accept(nodes.getNeighbor(right, upward));
action.accept(nodes.getNeighbor(left, downward));
// far neighbors (6)
action.accept(nodes.getNeighbor(front, forward));
action.accept(nodes.getNeighbor(back, backward));
action.accept(nodes.getNeighbor(right, rightward));
action.accept(nodes.getNeighbor(left, leftward));
action.accept(nodes.getNeighbor(below, downward));
action.accept(nodes.getNeighbor(above, upward));
}
},
HORIZONTAL_FIRST_INWARD(
new int[][] {
new int[] { Directions.WEST , Directions.EAST , Directions.NORTH, Directions.SOUTH, Directions.DOWN, Directions.UP },
new int[] { Directions.NORTH, Directions.SOUTH, Directions.EAST , Directions.WEST , Directions.DOWN, Directions.UP },
new int[] { Directions.EAST , Directions.WEST , Directions.SOUTH, Directions.NORTH, Directions.DOWN, Directions.UP },
new int[] { Directions.SOUTH, Directions.NORTH, Directions.WEST , Directions.EAST , Directions.DOWN, Directions.UP }
},
new int[][] {
new int[] { Directions.WEST , Directions.EAST , Directions.NORTH, Directions.SOUTH },
new int[] { Directions.NORTH, Directions.SOUTH, Directions.EAST , Directions.WEST },
new int[] { Directions.EAST , Directions.WEST , Directions.SOUTH, Directions.NORTH },
new int[] { Directions.SOUTH, Directions.NORTH, Directions.WEST , Directions.EAST }
}
) {
@Override
public void forEachNeighbor(NodeProvider nodes, Node source, int forward, Consumer<Node> action) {
/*
* This iteration order is designed to be an inversion of the above update
* order, and is determined as follows:
* <br>
* 1. Each neighbor is identified by the step(s) you must take, starting at the
* source, to reach it. Each step is 1 block, thus the position of a neighbor is
* encoded by the direction(s) of the step(s), e.g. (right), (down), (up, left),
* etc.
* <br>
* 2. Neighbors are iterated over in pairs that lie on opposite sides of the
* source.
* <br>
* 3. Neighbors are iterated over in order of their distance from the source,
* moving inward. This means they are iterated over in 3 groups: neighbors that
* are 2 blocks directly out first, then diagonal neighbors, and last are direct
* neighbors.
* <br>
* 4. The order within each group is determined using the following basic order:
* { front, back, right, left, down, up }. This order was chosen because it
* converts to the following order of absolute directions when west is said to
* be 'forward': { west, east, north, south, down, up } - this is the order of
* shape updates.
*/
int rightward = (forward + 1) & 0b11;
int backward = (forward + 2) & 0b11;
int leftward = (forward + 3) & 0b11;
int downward = Directions.DOWN;
int upward = Directions.UP;
Node front = nodes.getNeighbor(source, forward);
Node right = nodes.getNeighbor(source, rightward);
Node back = nodes.getNeighbor(source, backward);
Node left = nodes.getNeighbor(source, leftward);
Node below = nodes.getNeighbor(source, downward);
Node above = nodes.getNeighbor(source, upward);
// far neighbors (6)
action.accept(nodes.getNeighbor(front, forward));
action.accept(nodes.getNeighbor(back, backward));
action.accept(nodes.getNeighbor(right, rightward));
action.accept(nodes.getNeighbor(left, leftward));
action.accept(nodes.getNeighbor(below, downward));
action.accept(nodes.getNeighbor(above, upward));
// diagonal neighbors (12)
action.accept(nodes.getNeighbor(front, rightward));
action.accept(nodes.getNeighbor(back, leftward));
action.accept(nodes.getNeighbor(front, leftward));
action.accept(nodes.getNeighbor(back, rightward));
action.accept(nodes.getNeighbor(front, downward));
action.accept(nodes.getNeighbor(back, upward));
action.accept(nodes.getNeighbor(front, upward));
action.accept(nodes.getNeighbor(back, downward));
action.accept(nodes.getNeighbor(right, downward));
action.accept(nodes.getNeighbor(left, upward));
action.accept(nodes.getNeighbor(right, upward));
action.accept(nodes.getNeighbor(left, downward));
// direct neighbors (6)
action.accept(front);
action.accept(back);
action.accept(right);
action.accept(left);
action.accept(below);
action.accept(above);
}
},
VERTICAL_FIRST_OUTWARD(
new int[][] {
new int[] { Directions.DOWN, Directions.UP, Directions.WEST , Directions.EAST , Directions.NORTH, Directions.SOUTH },
new int[] { Directions.DOWN, Directions.UP, Directions.NORTH, Directions.SOUTH, Directions.EAST , Directions.WEST },
new int[] { Directions.DOWN, Directions.UP, Directions.EAST , Directions.WEST , Directions.SOUTH, Directions.NORTH },
new int[] { Directions.DOWN, Directions.UP, Directions.SOUTH, Directions.NORTH, Directions.WEST , Directions.EAST }
},
new int[][] {
new int[] { Directions.WEST , Directions.EAST , Directions.NORTH, Directions.SOUTH },
new int[] { Directions.NORTH, Directions.SOUTH, Directions.EAST , Directions.WEST },
new int[] { Directions.EAST , Directions.WEST , Directions.SOUTH, Directions.NORTH },
new int[] { Directions.SOUTH, Directions.NORTH, Directions.WEST , Directions.EAST }
}
) {
@Override
public void forEachNeighbor(NodeProvider nodes, Node source, int forward, Consumer<Node> action) {
/*
* This iteration order is designed to be the opposite of the Vanilla shape
* update order, and is determined as follows:
* <br>
* 1. Each neighbor is identified by the step(s) you must take, starting at the
* source, to reach it. Each step is 1 block, thus the position of a neighbor is
* encoded by the direction(s) of the step(s), e.g. (right), (down), (up, left),
* etc.
* <br>
* 2. Neighbors are iterated over in pairs that lie on opposite sides of the
* source.
* <br>
* 3. Neighbors are iterated over in order of their distance from the source,
* moving outward. This means they are iterated over in 3 groups: direct
* neighbors first, then diagonal neighbors, and last are the far neighbors that
* are 2 blocks directly out.
* <br>
* 4. The order within each group is determined using the following basic order:
* { down, up, front, back, right, left }. This order was chosen because it
* converts to the following order of absolute directions when west is said to
* be 'forward': { down, up west, east, north, south } - this is the order of
* shape updates, with the vertical directions moved to the front.
*/
int rightward = (forward + 1) & 0b11;
int backward = (forward + 2) & 0b11;
int leftward = (forward + 3) & 0b11;
int downward = Directions.DOWN;
int upward = Directions.UP;
Node front = nodes.getNeighbor(source, forward);
Node right = nodes.getNeighbor(source, rightward);
Node back = nodes.getNeighbor(source, backward);
Node left = nodes.getNeighbor(source, leftward);
Node below = nodes.getNeighbor(source, downward);
Node above = nodes.getNeighbor(source, upward);
// direct neighbors (6)
action.accept(below);
action.accept(above);
action.accept(front);
action.accept(back);
action.accept(right);
action.accept(left);
// diagonal neighbors (12)
action.accept(nodes.getNeighbor(below, forward));
action.accept(nodes.getNeighbor(above, backward));
action.accept(nodes.getNeighbor(below, backward));
action.accept(nodes.getNeighbor(above, forward));
action.accept(nodes.getNeighbor(below, rightward));
action.accept(nodes.getNeighbor(above, leftward));
action.accept(nodes.getNeighbor(below, leftward));
action.accept(nodes.getNeighbor(above, rightward));
action.accept(nodes.getNeighbor(front, rightward));
action.accept(nodes.getNeighbor(back, leftward));
action.accept(nodes.getNeighbor(front, leftward));
action.accept(nodes.getNeighbor(back, rightward));
// far neighbors (6)
action.accept(nodes.getNeighbor(below, downward));
action.accept(nodes.getNeighbor(above, upward));
action.accept(nodes.getNeighbor(front, forward));
action.accept(nodes.getNeighbor(back, backward));
action.accept(nodes.getNeighbor(right, rightward));
action.accept(nodes.getNeighbor(left, leftward));
}
},
VERTICAL_FIRST_INWARD(
new int[][] {
new int[] { Directions.DOWN, Directions.UP, Directions.WEST , Directions.EAST , Directions.NORTH, Directions.SOUTH },
new int[] { Directions.DOWN, Directions.UP, Directions.NORTH, Directions.SOUTH, Directions.EAST , Directions.WEST },
new int[] { Directions.DOWN, Directions.UP, Directions.EAST , Directions.WEST , Directions.SOUTH, Directions.NORTH },
new int[] { Directions.DOWN, Directions.UP, Directions.SOUTH, Directions.NORTH, Directions.WEST , Directions.EAST }
},
new int[][] {
new int[] { Directions.WEST , Directions.EAST , Directions.NORTH, Directions.SOUTH },
new int[] { Directions.NORTH, Directions.SOUTH, Directions.EAST , Directions.WEST },
new int[] { Directions.EAST , Directions.WEST , Directions.SOUTH, Directions.NORTH },
new int[] { Directions.SOUTH, Directions.NORTH, Directions.WEST , Directions.EAST }
}
) {
@Override
public void forEachNeighbor(NodeProvider nodes, Node source, int forward, Consumer<Node> action) {
/*
* This iteration order is designed to be an inversion of the above update
* order, and is determined as follows:
* <br>
* 1. Each neighbor is identified by the step(s) you must take, starting at the
* source, to reach it. Each step is 1 block, thus the position of a neighbor is
* encoded by the direction(s) of the step(s), e.g. (right), (down), (up, left),
* etc.
* <br>
* 2. Neighbors are iterated over in pairs that lie on opposite sides of the
* source.
* <br>
* 3. Neighbors are iterated over in order of their distance from the source,
* moving inward. This means they are iterated over in 3 groups: neighbors that
* are 2 blocks directly out first, then diagonal neighbors, and last are direct
* neighbors.
* <br>
* 4. The order within each group is determined using the following basic order:
* { down, up, front, back, right, left }. This order was chosen because it
* converts to the following order of absolute directions when west is said to
* be 'forward': { down, up west, east, north, south } - this is the order of
* shape updates, with the vertical directions moved to the front.
*/
int rightward = (forward + 1) & 0b11;
int backward = (forward + 2) & 0b11;
int leftward = (forward + 3) & 0b11;
int downward = Directions.DOWN;
int upward = Directions.UP;
Node front = nodes.getNeighbor(source, forward);
Node right = nodes.getNeighbor(source, rightward);
Node back = nodes.getNeighbor(source, backward);
Node left = nodes.getNeighbor(source, leftward);
Node below = nodes.getNeighbor(source, downward);
Node above = nodes.getNeighbor(source, upward);
// far neighbors (6)
action.accept(nodes.getNeighbor(below, downward));
action.accept(nodes.getNeighbor(above, upward));
action.accept(nodes.getNeighbor(front, forward));
action.accept(nodes.getNeighbor(back, backward));
action.accept(nodes.getNeighbor(right, rightward));
action.accept(nodes.getNeighbor(left, leftward));
// diagonal neighbors (12)
action.accept(nodes.getNeighbor(below, forward));
action.accept(nodes.getNeighbor(above, backward));
action.accept(nodes.getNeighbor(below, backward));
action.accept(nodes.getNeighbor(above, forward));
action.accept(nodes.getNeighbor(below, rightward));
action.accept(nodes.getNeighbor(above, leftward));
action.accept(nodes.getNeighbor(below, leftward));
action.accept(nodes.getNeighbor(above, rightward));
action.accept(nodes.getNeighbor(front, rightward));
action.accept(nodes.getNeighbor(back, leftward));
action.accept(nodes.getNeighbor(front, leftward));
action.accept(nodes.getNeighbor(back, rightward));
// direct neighbors (6)
action.accept(below);
action.accept(above);
action.accept(front);
action.accept(back);
action.accept(right);
action.accept(left);
}
};
private final int[][] directNeighbors;
private final int[][] cardinalNeighbors;
private UpdateOrder(int[][] directNeighbors, int[][] cardinalNeighbors) {
this.directNeighbors = directNeighbors;
this.cardinalNeighbors = cardinalNeighbors;
}
public String id() {
return name().toLowerCase(Locale.ENGLISH);
}
public static UpdateOrder byId(String id) {
return valueOf(id.toUpperCase(Locale.ENGLISH));
}
public int[] directNeighbors(int forward) {
return directNeighbors[forward];
}
public int[] cardinalNeighbors(int forward) {
return cardinalNeighbors[forward];
}
/**
* Iterate over all neighboring nodes of the given source node. The iteration
* order is built from relative directions around the source, depending on the
* given 'forward' direction. This is an effort to eliminate any directional
* biases that would be emerge in rotationally symmetric circuits if the update
* order was built from absolute directions around the source.
* <br>
* Each update order must include the source's direct neighbors, but further
* neighbors may not be included.
*/
public abstract void forEachNeighbor(NodeProvider nodes, Node source, int forward, Consumer<Node> action);
}
|
alternate-current
|
src\main\java\alternate\current\wire\WireConnection.java
|
package alternate.current.wire;
/**
* This class represents a connection between some WireNode (the 'owner') and a
* neighboring WireNode. Two wires are considered to be connected if power can
* flow from one wire to the other (and/or vice versa).
*
* @author Space Walker
*/
public class WireConnection {
/** The connected wire. */
final WireNode wire;
/** Cardinal direction to the connected wire. */
final int iDir;
/** True if the owner of the connection can provide power to the connected wire. */
final boolean offer;
/** True if the connected wire can provide power to the owner of the connection. */
final boolean accept;
/** The next connection in the sequence. */
WireConnection next;
WireConnection(WireNode wire, int iDir, boolean offer, boolean accept) {
this.wire = wire;
this.iDir = iDir;
this.offer = offer;
this.accept = accept;
}
}
|
alternate-current
|
src\main\java\alternate\current\wire\WireConnectionManager.java
|
package alternate.current.wire;
import java.util.Arrays;
import java.util.function.Consumer;
import alternate.current.wire.WireHandler.Directions;
import alternate.current.wire.WireHandler.NodeProvider;
public class WireConnectionManager {
/** The owner of these connections. */
final WireNode owner;
/** The first connection for each cardinal direction. */
private final WireConnection[] heads;
private WireConnection head;
private WireConnection tail;
/** The total number of connections. */
int total;
/**
* A 4 bit number that encodes which in direction(s) the owner has connections
* to other wires.
*/
private int flowTotal;
/** The direction of flow based connections to other wires. */
int iFlowDir;
WireConnectionManager(WireNode owner) {
this.owner = owner;
this.heads = new WireConnection[Directions.HORIZONTAL.length];
this.total = 0;
this.flowTotal = 0;
this.iFlowDir = -1;
}
void set(NodeProvider nodes) {
if (total > 0) {
clear();
}
boolean belowIsConductor = nodes.getNeighbor(owner, Directions.DOWN).isConductor();
boolean aboveIsConductor = nodes.getNeighbor(owner, Directions.UP).isConductor();
for (int iDir = 0; iDir < Directions.HORIZONTAL.length; iDir++) {
Node neighbor = nodes.getNeighbor(owner, iDir);
if (neighbor.isWire()) {
add(neighbor.asWire(), iDir, true, true);
} else {
boolean sideIsConductor = neighbor.isConductor();
if (!sideIsConductor) {
Node node = nodes.getNeighbor(neighbor, Directions.DOWN);
if (node.isWire()) {
add(node.asWire(), iDir, belowIsConductor, true);
}
}
if (!aboveIsConductor) {
Node node = nodes.getNeighbor(neighbor, Directions.UP);
if (node.isWire()) {
add(node.asWire(), iDir, true, sideIsConductor);
}
}
}
}
if (total > 0) {
iFlowDir = WireHandler.FLOW_IN_TO_FLOW_OUT[flowTotal];
}
}
private void clear() {
Arrays.fill(heads, null);
head = null;
tail = null;
total = 0;
flowTotal = 0;
iFlowDir = -1;
}
private void add(WireNode wire, int iDir, boolean offer, boolean accept) {
add(new WireConnection(wire, iDir, offer, accept));
}
private void add(WireConnection connection) {
if (head == null) {
head = connection;
tail = connection;
} else {
tail.next = connection;
tail = connection;
}
total++;
if (heads[connection.iDir] == null) {
heads[connection.iDir] = connection;
flowTotal |= (1 << connection.iDir);
}
}
/**
* Iterate over all connections. Use this method if the iteration order is not
* important.
*/
void forEach(Consumer<WireConnection> consumer) {
for (WireConnection c = head; c != null; c = c.next) {
consumer.accept(c);
}
}
/**
* Iterate over all connections. Use this method if the iteration order is
* important.
*/
void forEach(Consumer<WireConnection> consumer, UpdateOrder updateOrder, int iFlowDir) {
for (int iDir : updateOrder.cardinalNeighbors(iFlowDir)) {
for (WireConnection c = heads[iDir]; c != null && c.iDir == iDir; c = c.next) {
consumer.accept(c);
}
}
}
}
|
alternate-current
|
src\main\java\alternate\current\wire\WireHandler.java
|
package alternate.current.wire;
import java.util.Iterator;
import java.util.Queue;
//import alternate.current.AlternateCurrentMod;
//import alternate.current.util.profiler.Profiler;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap.Entry;
import it.unimi.dsi.fastutil.longs.Long2ObjectMaps;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.redstone.InstantNeighborUpdater;
import net.minecraft.world.level.redstone.NeighborUpdater;
import net.minecraft.world.level.redstone.Orientation;
import net.minecraft.world.level.redstone.Redstone;
import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess;
/**
* This class handles power changes for redstone wire. The algorithm was
* designed with the following goals in mind:
* <br>
* 1. Minimize the number of times a wire checks its surroundings to determine
* its power level.
* <br>
* 2. Minimize the number of block and shape updates emitted.
* <br>
* 3. Emit block and shape updates in a deterministic, non-locational order,
* fixing bug MC-11193.
*
* <p>
* In Vanilla redstone wire is laggy because it fails on points 1 and 2.
*
* <p>
* Redstone wire updates recursively and each wire calculates its power level in
* isolation rather than in the context of the network it is a part of. This
* means a wire in a grid can change its power level over half a dozen times
* before settling on its final value. This problem used to be worse in 1.13 and
* below, where a wire would only decrease its power level by 1 at a time.
*
* <p>
* In addition to this, a wire emits 42 block updates and up to 22 shape updates
* each time it changes its power level.
*
* <p>
* Of those 42 block updates, 6 are to itself, which are thus not only
* redundant, but a big source of lag, since those cause the wire to
* unnecessarily re-calculate its power level. A block only has 24 neighbors
* within a Manhattan distance of 2, meaning 12 of the remaining 36 block
* updates are duplicates and thus also redundant.
*
* <p>
* Of the 22 shape updates, only 6 are strictly necessary. The other 16 are sent
* to blocks diagonally above and below. These are necessary if a wire changes
* its connections, but not when it changes its power level.
*
* <p>
* Redstone wire in Vanilla also fails on point 3, though this is more of a
* quality-of-life issue than a lag issue. The recursive nature in which it
* updates, combined with the location-dependent order in which each wire
* updates its neighbors, makes the order in which neighbors of a wire network
* are updated incredibly inconsistent and seemingly random.
*
* <p>
* Alternate Current fixes each of these problems as follows.
*
* <p>
* 1. To make sure a wire calculates its power level as little as possible, we
* remove the recursive nature in which redstone wire updates in Vanilla.
* Instead, we build a network of connected wires, find those wires that receive
* redstone power from "outside" the network, and spread the power from there.
* This has a few advantages:
* <br>
* - Each wire checks for power from non-wire components at most once, and from
* nearby wires just twice.
* <br>
* - Each wire only sets its power level in the world once. This is important,
* because calls to Level.setBlock are even more expensive than calls to
* Level.getBlockState.
*
* <p>
* 2. There are 2 obvious ways in which we can reduce the number of block and
* shape updates.
* <br>
* - Get rid of the 18 redundant block updates and 16 redundant shape updates,
* so each wire only emits 24 block updates and 6 shape updates whenever it
* changes its power level.
* <br>
* - Only emit block updates and shape updates once a wire reaches its final
* power level, rather than at each intermediary stage.
* <br>
* For an individual wire, these two optimizations are the best you can do, but
* for an entire grid, you can do better!
*
* <p>
* Since we calculate the power of the entire network, sending block and shape
* updates to the wires in it is redundant. Removing those updates can reduce
* the number of block and shape updates by up to 20%.
*
* <p>
* 3. To make the order of block updates to neighbors of a network
* deterministic, the first thing we must do is to replace the location-
* dependent order in which a wire updates its neighbors. Instead, we base it on
* the direction of power flow. This part of the algorithm was heavily inspired
* by theosib's 'RedstoneWireTurbo', which you can read more about in theosib's
* comment on Mojira <a href="https://bugs.mojang.com/browse/MC-81098?focusedCommentId=420777&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-420777">here</a>
* or by checking out its implementation in carpet mod <a href="https://github.com/gnembon/fabric-carpet/blob/master/src/main/java/carpet/helpers/RedstoneWireTurbo.java">here</a>.
*
* <p>
* The idea is to determine the direction of power flow through a wire based on
* the power it receives from neighboring wires. For example, if the only power
* a wire receives is from a neighboring wire to its west, it can be said that
* the direction of power flow through the wire is east.
*
* <p>
* We make the order of block updates to neighbors of a wire depend on what is
* determined to be the direction of power flow. This not only removes
* locationality entirely, it even removes directionality in a large number of
* cases. Unlike in 'RedstoneWireTurbo', however, I have decided to keep a
* directional element in ambiguous cases, rather than to introduce randomness,
* though this is trivial to change.
*
* <p>
* While this change fixes the block update order of individual wires, we must
* still address the overall block update order of a network. This turns out to
* be a simple fix, because of a change we made earlier: we search through the
* network for wires that receive power from outside it, and spread the power
* from there. If we make each wire transmit its power to neighboring wires in
* an order dependent on the direction of power flow, we end up with a
* non-locational and largely non-directional wire update order.
*
* @author Space Walker
*/
public class WireHandler {
public static class Directions {
public static final Direction[] ALL = { Direction.WEST, Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.DOWN, Direction.UP };
public static final Direction[] HORIZONTAL = { Direction.WEST, Direction.NORTH, Direction.EAST, Direction.SOUTH };
// Indices for the arrays above.
// The cardinal directions are ordered clockwise. This allows
// for conversion between relative and absolute directions
// ('left' 'right' vs 'east' 'west') with simple arithmetic:
// If some Direction index 'iDir' is considered 'forward', then
// '(iDir + 1) & 0b11' is 'right', '(iDir + 2) & 0b11' is 'backward', etc.
public static final int WEST = 0b000; // 0
public static final int NORTH = 0b001; // 1
public static final int EAST = 0b010; // 2
public static final int SOUTH = 0b011; // 3
public static final int DOWN = 0b100; // 4
public static final int UP = 0b101; // 5
public static int iOpposite(int iDir) {
return iDir ^ (0b10 >>> (iDir >>> 2));
}
public static int index(Direction dir) {
for (int i = 0; i < ALL.length; i++) {
if (dir == ALL[i]) {
return i;
}
}
return -1;
}
}
/**
* This conversion table takes in information about incoming flow, and outputs
* the determined outgoing flow.
*
* <p>
* The input is a 4 bit number that encodes the incoming flow. Each bit
* represents a cardinal direction, and when it is 'on', there is flow in that
* direction.
*
* <p>
* The output is a single Direction index, or -1 for ambiguous cases.
*
* <p>
* The outgoing flow is determined as follows:
*
* <p>
* If there is just 1 direction of incoming flow, that direction will be the
* direction of outgoing flow.
*
* <p>
* If there are 2 directions of incoming flow, and these directions are not each
* other's opposites, the direction that is 'more clockwise' will be the
* direction of outgoing flow. More precisely, the direction that is 1 clockwise
* turn from the other is picked.
*
* <p>
* If there are 3 directions of incoming flow, the two opposing directions
* cancel each other out, and the remaining direction will be the direction of
* outgoing flow.
*
* <p>
* In all other cases, the flow is completely ambiguous.
*/
static final int[] FLOW_IN_TO_FLOW_OUT = {
-1, // 0b0000: - -> x
Directions.WEST, // 0b0001: west -> west
Directions.NORTH, // 0b0010: north -> north
Directions.NORTH, // 0b0011: west/north -> north
Directions.EAST, // 0b0100: east -> east
-1, // 0b0101: west/east -> x
Directions.EAST, // 0b0110: north/east -> east
Directions.NORTH, // 0b0111: west/north/east -> north
Directions.SOUTH, // 0b1000: south -> south
Directions.WEST, // 0b1001: west/south -> west
-1, // 0b1010: north/south -> x
Directions.WEST, // 0b1011: west/north/south -> west
Directions.SOUTH, // 0b1100: east/south -> south
Directions.SOUTH, // 0b1101: west/east/south -> south
Directions.EAST, // 0b1110: north/east/south -> east
-1, // 0b1111: west/north/east/south -> x
};
/**
* Update order of shape updates, matching that of Vanilla.
*/
static final int[] SHAPE_UPDATE_ORDER = { Directions.WEST, Directions.EAST, Directions.NORTH, Directions.SOUTH, Directions.DOWN, Directions.UP };
private static final int POWER_MIN = Redstone.SIGNAL_MIN;
private static final int POWER_MAX = Redstone.SIGNAL_MAX;
private static final int POWER_STEP = 1;
// If Vanilla will ever multi-thread the ticking of levels, there should
// be only one WireHandler per level, in case redstone updates in multiple
// levels at the same time. There are already mods that add multi-threading
// as well.
private final ServerLevel level;
private final Config config;
/** Map of wires and neighboring blocks. */
private final Long2ObjectMap<Node> nodes;
/** Queue for the breadth-first search through the network. */
private final Queue<WireNode> search;
/** Queue of updates to wires and neighboring blocks. */
private final Queue<Node> updates;
private final NeighborUpdater neighborUpdater;
// Rather than creating new nodes every time a network is updated we keep
// a cache of nodes that can be re-used.
private Node[] nodeCache;
private int nodeCount;
/** Is this WireHandler currently working through the update queue? */
private boolean updating;
public WireHandler(ServerLevel level, LevelStorageAccess storage) {
this.level = level;
this.config = Config.forLevel(level, storage);
this.config.load();
this.nodes = new Long2ObjectOpenHashMap<>();
this.search = new SimpleQueue();
this.updates = new PriorityQueue();
this.neighborUpdater = new InstantNeighborUpdater(this.level);
this.nodeCache = new Node[16];
this.fillNodeCache(0, 16);
}
public Config getConfig() {
return config;
}
private Node getOrAddNode(BlockPos pos) {
// just pass in null, then the state will only be retrieved
// if there is no node as this position yet
return getOrAddNode(pos, null);
}
/**
* Retrieve the {@link alternate.current.wire.Node Node} that represents the
* block at the given position in the level.
*/
private Node getOrAddNode(BlockPos pos, BlockState state) {
return nodes.compute(pos.asLong(), (key, node) -> {
if (node == null) {
// If there is not yet a node at this position, retrieve and
// update one from the cache.
return getNextNode(pos, state != null ? state : level.getBlockState(pos));
}
if (node.invalid) {
return revalidateNode(node);
}
return node;
});
}
/**
* Remove and return the {@link alternate.current.wire.Node Node} at the given
* position.
*/
private Node removeNode(BlockPos pos) {
return nodes.remove(pos.asLong());
}
/**
* Return a node that represents the given position and block state. If it is a
* wire, then create a new {@link alternate.current.wire.WireNode WireNode}.
* Otherwise, grab the next {@link alternate.current.wire.Node Node} from the
* cache and update it.
*/
private Node getNextNode(BlockPos pos, BlockState state) {
return state.is(Blocks.REDSTONE_WIRE) ? new WireNode(level, pos, state) : getNextNode().set(pos, state, true);
}
/**
* Grab the first unused node from the cache. If all of the cache is already in
* use, increase it in size first.
*/
private Node getNextNode() {
if (nodeCount == nodeCache.length) {
increaseNodeCache();
}
return nodeCache[nodeCount++];
}
private void increaseNodeCache() {
Node[] oldCache = nodeCache;
nodeCache = new Node[oldCache.length << 1];
for (int index = 0; index < oldCache.length; index++) {
nodeCache[index] = oldCache[index];
}
fillNodeCache(oldCache.length, nodeCache.length);
}
private void fillNodeCache(int start, int end) {
for (int index = start; index < end; index++) {
nodeCache[index] = new Node(level);
}
}
/**
* Try to revalidate the given node by looking at the block state that is
* occupying its position. If the given node is a wire but the block state is
* not, or vice versa, a new node must be created/grabbed from the cache.
* Otherwise, the node can be quickly revalidated with the new block state.
*/
private Node revalidateNode(Node node) {
if (!node.invalid) {
return node;
}
BlockPos pos = node.pos;
BlockState state = level.getBlockState(pos);
boolean wasWire = node.isWire();
boolean isWire = state.is(Blocks.REDSTONE_WIRE);
if (wasWire != isWire) {
return getNextNode(pos, state);
}
node.invalid = false;
if (isWire) {
// No need to update the block state of this wire - it will grab
// the current block state just before setting power anyway.
WireNode wire = node.asWire();
wire.root = false;
wire.discovered = false;
wire.searched = false;
} else {
node.set(pos, state, false);
}
return node;
}
/**
* Retrieve the neighbor of a node in the given direction and create a link
* between the two nodes if they are not yet linked. This link makes accessing
* neighbors of a node signficantly faster.
*/
private Node getNeighbor(Node node, int iDir) {
Node neighbor = node.neighbors[iDir];
if (neighbor == null || neighbor.invalid) {
Direction dir = Directions.ALL[iDir];
BlockPos pos = node.pos.relative(dir);
Node oldNeighbor = neighbor;
neighbor = getOrAddNode(pos);
if (neighbor != oldNeighbor) {
int iOpp = Directions.iOpposite(iDir);
node.neighbors[iDir] = neighbor;
neighbor.neighbors[iOpp] = node;
}
}
return neighbor;
}
/**
* This method should be called whenever a wire receives a block update.
*/
public boolean onWireUpdated(BlockPos pos, BlockState state, Orientation orientation) {
Node node = getOrAddNode(pos, state);
if (!node.isWire()) {
return false; // we should never get here
}
WireNode wire = node.asWire();
invalidate();
revalidateNode(wire);
findRoots(wire, orientation);
tryUpdate();
return true;
}
/**
* This method should be called whenever a wire is placed.
*/
public void onWireAdded(BlockPos pos, BlockState state) {
Node node = getOrAddNode(pos, state);
if (!node.isWire()) {
return; // we should never get here
}
WireNode wire = node.asWire();
wire.added = true;
invalidate();
revalidateNode(wire);
findRoot(wire);
tryUpdate();
}
/**
* This method should be called whenever a wire is removed.
*/
public void onWireRemoved(BlockPos pos, BlockState state) {
Node node = removeNode(pos);
WireNode wire;
if (node == null || !node.isWire()) {
wire = new WireNode(level, pos, state);
} else {
wire = node.asWire();
}
wire.invalid = true;
wire.removed = true;
// If these fields are set to 'true', the removal of this wire was part of
// already ongoing power changes, so we can exit early here.
if (updating && wire.shouldBreak) {
return;
}
invalidate();
revalidateNode(wire);
findRoot(wire);
tryUpdate();
}
/**
* The nodes map is a snapshot of the state of the world. It becomes invalid
* when power changes are carried out, since the block and shape updates can
* lead to block changes. If these block changes cause the network to be updated
* again every node must be invalidated, and revalidated before it is used
* again. This ensures the power calculations of the network are accurate.
*/
private void invalidate() {
if (updating && !nodes.isEmpty()) {
Iterator<Entry<Node>> it = Long2ObjectMaps.fastIterator(nodes);
while (it.hasNext()) {
Entry<Node> entry = it.next();
Node node = entry.getValue();
node.invalid = true;
}
}
}
/**
* Look for wires at and around the given position that are in an invalid state
* and require power changes. These wires are called 'roots' because it is only
* when these wires change power level that neighboring wires must adjust as
* well.
*
* <p>
* While it is strictly only necessary to check the wire at the given position,
* if that wire is part of a network, it is beneficial to check its surroundings
* for other wires that require power changes. This is because a network can
* receive power at multiple points. Consider the following setup:
*
* <p>
* (top-down view, W = wire, L = lever, _ = air/other)
* <br> {@code _ _ W _ _ }
* <br> {@code _ W W W _ }
* <br> {@code W W L W W }
* <br> {@code _ W W W _ }
* <br> {@code _ _ W _ _ }
*
* <p>
* The lever powers four wires in the network at once. If this is identified
* correctly, the entire network can (un)power at once. While it is not
* practical to cover every possible situation where a network is (un)powered
* from multiple points at once, checking for common cases like the one
* described above is relatively straight-forward.
*/
private void findRoots(WireNode wire, Orientation orientation) {
// horizontal direction bias for update order purposes
int iDirBias = -1;
if (orientation != null) {
Direction dir = orientation.getFront().getAxis().isHorizontal()
? orientation.getFront()
: orientation.getUp();
iDirBias = Directions.index(dir);
}
findRoot(wire, iDirBias);
// If the wire at the given position is not in an invalid state
// we can exit early.
if (!wire.searched) {
return;
}
if (orientation == null) {
// no neighborChanged orientation present, look around in all sides
for (int iDir : config.getUpdateOrder().directNeighbors(wire.iFlowDir)) {
findRootsAround(wire, iDir);
}
} else {
// use the orientation from the neighborChanged update to look for roots only behind
findRootsAround(wire, Directions.index(orientation.getFront().getOpposite()));
}
}
/**
* Look for wires around a neighbor of the given wire that require power changes.
*/
private void findRootsAround(WireNode wire, int iDir) {
Node node = getNeighbor(wire, iDir);
if (node.isConductor() || node.isSignalSource()) {
for (int iSide : config.getUpdateOrder().cardinalNeighbors(wire.iFlowDir)) {
Node neighbor = getNeighbor(node, iSide);
if (neighbor.isWire()) {
findRoot(neighbor.asWire(), iSide);
}
}
}
}
private void findRoot(WireNode wire) {
findRoot(wire, -1);
}
/**
* Check if the given wire requires power changes. If it does, queue it for the
* breadth-first search as a root.
*/
private void findRoot(WireNode wire, int iDiscoveryDir) {
// Each wire only needs to be checked once.
if (wire.discovered) {
return;
}
discover(wire);
findExternalPower(wire);
findPower(wire, false);
if (needsUpdate(wire)) {
searchRoot(wire, iDiscoveryDir);
}
}
/**
* Prepare the given wire for the breadth-first search. This means:
* <br>
* - Check if the wire should break. Rather than breaking the wire right away,
* its effects are integrated into the power calculations.
* <br>
* - Reset the virtual and external power.
* <br>
* - Find connections to neighboring wires.
*/
private void discover(WireNode wire) {
if (wire.discovered) {
return;
}
wire.discovered = true;
wire.searched = false;
if (!wire.removed && !wire.shouldBreak && !wire.state.canSurvive(level, wire.pos)) {
wire.shouldBreak = true;
}
wire.virtualPower = wire.currentPower;
wire.externalPower = POWER_MIN - 1;
wire.connections.set(this::getNeighbor);
}
/**
* Determine the power level the given wire receives from the blocks around it.
* Power from non-wire components only needs to be computed if power from
* neighboring wires has decreased, so as to determine how low the power of the
* wire can fall.
*/
private void findPower(WireNode wire, boolean ignoreSearched) {
// As wire power is (re-)computed, flow information must be reset.
wire.virtualPower = wire.externalPower;
wire.flowIn = 0;
// If the wire is removed or going to break, its power level should always be
// the minimum value. This is because it (effectively) no longer exists, so
// cannot provide any power to neighboring wires.
if (wire.removed || wire.shouldBreak) {
return;
}
// Power received from neighboring wires will never exceed POWER_MAX -
// POWER_STEP, so if the external power is already larger than or equal to
// that, there is no need to check for power from neighboring wires.
if (wire.externalPower < (POWER_MAX - POWER_STEP)) {
findWirePower(wire, ignoreSearched);
}
}
/**
* Determine the power the given wire receives from connected neighboring wires
* and update the virtual power accordingly.
*/
private void findWirePower(WireNode wire, boolean ignoreSearched) {
wire.connections.forEach(connection -> {
if (!connection.accept) {
return;
}
WireNode neighbor = connection.wire;
if (!ignoreSearched || !neighbor.searched) {
int power = Math.max(POWER_MIN, neighbor.virtualPower - POWER_STEP);
int iOpp = Directions.iOpposite(connection.iDir);
wire.offerPower(power, iOpp);
}
});
}
/**
* Determine the redstone signal the given wire receives from non-wire
* components and update the virtual power accordingly.
*/
private void findExternalPower(WireNode wire) {
// If the wire is removed or going to break, its power level should always be
// the minimum value. Thus external power need not be computed.
// In other cases external power need only be computed once.
if (wire.removed || wire.shouldBreak || wire.externalPower >= POWER_MIN) {
return;
}
wire.externalPower = getExternalPower(wire);
if (wire.externalPower > wire.virtualPower) {
wire.virtualPower = wire.externalPower;
}
}
/**
* Determine the redstone signal the given wire receives from non-wire
* components.
*/
private int getExternalPower(WireNode wire) {
int power = POWER_MIN;
for (int iDir = 0; iDir < Directions.ALL.length; iDir++) {
Node neighbor = getNeighbor(wire, iDir);
// Power from wires is handled separately.
if (neighbor.isWire()) {
continue;
}
// Since 1.16 there is a block that is both a conductor and a signal
// source: the target block!
if (neighbor.isConductor()) {
power = Math.max(power, getDirectSignalTo(wire, neighbor));
}
if (neighbor.isSignalSource()) {
power = Math.max(power, neighbor.state.getSignal(level, neighbor.pos, Directions.ALL[iDir]));
}
if (power >= POWER_MAX) {
return POWER_MAX;
}
}
return power;
}
/**
* Determine the direct signal the given wire receives from neighboring blocks
* through the given conductor node.
*/
private int getDirectSignalTo(WireNode wire, Node node) {
int power = POWER_MIN;
for (int iDir = 0; iDir < Directions.ALL.length; iDir++) {
Node neighbor = getNeighbor(node, iDir);
if (neighbor.isSignalSource()) {
power = Math.max(power, neighbor.state.getDirectSignal(level, neighbor.pos, Directions.ALL[iDir]));
if (power >= POWER_MAX) {
return POWER_MAX;
}
}
}
return power;
}
/**
* Check if the given wire needs to update its state in the world.
*/
private boolean needsUpdate(WireNode wire) {
return wire.removed || wire.shouldBreak || wire.virtualPower != wire.currentPower;
}
/**
* Queue the given wire for the breadth-first search as a root.
*/
private void searchRoot(WireNode wire, int iBackupFlowDir) {
if (wire.connections.iFlowDir >= 0) {
// power flow direction takes precedent
iBackupFlowDir = wire.connections.iFlowDir;
} else if (iBackupFlowDir < 0) {
// use default value if none is given
iBackupFlowDir = 0;
}
search(wire, true, iBackupFlowDir);
}
/**
* Queue the given wire for the breadth-first search and set a backup flow
* direction.
*/
private void search(WireNode wire, boolean root, int iBackupFlowDir) {
search.offer(wire);
wire.root = root;
wire.searched = true;
// Normally the flow is not set until the power level is updated. However,
// in networks with multiple power sources the update order between them
// depends on which was discovered first. To make this less prone to
// directionality, each wire node is given a 'backup' flow. For roots, this
// is the determined flow of their connections. For non-roots this is the
// direction from which they were discovered.
wire.iFlowDir = iBackupFlowDir;
}
private void tryUpdate() {
if (!search.isEmpty()) {
update();
}
if (!updating) {
nodes.clear();
nodeCount = 0;
}
}
/**
* Update the network and neighboring blocks. This is done in 3 steps.
*
* <p>
* <b>1. Search through the network</b>
* <br>
* Conduct a breadth-first search around the roots to find wires that are in an
* invalid state and need power changes.
*
* <p>
* <b>2. Depower the network</b>
* <br>
* Depower all wires in the network. This allows power to be spread most
* efficiently.
*
* <p>
* <b>3. Power the network</b>
* <br>
* Work through the update queue, setting the new power level of each wire and
* updating neighboring blocks. After a wire has updated its power level, it
* will emit shape updates and queue updates for neighboring wires and blocks.
*/
private void update() {
// The profiler keeps track of how long various parts of the algorithm take.
// It is only here for debugging purposes, and is commented out in production.
// Profiler profiler = AlternateCurrentMod.createProfiler();
// profiler.start();
// Search through the network for wires that need power changes. This includes
// the roots as well as any wires that will be affected by power changes to
// those roots.
// profiler.push("search network");
searchNetwork();
// Depower all the wires in the network.
// profiler.swap("depower network");
depowerNetwork();
// Bring each wire up to its new power level and update neighboring blocks.
// profiler.swap("power network");
try {
powerNetwork();
} catch (Throwable t) {
// If anything goes wrong while carrying out power changes, this field must
// be reset to 'false', or the wire handler will be locked out of carrying
// out power changes until the world is reloaded.
updating = false;
throw t;
// } finally {
// profiler.pop();
// profiler.end();
}
}
/**
* Search through the network for wires that are in an invalid state and need
* power changes. These wires are added to the end of the queue, so that their
* neighbors can be searched next.
*/
private void searchNetwork() {
for (WireNode wire : search) {
// The order in which wires are searched will influence the order in
// which they update their power levels.
wire.connections.forEach(connection -> {
if (!connection.offer) {
return;
}
WireNode neighbor = connection.wire;
if (neighbor.searched) {
return;
}
discover(neighbor);
findPower(neighbor, false);
// If power from neighboring wires has decreased, check for power
// from non-wire components so as to determine how low power can
// fall.
if (neighbor.virtualPower < neighbor.currentPower) {
findExternalPower(neighbor);
}
if (needsUpdate(neighbor)) {
search(neighbor, false, connection.iDir);
}
}, config.getUpdateOrder(), wire.iFlowDir);
}
}
/**
* Depower all wires in the network so that power can be spread from the power
* sources.
*/
private void depowerNetwork() {
while (!search.isEmpty()) {
WireNode wire = search.poll();
findPower(wire, true);
if (wire.root || wire.removed || wire.shouldBreak || wire.virtualPower > POWER_MIN) {
queueWire(wire);
} else {
// Wires that do not receive any power do not queue power changes
// until they are offered power from a neighboring wire. To ensure
// that they accept any power from neighboring wires and thus queue
// their power changes, their virtual power is set to below the
// minimum.
wire.virtualPower--;
}
}
}
/**
* Work through the update queue, setting the new power level of each wire, then
* queueing updates to connected wires and neighboring blocks.
*/
private void powerNetwork() {
// If an instantaneous update chain causes updates to another network
// (or the same network in another place), new power changes will be
// integrated into the already ongoing power queue, so we can exit early
// here.
if (updating) {
return;
}
updating = true;
while (!updates.isEmpty()) {
Node node = updates.poll();
if (node.isWire()) {
WireNode wire = node.asWire();
if (!needsUpdate(wire)) {
continue;
}
findPowerFlow(wire);
transmitPower(wire);
if (wire.setPower()) {
queueNeighbors(wire);
// If the wire was newly placed or removed, shape updates have
// already been emitted. However, unlike before 1.19, neighbor
// updates are now queued, so to preserve behavior parity with
// previous versions, we emit extra shape updates here to
// notify neighboring observers.
updateNeighborShapes(wire);
}
} else {
WireNode neighborWire = node.neighborWire;
if (neighborWire != null) {
BlockPos neighborPos = neighborWire.pos;
Block neighborBlock = neighborWire.state.getBlock();
updateBlock(node, neighborPos, neighborBlock);
}
}
}
updating = false;
}
/**
* Use the information of incoming power flow to determine the direction of
* power flow through this wire. If that flow is ambiguous, try to use a flow
* direction based on connections to neighboring wires. If that is also
* ambiguous, use the backup value that was set when the wire was first added to
* the network.
*/
private void findPowerFlow(WireNode wire) {
int flow = FLOW_IN_TO_FLOW_OUT[wire.flowIn];
if (flow >= 0) {
wire.iFlowDir = flow;
} else if (wire.connections.iFlowDir >= 0) {
wire.iFlowDir = wire.connections.iFlowDir;
}
}
/**
* Transmit power from the given wire to neighboring wires and queue updates to
* those wires.
*/
private void transmitPower(WireNode wire) {
wire.connections.forEach(connection -> {
if (!connection.offer) {
return;
}
WireNode neighbor = connection.wire;
int power = Math.max(POWER_MIN, wire.virtualPower - POWER_STEP);
int iDir = connection.iDir;
if (neighbor.offerPower(power, iDir)) {
queueWire(neighbor);
}
}, config.getUpdateOrder(), wire.iFlowDir);
}
/**
* Emit shape updates around the given wire.
*/
private void updateNeighborShapes(WireNode wire) {
BlockPos wirePos = wire.pos;
BlockState wireState = wire.state;
for (int iDir : SHAPE_UPDATE_ORDER) {
Node neighbor = getNeighbor(wire, iDir);
// Shape updates to redstone wire are very expensive, and should never happen
// as a result of power changes anyway, while shape updates to air do nothing.
// The current block state at this position *could* be wrong, but if you somehow
// manage to place a block where air used to be during the execution of a shape
// update I am very impressed and you deserve to have some broken behavior.
if (!neighbor.isWire() && !neighbor.state.isAir()) {
int iOpp = Directions.iOpposite(iDir);
Direction opp = Directions.ALL[iOpp];
updateShape(neighbor, opp, wirePos, wireState);
}
}
}
private void updateShape(Node node, Direction dir, BlockPos neighborPos, BlockState neighborState) {
neighborUpdater.shapeUpdate(dir, neighborState, node.pos, neighborPos, Block.UPDATE_CLIENTS, 512);
}
/**
* Queue block updates to nodes around the given wire.
*/
private void queueNeighbors(WireNode wire) {
config.getUpdateOrder().forEachNeighbor(this::getNeighbor, wire, wire.iFlowDir, neighbor -> queueNeighbor(neighbor, wire));
}
/**
* Queue the given node for an update from the given neighboring wire.
*/
private void queueNeighbor(Node node, WireNode neighborWire) {
// Updates to wires are queued when power is transmitted.
// While this check makes sure wires in the network are not given block
// updates, it also prevents block updates to wires in neighboring networks.
// While this should not make a difference in theory, in practice, it is
// possible to force a network into an invalid state without updating it, even
// if it is relatively obscure.
// While I was willing to make this compromise in return for some significant
// performance gains in certain setups, if you are not, you can add all the
// positions of the network to a set and filter out block updates to wires in
// the network that way.
// Block updates to air do nothing, so those are skipped as well.
// The current block state at this position *could* be wrong, but if you somehow
// manage to place a block where air used to be during the execution of a block
// update I am very impressed and you deserve to have some broken behavior.
if (!node.isWire() && !node.state.isAir()) {
node.neighborWire = neighborWire;
updates.offer(node);
}
}
/**
* Queue the given wire for a power change. If the wire does not need a power
* change (perhaps because its power has already changed), transmit power to
* neighboring wires.
*/
private void queueWire(WireNode wire) {
if (needsUpdate(wire)) {
updates.offer(wire);
} else {
findPowerFlow(wire);
transmitPower(wire);
}
}
/**
* Emit a block update to the given node.
*/
private void updateBlock(Node node, BlockPos neighborPos, Block neighborBlock) {
// redstone wire is the only block that uses the neighborChanged orientation
// so leaving it as null should not be an issue
neighborUpdater.neighborChanged(node.pos, neighborBlock, null);
}
@FunctionalInterface
public static interface NodeProvider {
public Node getNeighbor(Node node, int iDir);
}
}
|
alternate-current
|
src\main\java\alternate\current\wire\WireNode.java
|
package alternate.current.wire;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.Mth;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.RedStoneWireBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.redstone.Redstone;
/**
* A WireNode is a Node that represents a wire in the world. It stores all the
* information about the wire that the WireHandler needs to calculate power
* changes.
*
* @author Space Walker
*/
public class WireNode extends Node {
final WireConnectionManager connections;
/** The power level this wire currently holds in the world. */
int currentPower;
/**
* While calculating power changes for a network, this field is used to keep
* track of the power level this wire should have.
*/
int virtualPower;
/** The power level received from non-wire components. */
int externalPower;
/**
* A 4-bit number that keeps track of the power flow of the wires that give this
* wire its power level.
*/
int flowIn;
/** The direction of power flow, based on the incoming flow. */
int iFlowDir;
boolean added;
boolean removed;
boolean shouldBreak;
boolean root;
boolean discovered;
boolean searched;
/** The next wire in the simple queue. */
WireNode next_wire;
WireNode(ServerLevel level, BlockPos pos, BlockState state) {
super(level);
this.pos = pos.immutable();
this.state = state;
this.connections = new WireConnectionManager(this);
this.virtualPower = this.currentPower = this.state.getValue(RedStoneWireBlock.POWER);
this.priority = priority();
}
@Override
Node set(BlockPos pos, BlockState state, boolean clearNeighbors) {
throw new UnsupportedOperationException("Cannot update a WireNode!");
}
@Override
int priority() {
return Mth.clamp(virtualPower, Redstone.SIGNAL_MIN, Redstone.SIGNAL_MAX);
}
@Override
public boolean isWire() {
return true;
}
@Override
public WireNode asWire() {
return this;
}
boolean offerPower(int power, int iDir) {
if (removed || shouldBreak) {
return false;
}
if (power == virtualPower) {
flowIn |= (1 << iDir);
return false;
}
if (power > virtualPower) {
virtualPower = power;
flowIn = (1 << iDir);
return true;
}
return false;
}
boolean setPower() {
if (removed) {
return true;
}
state = level.getBlockState(pos);
if (!state.is(Blocks.REDSTONE_WIRE)) {
return false; // we should never get here
}
if (shouldBreak) {
Block.dropResources(state, level, pos);
level.setBlock(pos, Blocks.AIR.defaultBlockState(), Block.UPDATE_CLIENTS);
return true;
}
currentPower = Mth.clamp(virtualPower, Redstone.SIGNAL_MIN, Redstone.SIGNAL_MAX);
state = state.setValue(RedStoneWireBlock.POWER, currentPower);
return LevelHelper.setWireState(level, pos, state, added);
}
}
|
alternate-current
|
src\main\java\alternate\current\interfaces\mixin\IServerLevel.java
|
package alternate.current.interfaces.mixin;
import alternate.current.wire.WireHandler;
public interface IServerLevel {
WireHandler alternate_current$getWireHandler();
}
|
alternate-current
|
src\main\java\alternate\current\util\profiler\ACProfiler.java
|
package alternate.current.util.profiler;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import org.apache.logging.log4j.Logger;
import alternate.current.AlternateCurrentMod;
public class ACProfiler implements Profiler {
private static final Logger LOGGER = AlternateCurrentMod.LOGGER;
private final Stack<Integer> indexStack;
private final List<String> locations;
private final List<Long> times;
private boolean started;
public ACProfiler() {
this.indexStack = new Stack<>();
this.locations = new ArrayList<>();
this.times = new ArrayList<>();
}
@Override
public void start() {
if (started) {
LOGGER.warn("profiling already started!");
} else {
indexStack.clear();
locations.clear();
times.clear();
started = true;
push("total");
}
}
@Override
public void end() {
if (started) {
pop();
started = false;
if (!indexStack.isEmpty()) {
LOGGER.warn("profiling ended before stack was fully popped, did something go wrong?");
}
ProfilerResults.add(locations, times);
} else {
LOGGER.warn("profiling already ended!");
}
}
@Override
public void push(String location) {
if (started) {
indexStack.add(times.size());
locations.add(location);
times.add(System.nanoTime());
} else {
LOGGER.error("cannot push " + location + " as profiling hasn't started!");
}
}
@Override
public void pop() {
if (started) {
Integer index = indexStack.pop();
if (index == null) {
LOGGER.error("no element to pop!");
} else {
long startTime = times.get(index);
long endTime = System.nanoTime();
times.set(index, endTime - startTime);
}
} else {
LOGGER.error("cannot pop as profiling hasn't started!");
}
}
@Override
public void swap(String location) {
pop();
push(location);
}
}
|
alternate-current
|
src\main\java\alternate\current\util\profiler\Profiler.java
|
package alternate.current.util.profiler;
public interface Profiler {
public static final Profiler DUMMY = new Profiler() {
@Override public void start() { }
@Override public void end() { }
@Override public void push(String location) { }
@Override public void pop() { }
@Override public void swap(String location) { }
};
public void start();
public void end();
public void push(String location);
public void pop();
public void swap(String location);
}
|
alternate-current
|
src\main\java\alternate\current\util\profiler\ProfilerResults.java
|
package alternate.current.util.profiler;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.logging.log4j.Logger;
import alternate.current.AlternateCurrentMod;
public class ProfilerResults {
private static final Logger LOGGER = AlternateCurrentMod.LOGGER;
private static final Map<String, Long> RESULTS = new LinkedHashMap<>();
private static long totalTime;
public static void clear() {
RESULTS.clear();
totalTime = 0;
}
public static void add(List<String> locations, List<Long> times) {
long total = times.get(0);
totalTime += total;
for (int index = 1; index < locations.size(); index++) {
String location = locations.get(index);
long time = times.get(index);
RESULTS.compute(location, (l, t) -> t == null ? time : t + time);
}
}
public static void log() {
LOGGER.info("------------------------------------------------------");
LOGGER.info("..... Alternate Current Profiler Session Results .....");
LOGGER.info("total: " + totalTime);
for (Entry<String, Long> entry : RESULTS.entrySet()) {
String loc = entry.getKey();
long time = entry.getValue();
LOGGER.info(String.format("%s: %d (~%d%%)", loc, time, (100 * time / totalTime)));
}
}
}
|
amecs-api
|
src\main\mixins\amecsapi.compat.controlling.mixins.json
|
{
"required": false,
"package": "de.siphalor.amecs.impl.mixin.compat.controlling",
"compatibilityLevel": "JAVA_8",
"mixins": [],
"client": [
"MixinControllingKeyBindingEntry"
],
"server": [],
"injectors": {
"defaultRequire": 1
}
}
|
amecs-api
|
src\main\resources\amecsapi.mixins.json
|
{
"required": true,
"package": "de.siphalor.amecs.impl.mixin",
"compatibilityLevel": "JAVA_8",
"mixins": [],
"client": [
"MixinGameOptions",
"MixinInputUtilType",
"MixinKeyBinding",
"MixinKeyBindingEntry",
"MixinKeybindsScreen",
"MixinKeyboard",
"MixinMinecraftClient",
"MixinMouse"
],
"server": [],
"injectors": {
"defaultRequire": 1
}
}
|
amecs-api
|
src\main\resources\fabric.mod.json
|
{
"schemaVersion": 1,
"id": "amecsapi",
"version": "${version}",
"name": "Amecs API",
"description": "The keybinding modifier API of Amecs",
"authors": [
"Siphalor",
"Klotzi111"
],
"contributors": [],
"contact": {},
"license": "Apache-2.0",
"icon": "assets/amecsapi/icon.png",
"environment": "client",
"entrypoints": {
"main": [],
"client": [
"de.siphalor.amecs.impl.AmecsAPI"
],
"server": []
},
"accessWidener": "amecsapi.accesswidener",
"mixins": [${mixins}],
"custom": {
"modmenu:api": true,
"modmenu": {
"badges": [
"library"
]
}
},
"depends": {
"fabricloader": ">=0.17.0",
"fabric-api-base": "*",
"fabric-key-binding-api-v1": "*",
"fabric-resource-loader-v0": "*"
},
"conflicts": {
"nmuk": "<=1.0.999"
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\api\AmecsKeyBinding.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.api;
import com.mojang.blaze3d.platform.InputConstants;
import de.siphalor.amecs.impl.duck.IKeyBinding;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.KeyMapping;
import net.minecraft.resources.ResourceLocation;
/**
* A {@link net.minecraft.client.KeyMapping} base class to be used when you want to define modifiers keys as default
*/
@Environment(EnvType.CLIENT)
public class AmecsKeyBinding extends KeyMapping {
private final KeyModifiers defaultModifiers;
/**
* Constructs a new amecs keybinding. And because how the vanilla key binding works. It is automatically registered.
* <br>
* See {@link KeyBindingUtils#unregisterKeyBinding(KeyMapping)} for how to unregister it
* If you want to set the key's translationKey directly use {@link #AmecsKeyBinding(String, InputConstants.Type, int, String, KeyModifiers)} instead
*
* @param id the id to use
* @param type the input type which triggers this keybinding
* @param code the default key code
* @param category the id of the category which should include this keybinding
* @param defaultModifiers the default modifiers
*/
public AmecsKeyBinding(
ResourceLocation id,
InputConstants.Type type,
int code,
//# if MC_VERSION_NUMBER >= 12109
Category category,
//# else
//- String category,
//# end
KeyModifiers defaultModifiers
) {
this("key." + id.getNamespace() + "." + id.getPath(), type, code, category, defaultModifiers);
}
/**
* Constructs a new amecs keybinding. And because how the vanilla key binding works. It is automatically registered.
* <br>
* See {@link KeyBindingUtils#unregisterKeyBinding(KeyMapping)} for how to unregister it
*
* @param id the id to use
* @param type the input type which triggers this keybinding
* @param code the default key code
* @param category the id of the category which should include this keybinding
* @param defaultModifiers the default modifiers
*/
public AmecsKeyBinding(
String id,
InputConstants.Type type,
int code,
//# if MC_VERSION_NUMBER >= 12109
Category category,
//# else
//- String category,
//# end
KeyModifiers defaultModifiers
) {
super(id, type, code, category);
if (defaultModifiers == null || defaultModifiers == KeyModifiers.NO_MODIFIERS) {
defaultModifiers = new KeyModifiers(); // the modifiable version of: KeyModifiers.NO_MODIFIERS
}
this.defaultModifiers = defaultModifiers;
((IKeyBinding) this).amecs$getKeyModifiers().copyModifiers(this.defaultModifiers);
}
//# if MC_VERSION_NUMBER >= 11500
@Override
//# end
public void setDown(boolean pressed) {
//# if MC_VERSION_NUMBER >= 11500
super.setDown(pressed);
//# else
//- ((IKeyBinding) this).amecs$setDown(pressed);
//# end
if (pressed) {
onPressed();
} else {
onReleased();
}
}
/**
* A convenience method which gets fired when the keybinding is used
*/
public void onPressed() {
}
/**
* A convenience method which gets fired when the keybinding is stopped being used
*/
public void onReleased() {
}
/**
* Resets this keybinding (triggered when the user clicks on the "Reset" button).
*/
public void resetKeyBinding() {
((IKeyBinding) this).amecs$getKeyModifiers().copyModifiers(defaultModifiers);
}
@Override
public boolean isDefault() {
return defaultModifiers.equals(((IKeyBinding) this).amecs$getKeyModifiers()) && super.isDefault();
}
public KeyModifiers getDefaultModifiers() {
return defaultModifiers;
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\api\KeyBindingUtils.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.api;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import com.mojang.blaze3d.platform.InputConstants;
import de.siphalor.amecs.impl.KeyBindingManager;
import de.siphalor.amecs.impl.duck.IKeyBinding;
import lombok.CustomLog;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.KeyMapping;
/**
* Utility methods and constants for Amecs and vanilla key bindings
*/
@SuppressWarnings("unused")
@Environment(EnvType.CLIENT)
@CustomLog
public class KeyBindingUtils {
public static final int MOUSE_SCROLL_UP = 512;
public static final int MOUSE_SCROLL_DOWN = 513;
//# if MC_VERSION_NUMBER >= 12002
public static final int MOUSE_SCROLL_LEFT = 514;
public static final int MOUSE_SCROLL_RIGHT = 515;
//# end
/**
* The last (y directional) scroll delta
*/
@Deprecated
private static double lastScrollAmountY = 0;
private static Map<String, KeyMapping> idToKeyBindingMap;
private KeyBindingUtils() {
}
/**
* Gets the last (y directional) scroll amount.
*
* @return the last (y directional) scroll amount
* @deprecated Just exists for legacy support.
*/
@Deprecated
public static double getLastScrollAmount() {
return lastScrollAmountY;
}
/**
* Sets the last (y directional) scroll amount. <b>For internal use only.</b>
*
* @param lastScrollAmountY the amount
* @deprecated Just exists for legacy support.
*/
@Deprecated
public static void setLastScrollAmount(double lastScrollAmountY) {
KeyBindingUtils.lastScrollAmountY = lastScrollAmountY;
}
/**
* Gets the key object for the vertical scroll direction
*
* @param deltaY the vertical (y) scroll amount {@link #getLastScrollAmount}
* @return the key object
* @see #getKeyFromVerticalScroll(double)
* @see #getKeyFromHorizontalScroll(double)
* @deprecated Just exists for legacy support. Use {@link #getKeyFromVerticalScroll(double)} instead.
*/
@Deprecated
public static InputConstants.Key getKeyFromScroll(double deltaY) {
return InputConstants.Type.MOUSE.getOrCreate(deltaY > 0 ? KeyBindingUtils.MOUSE_SCROLL_UP : KeyBindingUtils.MOUSE_SCROLL_DOWN);
}
/**
* Gets the key object for the vertical scroll direction
*
* @param deltaY the vertical (y) scroll amount {@link #getLastScrollAmount}
* @return the key object
*/
public static InputConstants.Key getKeyFromVerticalScroll(double deltaY) {
if (deltaY == 0D) {
return null;
}
return InputConstants.Type.MOUSE.getOrCreate(deltaY > 0 ? KeyBindingUtils.MOUSE_SCROLL_UP : KeyBindingUtils.MOUSE_SCROLL_DOWN);
}
//# if MC_VERSION_NUMBER >= 12002
/**
* Gets the key object for the horizontal scroll direction
*
* @param deltaX the horizontal (x) scroll amount {@link #getLastScrollAmount}
* @return the key object
*/
public static InputConstants.Key getKeyFromHorizontalScroll(double deltaX) {
if (deltaX == 0D) {
return null;
}
return InputConstants.Type.MOUSE.getOrCreate(deltaX > 0 ? KeyBindingUtils.MOUSE_SCROLL_RIGHT : KeyBindingUtils.MOUSE_SCROLL_LEFT);
}
//# end
/**
* Gets the "official" idToKeys map
*
* @return the map (use with care)
*/
public static Map<String, KeyMapping> getIdToKeyBindingMap() {
if (idToKeyBindingMap == null) {
try {
// reflections accessors should be initialized statically if they are static
// but in this case its fine because we only do this once because it is cached in a static field
// noinspection JavaReflectionMemberAccess
Method method = KeyMapping.class.getDeclaredMethod("amecs$getIdToKeyBindingMap");
method.setAccessible(true);
// noinspection unchecked
idToKeyBindingMap = (Map<String, KeyMapping>) method.invoke(null);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
log.error("Failed to get access to key bindings", e);
}
}
return idToKeyBindingMap;
}
/**
* Unregisters a keybinding from input querying but is NOT removed from the controls GUI
* <br>
* if you unregister a keybinding which is already in the controls GUI you can call {@link #registerHiddenKeyBinding(KeyMapping)} with this keybinding to undo this
* <br>
* <br>
* This is possible even after the game initialized
*
* @param keyBinding the keybinding
* @return whether the keyBinding was removed. It is not removed if it was not contained
*/
public static boolean unregisterKeyBinding(KeyMapping keyBinding) {
return unregisterKeyBinding(keyBinding.getName());
}
/**
* Unregisters a keybinding with the given id
* <br>
* for more details {@link #unregisterKeyBinding(KeyMapping)}
*
* @param id the translation key
* @return whether the keyBinding was removed. It is not removed if it was not contained
* @see #unregisterKeyBinding(KeyMapping)
*/
public static boolean unregisterKeyBinding(String id) {
KeyMapping keyBinding = getIdToKeyBindingMap().remove(id);
return KeyBindingManager.unregister(keyBinding);
}
/**
* Registers a keybinding for input querying but is NOT added to the controls GUI
* <br>
* you can register a keybinding which is already in the controls GUI but was removed from input querying via {@link #unregisterKeyBinding(KeyMapping)}
* <br>
* <br>
* This is possible even after the game initialized
*
* @param keyBinding the keybinding
* @return whether the keybinding was added. It is not added if it is already contained
*/
public static boolean registerHiddenKeyBinding(KeyMapping keyBinding) {
return KeyBindingManager.register(keyBinding);
}
/**
* Gets the key modifiers that are bound to the given key binding
*
* @param keyBinding the key binding
* @return the key modifiers
*/
public static KeyModifiers getBoundModifiers(KeyMapping keyBinding) {
return ((IKeyBinding) keyBinding).amecs$getKeyModifiers();
}
/**
* Gets the default modifiers of the given key binding.
* The returned value <b>must not be modified!</b>
*
* @param keyBinding the key binding
* @return a reference to the default modifiers
*/
public static KeyModifiers getDefaultModifiers(KeyMapping keyBinding) {
if (keyBinding instanceof AmecsKeyBinding) {
return ((AmecsKeyBinding) keyBinding).getDefaultModifiers();
}
return KeyModifiers.NO_MODIFIERS;
}
public static void resetBoundModifiers(KeyMapping keyBinding) {
((IKeyBinding) keyBinding).amecs$getKeyModifiers().unset();
if (keyBinding instanceof AmecsKeyBinding) {
((AmecsKeyBinding) keyBinding).resetKeyBinding();
}
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\api\KeyModifier.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.api;
import com.mojang.blaze3d.platform.InputConstants;
import de.siphalor.amecs.impl.AmecsAPI;
import de.siphalor.amecs.impl.ModifierPrefixTextProvider;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import org.apache.commons.lang3.ArrayUtils;
@SuppressWarnings("WeakerAccess")
@Environment(EnvType.CLIENT)
public enum KeyModifier {
// the order of the enums makes a difference when generating the shown name in the gui
// with this order the old text order is preserved. But now the id values do not increment nicely. But changing them would eliminate
// backward compatibility with the old save format
NONE("none", -1),
ALT("alt", 0, 342, 346),
SHIFT("shift", 2, 340, 344),
CONTROL("control", 1, 341, 345);
// using this array for the values because it is faster than calling values() every time
public static final KeyModifier[] VALUES = KeyModifier.values();
public final String name;
public final int id;
public final ModifierPrefixTextProvider textProvider;
// these keyCodes are all from Type: InputUtil.Type.KEYSYM
final int[] keyCodes;
KeyModifier(String name, int id, int... keyCodes) {
this.name = name;
this.id = id;
textProvider = new ModifierPrefixTextProvider(this);
this.keyCodes = keyCodes;
}
public static KeyModifier fromKeyCode(int keyCode) {
for (KeyModifier keyModifier : VALUES) {
if (keyModifier == NONE) {
continue;
}
if (keyModifier.matches(keyCode)) {
return keyModifier;
}
}
return NONE;
}
public static KeyModifier fromKey(InputConstants.Key key) {
if (key == null || key.getType() != InputConstants.Type.KEYSYM) {
return NONE;
}
return fromKeyCode(key.getValue());
}
public boolean matches(int keyCode) {
return ArrayUtils.contains(keyCodes, keyCode);
}
public String getTranslationKey() {
return AmecsAPI.MOD_ID + ".modifier." + name;
}
public static int getModifierCount() {
return VALUES.length - 1; // remove 1 for NONE
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\api\KeyModifiers.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.api;
import com.mojang.blaze3d.platform.InputConstants;
import de.siphalor.amecs.impl.AmecsAPI;
import de.siphalor.amecs.impl.duck.IKeyBinding;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.KeyMapping;
import org.apache.commons.lang3.ArrayUtils;
import org.jetbrains.annotations.ApiStatus;
import java.util.Arrays;
/**
* Defines modifiers for a key binding
*/
@SuppressWarnings({"WeakerAccess", "UnusedReturnValue"})
@Environment(EnvType.CLIENT)
public class KeyModifiers {
/**
* This field is for comparison ONLY.
* <p>
* Trying to change the modifiers of it will fail with an {@link UnsupportedOperationException}
*/
public static final KeyModifiers NO_MODIFIERS = new FinalKeyModifiers();
private static class FinalKeyModifiers extends KeyModifiers {
private static final String EXCEPTION_MESSAGE = "You must not alter this Modifiers object";
@Override
public KeyModifiers setValue(boolean[] value) {
throw new UnsupportedOperationException(EXCEPTION_MESSAGE);
}
@Override
public void set(KeyModifier keyModifier, boolean value) {
throw new UnsupportedOperationException(EXCEPTION_MESSAGE);
}
@Override
public void unset() {
throw new UnsupportedOperationException(EXCEPTION_MESSAGE);
}
}
public static KeyModifiers getCurrentlyPressed() {
return AmecsAPI.CURRENT_MODIFIERS;
}
// using a boolean array here because it is faster and needs less space
private final boolean[] value;
/**
* Constructs new object with no modifiers set
*/
public KeyModifiers() {
this(new boolean[KeyModifier.getModifierCount()]);
}
/**
* FOR INTERNAL USE ONLY
* <p>
* Constructs a new modifier object by a raw boolean array
*
* @param value the raw value with flags set
*/
@ApiStatus.Internal
public KeyModifiers(boolean[] value) {
if (value.length != KeyModifier.getModifierCount()) {
throw new IllegalArgumentException("value.length != KeyModifier.getModifierCount(): " + KeyModifier.getModifierCount());
}
this.value = value;
}
/**
* Constructs a new modifier object by all modifier bits
*
* @param alt sets whether the alt flag should be set
* @param control sets whether the control flag should be set
* @param shift sets whether the shift flag should be set
*/
public KeyModifiers(boolean alt, boolean control, boolean shift) {
this();
setAlt(alt);
setControl(control);
setShift(shift);
}
/**
* Compares this object with the currently pressed keys
*
* @return whether the modifiers match in the current context
* @deprecated always performs an exact check against {@link #getCurrentlyPressed()}.
* Use {@link AmecsAPI#CURRENT_MODIFIERS} in combination with {@link #contains(KeyModifiers)} or {@link #equals(KeyModifiers)} instead.
*/
@Deprecated
public boolean isPressed() {
return equals(AmecsAPI.CURRENT_MODIFIERS);
}
/**
* Returns whether the given modifiers are also set in this object.
* @param other the modifiers to check
* @return whether the given modifiers are also set in this object
*/
public boolean contains(KeyModifiers other) {
for (int i = 0; i < value.length; i++) {
if (other.value[i] && !this.value[i]) {
return false;
}
}
return true;
}
/**
* FOR INTERNAL USE ONLY
* <p>
* Sets the raw value
*
* @param value the value with flags set
*/
@ApiStatus.Internal
public KeyModifiers setValue(boolean[] value) {
int length = this.value.length;
if (value.length != length) {
throw new IllegalArgumentException("value != this.value.length: " + length);
}
System.arraycopy(value, 0, this.value, 0, length);
return this;
}
/**
* FOR INTERNAL USE ONLY
* <p>
* Gets the raw value
*
* @return the value with all flags set
*/
@ApiStatus.Internal
public boolean[] getValue() {
return value;
}
/**
* FOR INTERNAL USE ONLY
* <p>
* copies the modifiers of the other KeyModifiers object into this
*/
@ApiStatus.Internal
public void copyModifiers(KeyModifiers other) {
setValue(other.getValue());
}
/**
* Sets the alt flag
*
* @param value whether the alt flag should be activated or not
*/
public KeyModifiers setAlt(boolean value) {
set(KeyModifier.ALT, value);
return this;
}
/**
* Gets the state of the alt flag
*
* @return whether the alt key needs to be pressed
*/
public boolean getAlt() {
return get(KeyModifier.ALT);
}
/**
* Sets the control flag
*
* @param value whether the control flag should be activated or not
*/
public KeyModifiers setControl(boolean value) {
set(KeyModifier.CONTROL, value);
return this;
}
/**
* Gets the state of the control flag
*
* @return whether the control key needs to be pressed
*/
public boolean getControl() {
return get(KeyModifier.CONTROL);
}
/**
* Sets the shift flag
*
* @param value whether the shift flag should be activated or not
*/
public KeyModifiers setShift(boolean value) {
set(KeyModifier.SHIFT, value);
return this;
}
/**
* Gets the state of the shift flag
*
* @return whether the shift key needs to be pressed
*/
public boolean getShift() {
return get(KeyModifier.SHIFT);
}
public void set(KeyModifier keyModifier, boolean value) {
if (keyModifier != KeyModifier.NONE) {
this.value[keyModifier.id] = value;
}
}
public boolean get(KeyModifier keyModifier) {
if (keyModifier == KeyModifier.NONE) {
return true;
}
return value[keyModifier.id];
}
/**
* Returns whether no flag is set
*
* @return value == 0
*/
public boolean isUnset() {
return !ArrayUtils.contains(value, true);
}
/**
* Clears all flags
*/
public void unset() {
Arrays.fill(value, false);
}
/**
* Cleans up the flags by the key code present in the given key binding
*
* @param keyBinding the key binding from where to extract the key code
*/
public void cleanup(KeyMapping keyBinding) {
InputConstants.Key key = ((IKeyBinding) keyBinding).amecs$getBoundKey();
set(KeyModifier.fromKey(key), false);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof KeyModifiers) {
return equals((KeyModifiers) obj);
}
return false;
}
/**
* Returns whether this object equals another one
*
* @param other another modifier object
* @return whether both values are equal
*/
public boolean equals(KeyModifiers other) {
return Arrays.equals(value, other.value);
}
@Override
public String toString() {
return "KeyModifiers [alt=" + getAlt() + ", control=" + getControl() + ", shift=" + getShift() + "]";
}
// new format even if it needs more characters because it is more user friendly (and simpler to parse). Not everyone knows about bit masks
// it could be discussed whether this new is really "better" but i leave it for now. It is backward compatible so nothing breaks
/**
* FOR INTERNAL USE ONLY
*
* @return the serialized string representation of the modifiers
*/
@ApiStatus.Internal
public String serializeValue() {
StringBuilder sb = new StringBuilder();
for (boolean b : value) {
sb.append(b ? 1 : 0);
sb.append(",");
}
// remove trailing comma
// this will fail if value.length is 0. But that would be useless anyways
sb.setLength(sb.length() - ",".length());
return sb.toString();
}
/**
* FOR INTERNAL USE ONLY
*
* @return the deserialized modifier array
*/
@ApiStatus.Internal
public static boolean[] deserializeValue(String value) {
boolean[] ret = new boolean[KeyModifier.getModifierCount()];
if (value.isEmpty()) {
return ret;
}
// backward compatibility for old format
if (!value.contains(",")) {
// we never had more than one value with the fat long
long packedModifiers = Long.parseLong(value, 16);
for (KeyModifier keyModifier : KeyModifier.VALUES) {
if (keyModifier == KeyModifier.NONE) {
continue;
}
long mask = (1L << keyModifier.id);
ret[keyModifier.id] = (packedModifiers & mask) == mask;
}
return ret;
}
// we have the new format
int i = 0;
for (String p : value.split(",")) {
ret[i++] = p.equals("1");
}
return ret;
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\api\PriorityKeyBinding.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.api;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
/**
* An interface to be used on {@link net.minecraft.client.KeyMapping}s.
* <b>This key binding triggers without further conditions before any other checks or conditions.</b>
*/
@Environment(EnvType.CLIENT)
public interface PriorityKeyBinding {
/**
* This method gets triggered when this key binding matches on an input event. <br>
* Since there are no other checks before the invocation you need to check yourself for possible open screens.
*
* @return Return true to cancel propagation of this event. Return false for normal evaluation.
*/
boolean onPressedPriority();
/**
* This method gets triggered when this key binding matches on an input release event. <br>
* Since there are no other checks before the invocation you need to check yourself for possible open screens.
*
* @return Return true to cancel propagation of this event. Return false for normal evaluation.
*/
default boolean onReleasedPriority() {
return false;
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\AmecsAPI.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl;
import de.siphalor.amecs.api.KeyModifiers;
import de.siphalor.amecs.impl.compat.controlling.AmecsControllingIntegration;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.loader.api.FabricLoader;
import org.jetbrains.annotations.ApiStatus;
@Environment(EnvType.CLIENT)
@ApiStatus.Internal
public class AmecsAPI implements ClientModInitializer {
public static final String MOD_ID = "amecsapi";
public static final String MOD_NAME = "Amecs API";
public static final KeyModifiers CURRENT_MODIFIERS = new KeyModifiers();
// this is used by KTIG
public static boolean TRIGGER_KEYBINDING_ON_SCROLL = true;
public static String makeKeyID(String keyName) {
return "key." + MOD_ID + "." + keyName;
}
@Override
public void onInitializeClient() {
//# if CONTROLLING_INTEGRATION
FabricLoader loader = FabricLoader.getInstance();
if (loader.isModLoaded("controlling")) {
AmecsControllingIntegration.initialize();
}
//# end
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\AmecsAPIOptions.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl;
import de.siphalor.amecs.api.KeyBindingUtils;
import de.siphalor.amecs.api.KeyModifiers;
import de.siphalor.amecs.impl.duck.IKeyBinding;
import lombok.CustomLog;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.Minecraft;
import org.jetbrains.annotations.ApiStatus;
import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
@Environment(EnvType.CLIENT)
@ApiStatus.Internal
@CustomLog
public class AmecsAPIOptions {
private static final String KEY_MODIFIERS_PREFIX = "key_modifiers_";
private static final File optionsFile = new File(Minecraft.getInstance().gameDirectory, "options." + AmecsAPI.MOD_ID + ".txt");
private AmecsAPIOptions() {}
public static void write(KeyMapping[] allKeyBindings) {
List<KeyMapping> bindingsWithChangedModifiers = new ArrayList<>(allKeyBindings.length);
for (KeyMapping keyBinding : allKeyBindings) {
if (!KeyBindingUtils.getDefaultModifiers(keyBinding).equals(KeyBindingUtils.getBoundModifiers(keyBinding))) {
bindingsWithChangedModifiers.add(keyBinding);
}
}
if (bindingsWithChangedModifiers.isEmpty()) {
if (optionsFile.exists()) {
try {
Files.delete(optionsFile.toPath());
} catch (IOException e) {
log.error("Failed to cleanup Amecs API key binding modifier file - weird.", e);
}
}
return;
}
try (PrintWriter writer = new PrintWriter(new FileOutputStream(optionsFile))) {
KeyModifiers modifiers;
for (KeyMapping binding : bindingsWithChangedModifiers) {
modifiers = KeyBindingUtils.getBoundModifiers(binding);
writer.println(KEY_MODIFIERS_PREFIX + binding.getName() + ":" + modifiers.serializeValue());
}
} catch (FileNotFoundException e) {
log.error("Failed to save Amecs API modifiers to options file", e);
}
}
public static void read() {
if (!optionsFile.exists()) {
return;
}
try (BufferedReader reader = new BufferedReader(new FileReader(optionsFile))) {
String line;
while ((line = reader.readLine()) != null) {
readLine(line);
}
} catch (IOException e) {
log.error("Failed to load Amecs API options file", e);
}
}
private static void readLine(String line) {
try {
int colon = line.indexOf(':');
if (colon <= 0) {
log.warn("Invalid line in Amecs API options file: {}", line);
return;
}
String id = line.substring(0, colon);
if (!id.startsWith(KEY_MODIFIERS_PREFIX)) {
log.warn("Invalid entry in Amecs API options file: {}", id);
return;
}
id = id.substring(KEY_MODIFIERS_PREFIX.length());
KeyMapping keyBinding = KeyBindingUtils.getIdToKeyBindingMap().get(id);
if (keyBinding == null) {
log.warn("Unknown keybinding identifier in Amecs API options file: {}", id);
return;
}
KeyModifiers modifiers = new KeyModifiers(KeyModifiers.deserializeValue(line.substring(colon + 1)));
if (keyBinding.isUnbound()) {
if (!modifiers.isUnset()) {
log.warn("Found modifiers for unbound keybinding in Amecs API options file. Ignoring them: {}", id);
}
return;
}
((IKeyBinding) keyBinding).amecs$getKeyModifiers().copyModifiers(modifiers);
} catch (Throwable e) {
log.error("Invalid line in Amecs API options file: {}", line, e);
}
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\KeyBindingEditGuiHelper.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl;
import com.mojang.blaze3d.platform.InputConstants;
import de.siphalor.amecs.api.KeyModifier;
import de.siphalor.amecs.api.KeyModifiers;
import de.siphalor.amecs.impl.duck.IKeyBinding;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import net.minecraft.client.KeyMapping;
//- import net.minecraft.client.Minecraft;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class KeyBindingEditGuiHelper {
public static void handleKeyPress(KeyMapping keyBinding, InputConstants.Key key) {
if (keyBinding.isUnbound()) {
keyBinding.setKey(key);
} else {
handleAdditionalKeyPress(keyBinding, key);
}
}
public static void handleAdditionalKeyPress(KeyMapping keyBinding, InputConstants.Key nextKey) {
InputConstants.Key mainKey = ((IKeyBinding) keyBinding).amecs$getBoundKey();
KeyModifiers keyModifiers = ((IKeyBinding) keyBinding).amecs$getKeyModifiers();
KeyModifier mainKeyModifier = KeyModifier.fromKey(mainKey);
KeyModifier nextKeyModifier = KeyModifier.fromKey(nextKey);
if (nextKeyModifier == KeyModifier.NONE) {
if (mainKeyModifier != KeyModifier.NONE) {
// swap'em around
keyModifiers.set(mainKeyModifier, true);
setKey(keyBinding, nextKey);
} else {
// shouldn't happen, as editing should already have been aborted
setKey(keyBinding, nextKey);
}
} else {
// add to existing modifiers
keyModifiers.set(nextKeyModifier, true);
if (mainKeyModifier != KeyModifier.NONE) {
// special case, if e.g. both left and right shift are pressed:
// we don't want to end up with Shift + Shift
keyModifiers.set(mainKeyModifier, false);
}
}
}
private static void setKey(KeyMapping keyBinding, InputConstants.Key key) {
//# if MC_VERSION_NUMBER >= 12102
keyBinding.setKey(key);
//# else
//- Minecraft.getInstance().options.setKey(keyBinding, key);
//# end
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\KeyBindingManager.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl;
import com.mojang.blaze3d.platform.InputConstants;
import com.mojang.blaze3d.platform.Window;
import de.siphalor.amecs.api.KeyBindingUtils;
import de.siphalor.amecs.api.KeyModifier;
import de.siphalor.amecs.api.KeyModifiers;
import de.siphalor.amecs.api.PriorityKeyBinding;
import de.siphalor.amecs.impl.duck.IKeyBinding;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.Minecraft;
import org.jetbrains.annotations.ApiStatus;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Environment(EnvType.CLIENT)
@ApiStatus.Internal
public class KeyBindingManager {
// split it in two maps because it is ways faster to only stream the map with the objects we need
// rather than streaming all and throwing out a bunch every time
public static final Map<InputConstants.Key, List<KeyMapping>> keysById = new HashMap<>();
public static final Map<InputConstants.Key, List<KeyMapping>> priorityKeysById = new HashMap<>();private static final List<KeyMapping> pressedKeyBindings = new ArrayList<>(10);
private KeyBindingManager() {}
/**
* Removes a key binding from one of the internal maps
* @param targetMap the key binding map to remove from
* @param keyBinding the key binding to remove
* @return whether the keyBinding was removed. It is not removed if it was not contained
*/
private static boolean removeKeyBindingFromMap(Map<InputConstants.Key, List<KeyMapping>> targetMap, KeyMapping keyBinding) {
// we need to get the backing list to remove elements thus we can not use any of the other methods that return streams
InputConstants.Key keyCode = ((IKeyBinding) keyBinding).amecs$getBoundKey();
List<KeyMapping> keyBindings = targetMap.get(keyCode);
if (keyBindings == null) {
return false;
}
boolean removed = false;
// while loop to ensure that we remove all equal KeyBindings if for some reason there should be duplicates
while (keyBindings.remove(keyBinding)) {
removed = true;
}
return removed;
}
/**
* Adds a key binding to one of the internal maps
* @param targetMap the key binding map to add to
* @param keyBinding the key binding to add
* @return whether the keyBinding was added. It is not added if it is already contained
*/
private static boolean addKeyBindingToListFromMap(Map<InputConstants.Key, List<KeyMapping>> targetMap, KeyMapping keyBinding) {
InputConstants.Key keyCode = ((IKeyBinding) keyBinding).amecs$getBoundKey();
List<KeyMapping> keyBindings = targetMap.computeIfAbsent(keyCode, k -> new ArrayList<>());
if (keyBindings.contains(keyBinding)) {
return false;
}
keyBindings.add(keyBinding);
return true;
}
/**
* Registers a key binding to Amecs API
* @param keyBinding the key binding to register
* @return whether the keyBinding was added. It is not added if it is already contained
*/
public static boolean register(KeyMapping keyBinding) {
if (keyBinding instanceof PriorityKeyBinding) {
return addKeyBindingToListFromMap(priorityKeysById, keyBinding);
} else {
return addKeyBindingToListFromMap(keysById, keyBinding);
}
}
public static Stream<KeyMapping> getMatchingKeyBindings(InputConstants.Key keyCode, boolean priority) {
List<KeyMapping> keyBindingList = (priority ? priorityKeysById : keysById).get(keyCode);
if (keyBindingList == null)
return Stream.empty();
// If there are two key bindings, alt + y and shift + alt + y, and you press shift + alt + y, both will be triggered.
// This is intentional.
Stream<KeyMapping> result = keyBindingList.stream().filter(KeyBindingManager::areExactModifiersPressed);
List<KeyMapping> keyBindings = result.collect(Collectors.toList());
if (keyBindings.isEmpty())
return keyBindingList.stream().filter(keyBinding -> ((IKeyBinding) keyBinding).amecs$getKeyModifiers().isUnset());
return keyBindings.stream();
}
private static boolean areExactModifiersPressed(KeyMapping keyBinding) {
return KeyBindingUtils.getBoundModifiers(keyBinding).equals(AmecsAPI.CURRENT_MODIFIERS);
}
public static void onKeyPressed(InputConstants.Key keyCode) {
getMatchingKeyBindings(keyCode, false).forEach(keyBinding ->
((IKeyBinding) keyBinding).amecs$incrementTimesPressed()
);
}
private static Stream<KeyMapping> getKeyBindingsFromMap(Map<InputConstants.Key, List<KeyMapping>> keysById_map) {
return keysById_map.values().stream().flatMap(Collection::stream);
}
private static void forEachKeyBinding(Consumer<KeyMapping> consumer) {
getKeyBindingsFromMap(priorityKeysById).forEach(consumer);
getKeyBindingsFromMap(keysById).forEach(consumer);
}
private static void forEachKeyBindingWithKey(InputConstants.Key key, Consumer<KeyMapping> consumer) {
getMatchingKeyBindings(key, true).forEach(consumer);
getMatchingKeyBindings(key, false).forEach(consumer);
}
public static void updatePressedStates() {
//# if MC_VERSION_NUMBER >= 12109
Window windowHandle = Minecraft.getInstance().getWindow();
//# elif MC_VERSION_NUMBER >= 11500
//- long windowHandle = Minecraft.getInstance().getWindow().getWindow();
//# else
//- long windowHandle = Minecraft.getInstance().window.getWindow();
//# end
forEachKeyBinding(keyBinding -> {
InputConstants.Key key = ((IKeyBinding) keyBinding).amecs$getBoundKey();
boolean pressed = !keyBinding.isUnbound() && key.getType() == InputConstants.Type.KEYSYM && InputConstants.isKeyDown(windowHandle, key.getValue());
setKeyBindingPressed(keyBinding, pressed);
});
}
/**
* Unregisters a key binding from Amecs API
* @param keyBinding the key binding to unregister
* @return whether the keyBinding was removed. It is not removed if it was not contained
*/
public static boolean unregister(KeyMapping keyBinding) {
if (keyBinding == null) {
return false;
}
// avoid having to rebuild the whole entry map with KeyMapping.updateKeysByCode()
boolean removed = false;
removed |= removeKeyBindingFromMap(keysById, keyBinding);
removed |= removeKeyBindingFromMap(priorityKeysById, keyBinding);
return removed;
}
public static void updateKeysByCode() {
keysById.clear();
priorityKeysById.clear();
KeyBindingUtils.getIdToKeyBindingMap().values().forEach(KeyBindingManager::register);
}
public static void setKeyBindingPressed(KeyMapping keyBinding, boolean pressed) {
if (pressed != keyBinding.isDown()) {
if (pressed) {
pressedKeyBindings.add(keyBinding);
} else {
pressedKeyBindings.remove(keyBinding);
}
}
//# if MC_VERSION_NUMBER >= 11500
keyBinding.setDown(pressed);
//# else
//- ((IKeyBinding) keyBinding).amecs$setDown(pressed);
//# end
}
public static void unpressAll() {
KeyBindingUtils.getIdToKeyBindingMap().values().forEach(keyBinding -> ((IKeyBinding) keyBinding).amecs$reset());
}
public static boolean onKeyPressedPriority(InputConstants.Key keyCode) {
// because streams are lazily evaluated, this code only calls onPressedPriority so often until one returns true
Optional<KeyMapping> keyBindings = getMatchingKeyBindings(keyCode, true).filter(keyBinding -> ((PriorityKeyBinding) keyBinding).onPressedPriority()).findFirst();
return keyBindings.isPresent();
}
public static boolean onKeyReleasedPriority(InputConstants.Key keyCode) {
// because streams are lazily evaluated, this code only calls onPressedPriority so often until one returns true
Optional<KeyMapping> keyBindings = getMatchingKeyBindings(keyCode, true).filter(keyBinding -> ((PriorityKeyBinding) keyBinding).onReleasedPriority()).findFirst();
return keyBindings.isPresent();
}
public static void setKeyPressed(InputConstants.Key keyCode, boolean pressed) {
KeyModifier modifier = KeyModifier.fromKeyCode(keyCode.getValue());
AmecsAPI.CURRENT_MODIFIERS.set(modifier, pressed);
// Update keybindings with matching modifiers and the same keycode
forEachKeyBindingWithKey(keyCode, keyBinding -> setKeyBindingPressed(keyBinding, pressed));
if (modifier != null && !pressed) {
handleReleasedModifier();
}
}
private static void handleReleasedModifier() {
// Handle the case that a modifier has been released
pressedKeyBindings.removeIf(pressedKeyBinding -> {
KeyModifiers boundModifiers = KeyBindingUtils.getBoundModifiers(pressedKeyBinding);
if (!AmecsAPI.CURRENT_MODIFIERS.contains(boundModifiers)) {
//# if MC_VERSION_NUMBER >= 11500
pressedKeyBinding.setDown(false);
//# else
//- ((IKeyBinding) pressedKeyBinding).amecs$setDown(false);
//# end
return true;
}
return false;
});
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\ModifierPrefixTextProvider.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl;
import de.siphalor.amecs.api.KeyModifier;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
//- import net.minecraft.client.resources.language.I18n;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
//- import net.minecraft.network.chat.TextComponent;
//- import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.network.chat.contents.TranslatableContents;
@Environment(EnvType.CLIENT)
public class ModifierPrefixTextProvider {
//# if MC_VERSION_NUMBER >= 11900
private static final Component SUFFIX = Component.literal(" + ");
private static final Component COMPRESSED_SUFFIX = Component.literal("+");
//# elif MC_VERSION_NUMBER >= 11600
//- private static final Component SUFFIX = new TextComponent(" + ");
//- private static final Component COMPRESSED_SUFFIX = new TextComponent("+");
//# else
//- private static final String SUFFIX = " + ";
//- private static final String COMPRESSED_SUFFIX = "+";
//# end
private final String translationKey;
public ModifierPrefixTextProvider(KeyModifier modifier) {
this(modifier.getTranslationKey());
}
public ModifierPrefixTextProvider(String translationKey) {
this.translationKey = translationKey;
}
//# if MC_VERSION_NUMBER >= 11600
protected MutableComponent getBaseComponent(Variation variation) {
//# if MC_VERSION_NUMBER >= 11900
return MutableComponent.create(variation.getTranslatableComponent(translationKey));
//# else
//- return variation.getTranslatableComponent(translationKey);
//# end
}
public MutableComponent getComponent(Variation variation) {
MutableComponent text = getBaseComponent(variation);
if (variation == Variation.COMPRESSED) {
text.append(COMPRESSED_SUFFIX);
} else {
text.append(SUFFIX);
}
return text;
}
//# else
//- public String getTranslation(Variation variation) {
//- String text = variation.getTranslation(translationKey);
//- if (variation == Variation.COMPRESSED) {
//- text += COMPRESSED_SUFFIX;
//- } else {
//- text += SUFFIX;
//- }
//- return text;
//- }
//# end
public enum Variation {
COMPRESSED(".tiny"),
TINY(".tiny"),
SHORT(".short"),
NORMAL("");
// using this array for the values because it is faster than calling values() every time
public static final Variation[] VALUES = Variation.values();
public static final Variation WIDEST = NORMAL;
public static final Variation SMALLEST = COMPRESSED;
public final String translateKeySuffix;
Variation(String translateKeySuffix) {
this.translateKeySuffix = translateKeySuffix;
}
//# if MC_VERSION_NUMBER >= 11900
public TranslatableContents getTranslatableComponent(String translationKey) {
return new TranslatableContents(translationKey + translateKeySuffix, null, new Object[0]);
}
//# elif MC_VERSION_NUMBER >= 11600
//- public TranslatableComponent getTranslatableComponent(String translationKey) {
//- return new TranslatableComponent(translationKey + translateKeySuffix, null, new Object[0]);
//- }
//# else
//- public String getTranslation(String translationKey) {
//- return I18n.get(translationKey + translateKeySuffix);
//- }
//# end
public Variation getNextVariation(int amount) {
int targetOrdinal = ordinal() + amount;
if (targetOrdinal < 0 || targetOrdinal >= VALUES.length) {
return null;
}
return VALUES[targetOrdinal];
}
public Variation getSmaller() {
return getNextVariation(-1);
}
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\NOPMap.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl;
import java.io.Serializable;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import org.jetbrains.annotations.NotNull;
/**
* Similar to Collections.EmptyMap
*
* @serial include
*/
@Environment(EnvType.CLIENT)
public class NOPMap<K, V> implements Map<K, V>, Serializable {
private static final long serialVersionUID = -5357463983776463053L;
@SuppressWarnings("rawtypes")
public static final Map NOP_MAP = new NOPMap<>();
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> nopMap() {
return NOP_MAP;
}
private NOPMap() {
}
@Override
public int size() {
return 0;
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public boolean containsKey(Object key) {
return false;
}
@Override
public boolean containsValue(Object value) {
return false;
}
@Override
public V get(Object key) {
return null;
}
@Override
public Set<K> keySet() {
return Collections.emptySet();
}
@Override
public Collection<V> values() {
return Collections.emptySet();
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
return Collections.emptySet();
}
@Override
public boolean equals(Object o) {
return (o instanceof Map) && ((Map<?, ?>) o).isEmpty();
}
@Override
public int hashCode() {
return 0;
}
// Override default methods in Map
@Override
public V getOrDefault(Object k, V defaultValue) {
return defaultValue;
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
}
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
Objects.requireNonNull(function);
}
@Override
public V putIfAbsent(K key, V value) {
// nop
return null;
}
@Override
public boolean remove(Object key, Object value) {
// nop
return false;
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
// nop
return false;
}
@Override
public V replace(K key, V value) {
// nop
return null;
}
@Override
public V computeIfAbsent(K key, @NotNull Function<? super K, ? extends V> mappingFunction) {
// nop
return mappingFunction.apply(key);
}
@Override
public V computeIfPresent(K key, @NotNull BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
// nop
return null;
}
@Override
public V compute(K key, @NotNull BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
// nop
return null;
}
@Override
public V merge(K key, @NotNull V value, @NotNull BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
// nop
return null;
}
// Preserves singleton property
private Object readResolve() {
return NOP_MAP;
}
@Override
public V put(K key, V value) {
// nop
return null;
}
@Override
public V remove(Object key) {
// nop
return null;
}
@Override
public void putAll(@NotNull Map<? extends K, ? extends V> m) {
// nop
}
@Override
public void clear() {
// nop
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\api\input\InputEventHandler.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.api.input;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.Minecraft;
/**
* This interface is used for input event handling and is (un-)registered in {@link InputHandlerManager}
*
* @see #handleInput
* @see InputHandlerManager
*/
@Environment(EnvType.CLIENT)
public interface InputEventHandler {
/**
* This method is called from {@link InputHandlerManager#handleInputEvents(Minecraft)}
*
* @see InputHandlerManager#handleInputEvents(Minecraft)
*/
void handleInput(Minecraft client);
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\api\input\InputHandlerManager.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.api.input;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.Minecraft;
import org.jetbrains.annotations.ApiStatus;
import java.util.LinkedHashSet;
/**
* This class allows you to (un-)register {@link InputEventHandler}s
*
* @see InputEventHandler#handleInput(Minecraft)
* @see #handleInputEvents
*/
@Environment(EnvType.CLIENT)
public class InputHandlerManager {
// all methods and fields in this class must be used from main thread only or manual synchronization is required
private static final LinkedHashSet<InputEventHandler> INPUT_HANDLERS = new LinkedHashSet<>();
/**
* This method is called from MinecraftClient.handleInputEvents()
* <br>
* It calls all registered InputEventHandler
*/
@ApiStatus.Internal
public static void handleInputEvents(Minecraft client) {
for (InputEventHandler handler : INPUT_HANDLERS) {
handler.handleInput(client);
}
}
public static boolean registerInputEventHandler(InputEventHandler handler) {
return INPUT_HANDLERS.add(handler);
}
public static boolean removeInputEventHandler(InputEventHandler handler) {
return INPUT_HANDLERS.remove(handler);
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\duck\IKeyBinding.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl.duck;
import com.mojang.blaze3d.platform.InputConstants;
import de.siphalor.amecs.api.KeyModifiers;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
@Environment(EnvType.CLIENT)
public interface IKeyBinding {
InputConstants.Key amecs$getBoundKey();
int amecs$getTimesPressed();
void amecs$setTimesPressed(int timesPressed);
void amecs$incrementTimesPressed();
void amecs$reset();
KeyModifiers amecs$getKeyModifiers();
//# if MC_VERSION_NUMBER < 11500
//- void amecs$setDown(boolean pressed);
//# end
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\duck\IKeyBindingEntry.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl.duck;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.KeyMapping;
@Environment(EnvType.CLIENT)
public interface IKeyBindingEntry {
KeyMapping amecs$getKeyBinding();
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\duck\IMouse.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl.duck;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
@Environment(EnvType.CLIENT)
public interface IMouse {
// this is used by KTIG
boolean amecs$getMouseScrolledEventUsed();
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\mixin\MixinGameOptions.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl.mixin;
import de.siphalor.amecs.impl.AmecsAPIOptions;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.Options;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@SuppressWarnings("WeakerAccess")
@Environment(EnvType.CLIENT)
@Mixin(Options.class)
public class MixinGameOptions {
@Shadow
@Final
public KeyMapping[] keyMappings;
@Inject(method = "save", at = @At("RETURN"))
public void write(CallbackInfo callbackInfo) {
AmecsAPIOptions.write(keyMappings);
}
@Inject(method = "load", at = @At("RETURN"))
public void load(CallbackInfo callbackInfo) {
AmecsAPIOptions.read();
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\mixin\MixinInputUtilType.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl.mixin;
import com.mojang.blaze3d.platform.InputConstants;
import de.siphalor.amecs.api.KeyBindingUtils;
import de.siphalor.amecs.impl.AmecsAPI;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Environment(EnvType.CLIENT)
@Mixin(InputConstants.Type.class)
public abstract class MixinInputUtilType {
@Inject(method = "<clinit>", at = @At("RETURN"))
private static void onRegisterKeyCodes(CallbackInfo callbackInfo) {
createScrollKey("mouse.scroll.up", KeyBindingUtils.MOUSE_SCROLL_UP);
createScrollKey("mouse.scroll.down", KeyBindingUtils.MOUSE_SCROLL_DOWN);
//# if MC_VERSION_NUMBER >= 12002
createScrollKey("mouse.scroll.left", KeyBindingUtils.MOUSE_SCROLL_LEFT);
createScrollKey("mouse.scroll.right", KeyBindingUtils.MOUSE_SCROLL_RIGHT);
//# end
}
@Unique
private static void createScrollKey(String name, int keyCode) {
String keyName = AmecsAPI.makeKeyID(name);
InputConstants.Type.addKey(InputConstants.Type.MOUSE, keyName, keyCode);
// Legacy compatibility (amecsapi <1.3)
InputConstants.Key.NAME_MAP.put("amecsapi.key." + name, InputConstants.getKey(keyName));
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\mixin\MixinKeyBinding.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl.mixin;
import java.util.Map;
import com.mojang.blaze3d.platform.InputConstants;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.network.chat.Component;
//- import net.minecraft.client.resources.language.I18n;
import org.spongepowered.asm.mixin.*;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import de.siphalor.amecs.api.AmecsKeyBinding;
import de.siphalor.amecs.api.KeyModifier;
import de.siphalor.amecs.api.KeyModifiers;
import de.siphalor.amecs.impl.KeyBindingManager;
import de.siphalor.amecs.impl.ModifierPrefixTextProvider;
import de.siphalor.amecs.impl.NOPMap;
import de.siphalor.amecs.impl.duck.IKeyBinding;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
//- import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
@SuppressWarnings("WeakerAccess")
@Environment(EnvType.CLIENT)
@Mixin(KeyMapping.class)
public abstract class MixinKeyBinding implements IKeyBinding {
@Shadow
private InputConstants.Key key;
@Shadow
private int clickCount;
//# if MC_VERSION_NUMBER < 11500
//- @Shadow
//- private boolean isDown;
//# end
@Shadow
@Final
private static Map<String, KeyMapping> ALL;
// set it to a NOPMap meaning everything done with this map is ignored. Because setting it to null would cause problems
// ... even if we remove the put in the KeyMapping constructor. Because maybe in the future this map is used elsewhere or a other mod uses it
@Shadow
@Final
@Mutable
private static Map<InputConstants.Key, KeyMapping> MAP = NOPMap.nopMap();
@Unique
private final KeyModifiers keyModifiers = new KeyModifiers();
@Override
public InputConstants.Key amecs$getBoundKey() {
return key;
}
@Override
public int amecs$getTimesPressed() {
return clickCount;
}
@Override
public void amecs$setTimesPressed(int timesPressed) {
this.clickCount = timesPressed;
}
@Override
public void amecs$incrementTimesPressed() {
clickCount++;
}
@Invoker("release")
@Override
public abstract void amecs$reset();
@Override
public KeyModifiers amecs$getKeyModifiers() {
return keyModifiers;
}
//# if MC_VERSION_NUMBER < 11500
//- @Override
//- public void amecs$setDown(boolean pressed) {
//- isDown = pressed;
//- }
//# end
//# if MC_VERSION_NUMBER >= 12109
@Inject(
method = "<init>(Ljava/lang/String;Lcom/mojang/blaze3d/platform/InputConstants$Type;ILnet/minecraft/client/KeyMapping$Category;)V",
at = @At("RETURN")
)
private void onConstructed(
String id,
InputConstants.Type type,
int defaultCode,
KeyMapping.Category category,
CallbackInfo ci
) {
KeyBindingManager.register((KeyMapping) (Object) this);
}
//# else
//- @Inject(
//- method = "<init>(Ljava/lang/String;Lcom/mojang/blaze3d/platform/InputConstants$Type;ILjava/lang/String;)V",
//- at = @At("RETURN")
//- )
//- private void onConstructed(String id, InputConstants.Type type, int defaultCode, String category, CallbackInfo callbackInfo) {
//- KeyBindingManager.register((KeyMapping) (Object) this);
//- }
//# end
//# if MC_VERSION_NUMBER >= 11600
@Inject(method = "getTranslatedKeyMessage", at = @At("TAIL"), cancellable = true)
public void getLocalizedName(CallbackInfoReturnable<Component> callbackInfoReturnable) {
Component name = key.getDisplayName();
Component fullName;
Font font = Minecraft.getInstance().font;
ModifierPrefixTextProvider.Variation variation = ModifierPrefixTextProvider.Variation.WIDEST;
do {
fullName = name;
for (KeyModifier keyModifier : KeyModifier.VALUES) {
if (keyModifier == KeyModifier.NONE) {
continue;
}
if (keyModifiers.get(keyModifier)) {
fullName = keyModifier.textProvider.getComponent(variation).append(fullName);
}
}
} while ((variation = variation.getSmaller()) != null && font.width(fullName) > 70);
callbackInfoReturnable.setReturnValue(fullName);
}
//# else
//- @Inject(method = "getTranslatedKeyMessage", at = @At("TAIL"), cancellable = true, locals = LocalCapture.CAPTURE_FAILSOFT)
//- public void getLocalizedName(CallbackInfoReturnable<String> callbackInfoReturnable, String i18nName, int keyCode, String glfwName) {
//- String name = (glfwName == null ? I18n.get(i18nName) : glfwName);
//- StringBuilder fullName;
//- Font font = Minecraft.getInstance().font;
//- ModifierPrefixTextProvider.Variation variation = ModifierPrefixTextProvider.Variation.WIDEST;
//- do {
//- fullName = new StringBuilder(name);
//- for (KeyModifier keyModifier : KeyModifier.VALUES) {
//- if (keyModifier == KeyModifier.NONE) {
//- continue;
//- }
//- if (keyModifiers.get(keyModifier)) {
//- fullName.insert(0, keyModifier.textProvider.getTranslation(variation));
//- }
//- }
//- } while ((variation = variation.getSmaller()) != null && font.width(fullName.toString()) > 70);
//- callbackInfoReturnable.setReturnValue(fullName.toString());
//- }
//# end
@Inject(method = "matches", at = @At("RETURN"), cancellable = true)
public void matchesKey(
//# if MC_VERSION_NUMBER >= 12109
KeyEvent event,
//# else
//- int keyCode,
//- int scanCode,
//# end
CallbackInfoReturnable<Boolean> callbackInfoReturnable
) {
if (!keyModifiers.isUnset() && !keyModifiers.equals(KeyModifiers.getCurrentlyPressed())) {
callbackInfoReturnable.setReturnValue(false);
}
}
@Inject(method = "matchesMouse", at = @At("RETURN"), cancellable = true)
public void matchesMouse(
//# if MC_VERSION_NUMBER >= 12109
MouseButtonEvent event,
//# else
//- int mouse,
//# end
CallbackInfoReturnable<Boolean> callbackInfoReturnable
) {
if (!keyModifiers.isUnset() && !keyModifiers.equals(KeyModifiers.getCurrentlyPressed())) {
callbackInfoReturnable.setReturnValue(false);
}
}
@Inject(method = "same", at = @At("RETURN"), cancellable = true)
public void same(KeyMapping other, CallbackInfoReturnable<Boolean> callbackInfoReturnable) {
if (!keyModifiers.equals(((IKeyBinding) other).amecs$getKeyModifiers())) {
callbackInfoReturnable.setReturnValue(false);
}
}
@Inject(method = "click", at = @At("HEAD"), cancellable = true)
private static void onKeyPressed(InputConstants.Key keyCode, CallbackInfo callbackInfo) {
KeyBindingManager.onKeyPressed(keyCode);
callbackInfo.cancel();
}
@Inject(method = "set", at = @At("HEAD"), cancellable = true)
private static void setKeyPressed(InputConstants.Key keyCode, boolean pressed, CallbackInfo callbackInfo) {
KeyBindingManager.setKeyPressed(keyCode, pressed);
callbackInfo.cancel();
}
@Inject(method = "setAll", at = @At("HEAD"), cancellable = true)
private static void updatePressedStates(CallbackInfo callbackInfo) {
KeyBindingManager.updatePressedStates();
callbackInfo.cancel();
}
@Inject(method = "resetMapping", at = @At("HEAD"), cancellable = true)
private static void updateKeysByCode(CallbackInfo callbackInfo) {
KeyBindingManager.updateKeysByCode();
callbackInfo.cancel();
}
@Inject(method = "releaseAll", at = @At("HEAD"), cancellable = true)
private static void unpressAll(CallbackInfo callbackInfo) {
KeyBindingManager.unpressAll();
callbackInfo.cancel();
}
@Inject(method = "setKey", at = @At("RETURN"))
public void setKey(InputConstants.Key key, CallbackInfo callbackInfo) {
if (key == InputConstants.UNKNOWN) {
keyModifiers.unset();
}
}
@Inject(method = "isDefault", at = @At("HEAD"), cancellable = true)
public void isDefault(CallbackInfoReturnable<Boolean> cir) {
if (!((Object) this instanceof AmecsKeyBinding)) {
if (!keyModifiers.isUnset()) {
cir.setReturnValue(false);
}
}
}
@SuppressWarnings("unused")
private static Map<String, KeyMapping> amecs$getIdToKeyBindingMap() {
return ALL;
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\mixin\MixinKeyBindingEntry.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl.mixin;
import com.mojang.blaze3d.platform.InputConstants;
//- import com.mojang.blaze3d.vertex.PoseStack;
import de.siphalor.amecs.api.KeyBindingUtils;
import de.siphalor.amecs.impl.AmecsAPI;
import de.siphalor.amecs.impl.duck.IKeyBindingEntry;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.KeyMapping;
//- import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.*;
import net.minecraft.client.gui.navigation.ScreenRectangle;
//# if MC_VERSION_NUMBER >= 12100
import net.minecraft.client.gui.screens.options.controls.KeyBindsList;
//# else
//- import net.minecraft.client.gui.screens.controls.ControlList;
//- import net.minecraft.client.gui.screens.controls.KeyBindsList;
//# end
import net.minecraft.client.resources.language.I18n;
import net.minecraft.network.chat.Component;
//- import net.minecraft.network.chat.TextComponent;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.contents.TranslatableContents;
//- import org.apache.commons.lang3.StringUtils;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
//- import java.util.ArrayList;
//- import java.util.Arrays;
//- import java.util.List;
@SuppressWarnings("WeakerAccess")
@Environment(EnvType.CLIENT)
//# if MC_VERSION_NUMBER >= 11800
@Mixin(KeyBindsList.KeyEntry.class)
//# else
//- @Mixin(ControlList.KeyEntry.class)
//# end
public abstract class MixinKeyBindingEntry
//# if MC_VERSION_NUMBER >= 11800
extends KeyBindsList.Entry
//# else
//- extends ControlList.Entry
//# end
implements IKeyBindingEntry {
@Unique
private static final String DESCRIPTION_SUFFIX = "." + AmecsAPI.MOD_ID + ".description";
@Shadow
@Final
private KeyMapping key;
@Shadow
@Final
private Button changeButton;
@Unique
//# if MC_VERSION_NUMBER >= 12106
private WidgetTooltipHolder description;
//# elif MC_VERSION_NUMBER >= 11600
//- private List<Component> description;
//# else
//- private List<String> description;
//# end
@Inject(method = "<init>", at = @At("RETURN"))
public void onConstructed(
/*# if MC_VERSION_NUMBER >= 11800 */KeyBindsList/*# else *//*- ControlList *//*# end */ parent,
KeyMapping keyBinding,
/*# if MC_VERSION_NUMBER >= 11600 */Component text,/*# end */
CallbackInfo callbackInfo
) {
String descriptionKey = key.getName() + DESCRIPTION_SUFFIX;
if (I18n.exists(descriptionKey)) {
//# if MC_VERSION_NUMBER >= 12106
description = new WidgetTooltipHolder();
MutableComponent component = MutableComponent.create(new TranslatableContents(
descriptionKey,
"",
new Object[0]
));
description.set(Tooltip.create(component));
//# elif MC_VERSION_NUMBER >= 11600
//- String[] lines = StringUtils.split(I18n.get(descriptionKey), '\n');
//- description = new ArrayList<>(lines.length);
//- for (String line : lines) {
//- //# if MC_VERSION_NUMBER >= 11900
//- description.add(Component.literal(line));
//- //# else
//- description.add(new TextComponent(line));
//- //# end
//- }
//# else
//- description = Arrays.asList(StringUtils.split(I18n.get(descriptionKey), '\n'));
//# end
} else {
description = null;
}
}
//# if MC_VERSION_NUMBER >= 12109
@Inject(method = "renderContent", at = @At("RETURN"), locals = LocalCapture.CAPTURE_FAILSOFT)
public void onRendered(
GuiGraphics context,
int mouseX,
int mouseY,
boolean hovered,
float delta,
CallbackInfo callbackInfo,
int x,
int y
) {
//# elif MC_VERSION_NUMBER >= 12000
//- @Inject(method = "render", at = @At("RETURN"))
//- public void onRendered(GuiGraphics context, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float delta, CallbackInfo callbackInfo) {
//# elif MC_VERSION_NUMBER >= 11600
//- @Inject(method = "render", at = @At("RETURN"))
//- public void onRendered(PoseStack poseStack, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float delta, CallbackInfo callbackInfo) {
//# else
//- @Inject(method = "render", at = @At("RETURN"))
//- public void onRendered(int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float delta, CallbackInfo callbackInfo) {
//# end
if (description != null) {
//# if MC_VERSION_NUMBER >= 12109
description.refreshTooltipForNextRenderPass(
context,
mouseX,
mouseY,
isMouseOverTitle(y, 20, mouseX, mouseY),
changeButton.isFocused(),
new ScreenRectangle(x, y, changeButton.getX(), 20)
);
//# elif MC_VERSION_NUMBER >= 12106
//- description.refreshTooltipForNextRenderPass(
//- context,
//- mouseX,
//- mouseY,
//- isMouseOverTitle(y, entryHeight, mouseX, mouseY),
//- changeButton.isFocused(),
//- new ScreenRectangle(x, y, entryWidth, entryHeight)
//- );
//# else
//- if (isMouseOverTitle(y, entryHeight, mouseX, mouseY)) {
//- //# if MC_VERSION_NUMBER >= 12000
//- context.renderComponentTooltip(Minecraft.getInstance().font, description, mouseX, mouseY);
//- //# elif MC_VERSION_NUMBER >= 11600
//- Minecraft.getInstance().screen.renderComponentTooltip(poseStack, description, mouseX, mouseY);
//- //# else
//- Minecraft.getInstance().screen.renderTooltip(description, mouseX, mouseY);
//- //# end
//- }
//# end
}
}
@Unique
private boolean isMouseOverTitle(int y, int entryHeight, int mouseX, int mouseY) {
//# if MC_VERSION_NUMBER >= 11903
return mouseY >= y && mouseY < y + entryHeight && mouseX < changeButton.getX();
//# else
//- return mouseY >= y && mouseY < y + entryHeight && mouseX < changeButton.x;
//# end
}
@Inject(
method = "method_19870(Lnet/minecraft/client/KeyMapping;Lnet/minecraft/client/gui/components/Button;)V",
at = @At("HEAD")
)
public void onResetButtonClicked(KeyMapping keyBinding, Button buttonWidget, CallbackInfo callbackInfo) {
KeyBindingUtils.resetBoundModifiers(keyBinding);
}
@Inject(method = "method_19871(Lnet/minecraft/client/KeyMapping;Lnet/minecraft/client/gui/components/Button;)V", at = @At("HEAD"))
public void onEditButtonClicked(KeyMapping keyBinding, Button buttonWidget, CallbackInfo callbackInfo) {
key.setKey(InputConstants.UNKNOWN);
}
@Override
public KeyMapping amecs$getKeyBinding() {
return key;
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\mixin\MixinKeybindsScreen.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl.mixin;
import com.mojang.blaze3d.platform.InputConstants;
import de.siphalor.amecs.impl.KeyBindingEditGuiHelper;
import net.minecraft.Util;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.Options;
import net.minecraft.client.gui.screens.Screen;
//# if MC_VERSION_NUMBER >= 12100
import net.minecraft.client.gui.screens.options.OptionsSubScreen;
import net.minecraft.client.gui.screens.options.controls.KeyBindsList;
import net.minecraft.client.gui.screens.options.controls.KeyBindsScreen;
//# else
//- import net.minecraft.client.gui.screens.OptionsSubScreen;
//- import net.minecraft.client.gui.screens.controls.ControlList;
//- import net.minecraft.client.gui.screens.controls.ControlsScreen;
//- import net.minecraft.client.gui.screens.controls.KeyBindsList;
//- import net.minecraft.client.gui.screens.controls.KeyBindsScreen;
//# end
import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.network.chat.Component;
//- import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import de.siphalor.amecs.api.KeyModifier;
import de.siphalor.amecs.api.KeyModifiers;
import de.siphalor.amecs.impl.duck.IKeyBinding;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
@SuppressWarnings("WeakerAccess")
@Environment(EnvType.CLIENT)
//# if MC_VERSION_NUMBER >= 11800
@Mixin(KeyBindsScreen.class)
//# else
//- @Mixin(ControlsScreen.class)
//# end
public abstract class MixinKeybindsScreen
extends /*# if MC_VERSION_NUMBER >= 11500 */OptionsSubScreen/*# else *//*- Screen *//*# end */ {
@Shadow
public KeyMapping selectedKey;
@Shadow
public long lastKeySelection;
//# if MC_VERSION_NUMBER >= 11904
@Shadow private KeyBindsList keyBindsList;
//# end
//# if MC_VERSION_NUMBER < 11500
//- @Shadow @Final
//- private Options options;
//#end
//# if MC_VERSION_NUMBER >= 11500
public MixinKeybindsScreen(Screen screen, Options gameOptions, Component text) {
super(screen, gameOptions, text);
}
//# else
//- public MixinKeybindsScreen(Component title) {
//- super(title);
//- }
//# end
@Inject(
method = "mouseClicked",
//# if MC_VERSION_NUMBER >= 12102
at = @At(value = "INVOKE", target = "Lnet/minecraft/client/KeyMapping;setKey(Lcom/mojang/blaze3d/platform/InputConstants$Key;)V")
//# else
//- at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Options;setKey(Lnet/minecraft/client/KeyMapping;Lcom/mojang/blaze3d/platform/InputConstants$Key;)V")
//# end
)
public void onClicked(
//# if MC_VERSION_NUMBER >= 12109
MouseButtonEvent mouseButtonEvent,
boolean bl,
//# else
//- double x,
//- double y,
//- int type,
//# end
CallbackInfoReturnable<Boolean> callbackInfoReturnable
) {
InputConstants.Key key = ((IKeyBinding) selectedKey).amecs$getBoundKey();
KeyModifiers keyModifiers = ((IKeyBinding) selectedKey).amecs$getKeyModifiers();
if (!key.equals(InputConstants.UNKNOWN)) {
keyModifiers.set(KeyModifier.fromKey(key), true);
}
}
@Inject(
method = "keyPressed",
at = @At(
value = "INVOKE",
//# if MC_VERSION_NUMBER >= 12102
target = "Lnet/minecraft/client/KeyMapping;setKey(Lcom/mojang/blaze3d/platform/InputConstants$Key;)V",
//# else
//- target = "Lnet/minecraft/client/Options;setKey(Lnet/minecraft/client/KeyMapping;Lcom/mojang/blaze3d/platform/InputConstants$Key;)V",
//# end
ordinal = 1
),
cancellable = true
)
public void onKeyPressed(
//# if MC_VERSION_NUMBER >= 12109
KeyEvent keyEvent,
//# else
//- int keyCode,
//- int scanCode,
//- int modifiers,
//# end
CallbackInfoReturnable<Boolean> callbackInfoReturnable
) {
//# if MC_VERSION_NUMBER >= 12109
InputConstants.Key key = InputConstants.getKey(keyEvent);
//# else
//- InputConstants.Key key = InputConstants.getKey(keyCode, scanCode);
//# end
KeyBindingEditGuiHelper.handleKeyPress(selectedKey, key);
this.lastKeySelection = Util.getMillis();
//# if MC_VERSION_NUMBER >= 11904
this.keyBindsList.resetMappingAndUpdateButtons();
//# else
//- KeyMapping.resetMapping();
//# end
callbackInfoReturnable.setReturnValue(true);
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\mixin\MixinKeyboard.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl.mixin;
import com.mojang.blaze3d.platform.InputConstants;
import de.siphalor.amecs.api.KeyModifier;
import de.siphalor.amecs.impl.AmecsAPI;
import de.siphalor.amecs.impl.KeyBindingManager;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.Util;
import net.minecraft.client.KeyboardHandler;
import net.minecraft.client.Minecraft;
//# if MC_VERSION_NUMBER >= 12100
import net.minecraft.client.gui.screens.options.controls.KeyBindsScreen;
//# else
//- import net.minecraft.client.gui.screens.controls.ControlsScreen;
//- import net.minecraft.client.gui.screens.controls.KeyBindsScreen;
//# end
import net.minecraft.client.input.KeyEvent;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Environment(EnvType.CLIENT)
@Mixin(KeyboardHandler.class)
public class MixinKeyboard {
@Inject(method = "keyPress", at = @At(value = "FIELD", target = "Lnet/minecraft/client/Minecraft;screen:Lnet/minecraft/client/gui/screens/Screen;", ordinal = 0, shift = At.Shift.BEFORE), cancellable = true)
private void onKeyPriority(
long window,
//# if MC_VERSION_NUMBER < 12109
//- int keyCode,
//- int scanCode,
//# end
int action,
//# if MC_VERSION_NUMBER >= 12109
KeyEvent keyEvent,
//# else
//- int modifiers,
//# end
CallbackInfo callbackInfo
) {
//# if MC_VERSION_NUMBER >= 12109
InputConstants.Key key = InputConstants.getKey(keyEvent);
//# else
//- InputConstants.Key key = InputConstants.getKey(keyCode, scanCode);
//# end
if (action == 1) {
if (KeyBindingManager.onKeyPressedPriority(key)) {
callbackInfo.cancel();
}
} else if (action == 0) {
if (KeyBindingManager.onKeyReleasedPriority(key)) {
callbackInfo.cancel();
}
}
}
@Inject(method = "keyPress", at = @At(value = "FIELD", target = "Lnet/minecraft/client/KeyboardHandler;debugCrashKeyTime:J", ordinal = 0))
private void onKey(
long window,
//# if MC_VERSION_NUMBER < 12109
//- int keyCode,
//- int scanCode,
//# end
int action,
//# if MC_VERSION_NUMBER >= 12109
KeyEvent keyEvent,
//# else
//- int modifiers,
//# end
CallbackInfo callbackInfo
) {
// Key released
//# if MC_VERSION_NUMBER >= 11800
if (action == 0 && Minecraft.getInstance().screen instanceof KeyBindsScreen screen) {
//# else
//- if (action == 0 && Minecraft.getInstance().screen instanceof ControlsScreen) {
//- ControlsScreen screen = (ControlsScreen) Minecraft.getInstance().screen;
//# end
screen.selectedKey = null;
screen.lastKeySelection = Util.getMillis();
}
//# if MC_VERSION_NUMBER >= 12109
InputConstants.Key key = InputConstants.getKey(keyEvent);
//# else
//- InputConstants.Key key = InputConstants.getKey(keyCode, scanCode);
//# end
AmecsAPI.CURRENT_MODIFIERS.set(KeyModifier.fromKeyCode(key.getValue()), action != 0);
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\mixin\MixinMinecraftClient.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl.mixin;
import de.siphalor.amecs.api.input.InputHandlerManager;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.Minecraft;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Environment(EnvType.CLIENT)
@Mixin(value = Minecraft.class, priority = 50)
public abstract class MixinMinecraftClient {
@Inject(method = "handleKeybinds()V", at = @At(value = "HEAD"))
private void handleInputEvents(CallbackInfo ci) {
InputHandlerManager.handleInputEvents((Minecraft) (Object) this);
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\mixin\MixinMouse.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl.mixin;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.mojang.blaze3d.platform.InputConstants;
import de.siphalor.amecs.api.KeyBindingUtils;
import de.siphalor.amecs.api.KeyModifier;
import de.siphalor.amecs.api.KeyModifiers;
import de.siphalor.amecs.impl.AmecsAPI;
import de.siphalor.amecs.impl.KeyBindingManager;
import de.siphalor.amecs.impl.duck.IKeyBinding;
import de.siphalor.amecs.impl.duck.IMouse;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.Minecraft;
import net.minecraft.client.MouseHandler;
import net.minecraft.client.gui.screens.Screen;
//# if MC_VERSION_NUMBER >= 12100
import net.minecraft.client.gui.screens.options.controls.KeyBindsScreen;
//# else
//- import net.minecraft.client.gui.screens.controls.ControlsScreen;
//- import net.minecraft.client.gui.screens.controls.KeyBindsScreen;
//# end
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.client.input.MouseButtonInfo;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
// TODO: Fix the priority when Mixin 0.8 is a thing and try again (-> MaLiLib causes incompatibilities)
@Environment(EnvType.CLIENT)
@Mixin(value = MouseHandler.class, priority = -2000)
public class MixinMouse implements IMouse {
@Shadow
@Final
private Minecraft minecraft;
@Unique
private boolean mouseScrolled_eventUsed;
@Override
public boolean amecs$getMouseScrolledEventUsed() {
return mouseScrolled_eventUsed;
}
@Inject(
//# if MC_VERSION_NUMBER >= 12109
method = "onButton",
//# else
//- method = "onPress",
//# end
at = @At(value = "FIELD", target = "Lnet/minecraft/client/Minecraft;screen:Lnet/minecraft/client/gui/screens/Screen;", ordinal = 0),
cancellable = true
)
//# if MC_VERSION_NUMBER >= 12109
private void onMouseButtonPriority(long window, MouseButtonInfo event, int state, CallbackInfo callbackInfo) {
if (state == 1
&& KeyBindingManager.onKeyPressedPriority(InputConstants.Type.MOUSE.getOrCreate(event.button()))) {
callbackInfo.cancel();
}
}
//# else
//- private void onMouseButtonPriority(long window, int type, int state, int int_3, CallbackInfo callbackInfo) {
//- if (state == 1 && KeyBindingManager.onKeyPressedPriority(InputConstants.Type.MOUSE.getOrCreate(type))) {
//- callbackInfo.cancel();
//- }
//- }
//# end
@Unique
//# if MC_VERSION_NUMBER >= 12002
private void onScrollReceived(double scrollAmountX, double scrollAmountY) {
InputConstants.Key keyCodeX = KeyBindingUtils.getKeyFromHorizontalScroll(scrollAmountX);
if (keyCodeX != null) {
handleScrollKey(keyCodeX, scrollAmountX);
}
//# else
//- private void onScrollReceived(double scrollAmountY) {
//# end
InputConstants.Key keyCodeY = KeyBindingUtils.getKeyFromVerticalScroll(scrollAmountY);
if (keyCodeY != null) {
handleScrollKey(keyCodeY, scrollAmountY);
}
}
@Unique
private void handleScrollKey(@NotNull InputConstants.Key key, double amount) {
KeyMapping.set(key, true);
amount = Math.abs(amount);
while (amount > 0) {
KeyMapping.click(key);
amount--;
}
KeyMapping.set(key, false);
}
@SuppressWarnings("InvalidInjectorMethodSignature")
@Inject(method = "onScroll", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;isSpectator()Z", ordinal = 0), locals = LocalCapture.CAPTURE_FAILHARD)
//# if MC_VERSION_NUMBER >= 12002
private void isSpectator_onMouseScroll(long window, double rawX, double rawY, CallbackInfo callbackInfo, boolean discreteScroll, double sensitivity, double scrollAmountX, double scrollAmountY) {
//# else
//- private void isSpectator_onMouseScroll(long window, double rawX, double rawY, CallbackInfo callbackInfo, double scrollAmountY) {
//# end
if (AmecsAPI.TRIGGER_KEYBINDING_ON_SCROLL) {
//# if MC_VERSION_NUMBER >= 12002
this.onScrollReceived(scrollAmountX, scrollAmountY);
//# else
//- this.onScrollReceived(scrollAmountY);
//# end
}
}
//# if MC_VERSION_NUMBER >= 12002
@WrapOperation(method = "onScroll", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screens/Screen;mouseScrolled(DDDD)Z"))
private boolean onMouseScrolledScreen(Screen screen, double mouseX, double mouseY, double xScrollAmount, double yScrollAmount, Operation<Boolean> original) {
Boolean handled = original.call(screen, mouseX, mouseY, xScrollAmount, yScrollAmount);
return onMouseScrolledScreen(handled, xScrollAmount, yScrollAmount);
}
//# else
//- @WrapOperation(method = "onScroll", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screens/Screen;mouseScrolled(DDD)Z"))
//- private boolean onMouseScrolledScreen(Screen screen, double mouseX, double mouseY, double yScrollAmount, Operation<Boolean> original) {
//- Boolean handled = original.call(screen, mouseX, mouseY, yScrollAmount);
//- return amecs$onMouseScrolledScreen(handled, yScrollAmount);
//- }
//# end
@Unique
private boolean onMouseScrolledScreen(
boolean handled,
//# if MC_VERSION_NUMBER >= 12002
double xScrollAmount,
//# end
double yScrollAmount
) {
this.mouseScrolled_eventUsed = handled;
if (handled) {
return true;
}
if (AmecsAPI.TRIGGER_KEYBINDING_ON_SCROLL) {
//# if MC_VERSION_NUMBER >= 12002
this.onScrollReceived(xScrollAmount, yScrollAmount);
//# else
//- this.onScrollReceived(yScrollAmount);
//# end
}
return false;
}
@Inject(method = "onScroll", at = @At(value = "FIELD", target = "Lnet/minecraft/client/Minecraft;screen:Lnet/minecraft/client/gui/screens/Screen;", ordinal = 0), locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true)
//# if MC_VERSION_NUMBER >= 12002
private void onMouseScroll(long window, double rawX, double rawY, CallbackInfo callbackInfo, boolean discreteScroll, double sensitivity, double scrollAmountX, double scrollAmountY) {
//# else
//- private void onMouseScroll(long window, double rawX, double rawY, CallbackInfo callbackInfo, double scrollAmountY) {
//# end
InputConstants.Key keyCodeY = KeyBindingUtils.getKeyFromVerticalScroll(scrollAmountY);
//# if MC_VERSION_NUMBER >= 12002
InputConstants.Key keyCodeX = KeyBindingUtils.getKeyFromHorizontalScroll(scrollAmountX);
InputConstants.Key primaryKeyCode = keyCodeY != null ? keyCodeY : keyCodeX;
//# else
//- InputConstants.Key primaryKeyCode = keyCodeY;
//# end
// check if we have scroll input for the options screen
//# if MC_VERSION_NUMBER >= 11800
if (minecraft.screen instanceof KeyBindsScreen) {
//# else
//- if (minecraft.screen instanceof ControlsScreen) {
//# end
if (handleScrollInKeybindsScreen(callbackInfo, primaryKeyCode)) return;
}
// Legacy support
//noinspection deprecation
KeyBindingUtils.setLastScrollAmount(scrollAmountY);
if (KeyBindingManager.onKeyPressedPriority(keyCodeY)) {
callbackInfo.cancel();
}
//# if MC_VERSION_NUMBER >= 12002
if (KeyBindingManager.onKeyPressedPriority(keyCodeX)) {
callbackInfo.cancel();
}
//# end
}
@Unique
private boolean handleScrollInKeybindsScreen(CallbackInfo callbackInfo, InputConstants.Key primaryKeyCode) {
assert minecraft.screen != null;
//# if MC_VERSION_NUMBER >= 11800
KeyMapping focusedBinding = ((KeyBindsScreen) minecraft.screen).selectedKey;
//# else
//- KeyMapping focusedBinding = ((ControlsScreen) minecraft.screen).selectedKey;
//# end
if (focusedBinding != null) {
if (!focusedBinding.isUnbound()) {
KeyModifiers keyModifiers = ((IKeyBinding) focusedBinding).amecs$getKeyModifiers();
keyModifiers.set(KeyModifier.fromKey(((IKeyBinding) focusedBinding).amecs$getBoundKey()), true);
}
// This is a bit hacky, but the easiest way out
// If the selected binding != null, the mouse x and y will always be ignored - so no need to convert them
//# if MC_VERSION_NUMBER >= 12109
minecraft.screen.mouseClicked(
new MouseButtonEvent(0D, 0D, new MouseButtonInfo(primaryKeyCode.getValue(), 0)),
true
);
//# else
//- minecraft.screen.mouseClicked(-1, -1, primaryKeyCode.getValue());
//# end
// if we do we cancel the method because we do not want the current screen to get the scroll event
callbackInfo.cancel();
return true;
}
return false;
}
}
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\compat\controlling\AmecsControllingIntegration.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl.compat.controlling;
import com.blamejared.controlling.api.event.ControllingEvents;
import de.siphalor.amecs.api.KeyBindingUtils;
import de.siphalor.amecs.api.KeyModifier;
import de.siphalor.amecs.impl.KeyBindingEditGuiHelper;
//# if CONTROLLING_INTEGRATION
public class AmecsControllingIntegration {
public static void initialize() {
ControllingEvents.IS_KEY_CODE_MODIFIER_EVENT.register(
event -> KeyModifier.fromKey(event.key()) != null
);
ControllingEvents.SET_TO_DEFAULT_EVENT.register(event -> {
KeyBindingUtils.resetBoundModifiers(event.mapping());
return false;
});
ControllingEvents.SET_KEY_EVENT.register(event -> {
KeyBindingEditGuiHelper.handleKeyPress(event.mapping(), event.key());
return true;
});
}
}
//# end
|
amecs-api
|
src\main\java\de\siphalor\amecs\impl\mixin\compat\controlling\MixinControllingKeyBindingEntry.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.impl.mixin.compat.controlling;
import com.blamejared.controlling.client.NewKeyBindsList;
import com.mojang.blaze3d.platform.InputConstants;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.gui.components.Button;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
//# if CONTROLLING_INTEGRATION
@Mixin(value = NewKeyBindsList.KeyEntry.class, remap = false)
public abstract class MixinControllingKeyBindingEntry {
@Inject(method = "lambda$new$0", at = @At("HEAD"))
public void onEditButtonClicked(KeyMapping keyBinding, Button button, CallbackInfo callbackInfo) {
keyBinding.setKey(InputConstants.UNKNOWN);
}
}
//# end
|
amecs-api
|
src\main\resources\assets\amecsapi\lang\de_de.json
|
{
"key.amecsapi.mouse.scroll.up": "Hochscrollen",
"key.amecsapi.mouse.scroll.down": "Herunterscrollen",
"amecsapi.modifier.alt": "Alt",
"amecsapi.modifier.alt.short": "Alt",
"amecsapi.modifier.alt.tiny": "A",
"amecsapi.modifier.control": "Steuerung",
"amecsapi.modifier.control.short": "Strg",
"amecsapi.modifier.control.tiny": "S",
"amecsapi.modifier.shift": "Umschalt",
"amecsapi.modifier.shift.short": "Umst",
"amecsapi.modifier.shift.tiny": "U",
"key.amecsapi.mouse.scroll.right": "Nach Rechts scrollen",
"key.amecsapi.mouse.scroll.left": "Nach Links scrollen"
}
|
amecs-api
|
src\main\resources\assets\amecsapi\lang\en_us.json
|
{
"key.amecsapi.mouse.scroll.up": "Scroll Up",
"key.amecsapi.mouse.scroll.down": "Scroll Down",
"key.amecsapi.mouse.scroll.left": "Scroll Left",
"key.amecsapi.mouse.scroll.right": "Scroll Right",
"amecsapi.modifier.alt": "Alt",
"amecsapi.modifier.alt.short": "Alt",
"amecsapi.modifier.alt.tiny": "A",
"amecsapi.modifier.control": "Control",
"amecsapi.modifier.control.short": "Ctrl",
"amecsapi.modifier.control.tiny": "C",
"amecsapi.modifier.shift": "Shift",
"amecsapi.modifier.shift.short": "Shft",
"amecsapi.modifier.shift.tiny": "S"
}
|
amecs-api
|
src\main\resources\assets\amecsapi\lang\et_ee.json
|
{}
|
amecs-api
|
src\main\resources\assets\amecsapi\lang\fi_fi.json
|
{
"amecsapi.modifier.alt.tiny": "A",
"amecsapi.modifier.control": "Control",
"amecsapi.modifier.control.short": "Ctrl",
"amecsapi.modifier.control.tiny": "C",
"amecsapi.modifier.shift": "Shift",
"amecsapi.modifier.shift.short": "Shft",
"amecsapi.modifier.shift.tiny": "S",
"amecsapi.modifier.alt": "Alt",
"amecsapi.modifier.alt.short": "Alt",
"key.amecsapi.mouse.scroll.up": "Selaa Ylös",
"key.amecsapi.mouse.scroll.down": "Selaa Alas"
}
|
amecs-api
|
src\main\resources\assets\amecsapi\lang\he_il.json
|
{
"key.amecsapi.mouse.scroll.down": "גלול למטה",
"key.amecsapi.mouse.scroll.right": "גלול לימין",
"amecsapi.modifier.alt": "טאב",
"amecsapi.modifier.alt.short": "אלט",
"amecsapi.modifier.alt.tiny": "ש",
"amecsapi.modifier.control": "קונטרול",
"amecsapi.modifier.control.tiny": "ב",
"amecsapi.modifier.shift": "שיפט",
"amecsapi.modifier.shift.short": "שיפט",
"amecsapi.modifier.shift.tiny": "ד",
"key.amecsapi.mouse.scroll.up": "גלול למלה",
"key.amecsapi.mouse.scroll.left": "גלול לשמאל",
"amecsapi.modifier.control.short": "קונטרול"
}
|
amecs-api
|
src\main\resources\assets\amecsapi\lang\it_it.json
|
{
"key.amecsapi.mouse.scroll.down": "Scorrere verso il basso",
"amecsapi.modifier.alt": "Alt",
"amecsapi.modifier.alt.short": "Alt",
"amecsapi.modifier.alt.tiny": "A",
"amecsapi.modifier.control.short": "Ctrl",
"amecsapi.modifier.control.tiny": "C",
"amecsapi.modifier.shift": "Maiuscolo",
"amecsapi.modifier.shift.short": "Maiusc",
"amecsapi.modifier.shift.tiny": "S",
"amecsapi.modifier.control": "Control",
"key.amecsapi.mouse.scroll.up": "Scorrere verso l'alto"
}
|
amecs-api
|
src\main\resources\assets\amecsapi\lang\ko_kr.json
|
{}
|
amecs-api
|
src\main\resources\assets\amecsapi\lang\pl_pl.json
|
{
"key.amecsapi.mouse.scroll.down": "Przewinięcie w dół",
"key.amecsapi.mouse.scroll.left": "Przewinięcie w lewo",
"key.amecsapi.mouse.scroll.right": "Przewinięcie w prawo",
"amecsapi.modifier.alt": "Alt",
"amecsapi.modifier.alt.short": "Alt",
"amecsapi.modifier.alt.tiny": "A",
"amecsapi.modifier.control": "Control",
"amecsapi.modifier.control.short": "Ctrl",
"amecsapi.modifier.control.tiny": "C",
"amecsapi.modifier.shift": "Shift",
"amecsapi.modifier.shift.short": "Shft",
"amecsapi.modifier.shift.tiny": "S",
"key.amecsapi.mouse.scroll.up": "Przewinięcie w górę"
}
|
amecs-api
|
src\main\resources\assets\amecsapi\lang\pt_br.json
|
{
"amecsapi.modifier.alt": "Alt",
"amecsapi.modifier.alt.short": "Alt",
"amecsapi.modifier.alt.tiny": "A",
"amecsapi.modifier.control": "Control",
"amecsapi.modifier.control.short": "Ctrl",
"amecsapi.modifier.control.tiny": "C",
"amecsapi.modifier.shift": "Shift",
"amecsapi.modifier.shift.short": "Shft",
"amecsapi.modifier.shift.tiny": "S",
"key.amecsapi.mouse.scroll.up": "Rolar para cima",
"key.amecsapi.mouse.scroll.down": "Rolar para baixo"
}
|
amecs-api
|
src\main\resources\assets\amecsapi\lang\pt_pt.json
|
{
"key.amecsapi.mouse.scroll.up": "Rolar para cima",
"key.amecsapi.mouse.scroll.down": "Rolar para baixo",
"amecsapi.modifier.alt": "Alt",
"amecsapi.modifier.alt.short": "Alt",
"amecsapi.modifier.alt.tiny": "A",
"amecsapi.modifier.control": "Control",
"amecsapi.modifier.control.short": "Ctrl",
"amecsapi.modifier.control.tiny": "C",
"amecsapi.modifier.shift": "Shift",
"amecsapi.modifier.shift.short": "Shft",
"amecsapi.modifier.shift.tiny": "S"
}
|
amecs-api
|
src\main\resources\assets\amecsapi\lang\ru_ru.json
|
{
"key.amecsapi.mouse.scroll.left": "Пролистать влево",
"key.amecsapi.mouse.scroll.right": "Пролистать вправо",
"amecsapi.modifier.alt": "Alt",
"amecsapi.modifier.alt.tiny": "A",
"amecsapi.modifier.alt.short": "Alt",
"amecsapi.modifier.control": "Control",
"amecsapi.modifier.control.short": "Ctrl",
"amecsapi.modifier.control.tiny": "C",
"amecsapi.modifier.shift": "Shift",
"amecsapi.modifier.shift.short": "Shft",
"amecsapi.modifier.shift.tiny": "S",
"key.amecsapi.mouse.scroll.up": "Пролистать вверх",
"key.amecsapi.mouse.scroll.down": "Пролистать вниз"
}
|
amecs-api
|
src\main\resources\assets\amecsapi\lang\tr_tr.json
|
{}
|
amecs-api
|
src\main\resources\assets\amecsapi\lang\uk_ua.json
|
{
"amecsapi.modifier.shift": "Shift",
"amecsapi.modifier.control": "Control",
"amecsapi.modifier.shift.tiny": "S",
"amecsapi.modifier.shift.short": "Shft",
"amecsapi.modifier.control.short": "Ctrl",
"amecsapi.modifier.control.tiny": "C",
"amecsapi.modifier.alt.short": "Alt",
"amecsapi.modifier.alt": "Alt",
"amecsapi.modifier.alt.tiny": "A",
"key.amecsapi.mouse.scroll.left": "Прогорнути ліворуч",
"key.amecsapi.mouse.scroll.down": "Прогорнути вниз",
"key.amecsapi.mouse.scroll.right": "Прогорнути праворуч",
"key.amecsapi.mouse.scroll.up": "Прогорнути вгору"
}
|
amecs-api
|
src\main\resources\assets\amecsapi\lang\zh_cn.json
|
{
"key.amecsapi.mouse.scroll.down": "向下滚动",
"key.amecsapi.mouse.scroll.left": "向左滚动",
"key.amecsapi.mouse.scroll.right": "向右滚动",
"amecsapi.modifier.alt": "Alt",
"amecsapi.modifier.alt.short": "Alt",
"amecsapi.modifier.alt.tiny": "A",
"amecsapi.modifier.control": "Control",
"amecsapi.modifier.control.short": "Ctrl",
"amecsapi.modifier.control.tiny": "C",
"amecsapi.modifier.shift": "Shift",
"amecsapi.modifier.shift.short": "Shft",
"amecsapi.modifier.shift.tiny": "S",
"key.amecsapi.mouse.scroll.up": "向上滚动"
}
|
amecs-api
|
src\testmod\resources\fabric.mod.json
|
{
"schemaVersion": 1,
"id": "amecsapi-testmod",
"version": "${version}",
"name": "Amecs API",
"description": "Testmod for Amecs API",
"authors": [
"Siphalor"
],
"contributors": [],
"contact": {},
"license": "Apache-2.0",
"icon": "assets/amecsapi/icon.png",
"environment": "client",
"entrypoints": {
"main": [],
"client": [
"de.siphalor.amecs.testmod.ClientInit"
],
"server": []
},
"depends": {
"fabricloader": ">=0.4.0",
"amecsapi": "*"
}
}
|
amecs-api
|
src\testmod\java\de\siphalor\amecs\testmod\ClientInit.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.testmod;
import com.mojang.blaze3d.platform.InputConstants;
import de.siphalor.amecs.api.KeyModifiers;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
import net.minecraft.client.KeyMapping;
import net.minecraft.resources.ResourceLocation;
import org.lwjgl.glfw.GLFW;
public class ClientInit implements ClientModInitializer {
@Override
public void onInitializeClient() {
KeyBindingHelper.registerKeyBinding(new TestPriorityKeybinding(
//# if MC_VERSION_NUMBER >= 12100
ResourceLocation.fromNamespaceAndPath("amecsapi-testmod", "priority"),
//# else
//- new ResourceLocation("amecsapi-testmod", "priority"),
//# end
InputConstants.Type.KEYSYM,
GLFW.GLFW_KEY_Z,
//# if MC_VERSION_NUMBER >= 12109
KeyMapping.Category.MISC,
//# else
//- "key.categories.misc",
//# end
new KeyModifiers(),
() -> {
System.out.println("priority");
return true;
},
() -> {
System.out.println("priority release");
return true;
}
));
}
}
|
amecs-api
|
src\testmod\java\de\siphalor\amecs\testmod\TestPriorityKeybinding.java
|
/*
* Copyright 2020 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.siphalor.amecs.testmod;
import com.mojang.blaze3d.platform.InputConstants;
import de.siphalor.amecs.api.AmecsKeyBinding;
import de.siphalor.amecs.api.KeyModifiers;
import de.siphalor.amecs.api.PriorityKeyBinding;
import net.minecraft.resources.ResourceLocation;
import java.util.function.BooleanSupplier;
public class TestPriorityKeybinding extends AmecsKeyBinding implements PriorityKeyBinding {
private final BooleanSupplier action;
private final BooleanSupplier releaseAction;
public TestPriorityKeybinding(
ResourceLocation id,
InputConstants.Type type,
int code,
//# if MC_VERSION_NUMBER >= 12109
Category category,
//# else
//- String category,
//# end
KeyModifiers defaultModifiers,
BooleanSupplier action,
BooleanSupplier releaseAction
) {
super(id, type, code, category, defaultModifiers);
this.action = action;
this.releaseAction = releaseAction;
}
@Override
public boolean onPressedPriority() {
return action.getAsBoolean();
}
@Override
public boolean onReleasedPriority() {
return releaseAction.getAsBoolean();
}
}
|
amecs-api
|
src\testmod\resources\assets\amecsapi-testmod\lang\en_us.json
|
{
"key.amecsapi-testmod.priority": "Priority Keybinding",
"key.amecsapi-testmod.priority.amecsapi.description": "A Keybinding that tests the priority execution using Amecs API.\nSupports line breaks."
}
|
amidst
|
biome\test.json
|
{ "name":"test", "colorMap":[
[ 0, { "r":0, "g":0, "b":112 } ],
[ 1, { "r":141, "g":179, "b":96 } ],
[ 2, { "r":250, "g":148, "b":24 } ],
[ 3, { "r":96, "g":96, "b":96 } ],
[ 4, { "r":5, "g":102, "b":33 } ],
[ 5, { "r":11, "g":2, "b":89 } ],
[ 6, { "r":7, "g":249, "b":178 } ],
[ 7, { "r":0, "g":0, "b":255 } ],
[ 8, { "r":255, "g":0, "b":0 } ],
[ 9, { "r":128, "g":128, "b":255 } ],
[ 10, { "r":112, "g":112, "b":214 } ],
[ 11, { "r":160, "g":160, "b":255 } ],
[ 12, { "r":255, "g":255, "b":255 } ],
[ 13, { "r":160, "g":160, "b":160 } ],
[ 14, { "r":255, "g":0, "b":255 } ],
[ 15, { "r":160, "g":0, "b":255 } ],
[ 16, { "r":250, "g":222, "b":85 } ],
[ 17, { "r":210, "g":95, "b":18 } ],
[ 18, { "r":34, "g":85, "b":28 } ],
[ 19, { "r":22, "g":57, "b":51 } ],
[ 20, { "r":114, "g":120, "b":154 } ],
[ 21, { "r":83, "g":123, "b":9 } ],
[ 22, { "r":44, "g":66, "b":5 } ],
[ 23, { "r":98, "g":139, "b":23 } ],
[ 24, { "r":0, "g":0, "b":48 } ],
[ 25, { "r":162, "g":162, "b":132 } ],
[ 26, { "r":250, "g":240, "b":192 } ],
[ 27, { "r":48, "g":116, "b":68 } ],
[ 28, { "r":31, "g":5, "b":50 } ],
[ 29, { "r":64, "g":81, "b":26 } ],
[ 30, { "r":49, "g":85, "b":74 } ],
[ 31, { "r":36, "g":63, "b":54 } ],
[ 32, { "r":89, "g":102, "b":81 } ],
[ 33, { "r":69, "g":7, "b":62 } ],
[ 34, { "r":80, "g":112, "b":80 } ],
[ 35, { "r":189, "g":18, "b":95 } ],
[ 36, { "r":167, "g":157, "b":100 } ],
[ 37, { "r":217, "g":69, "b":21 } ],
[ 38, { "r":17, "g":151, "b":101 } ],
[ 39, { "r":202, "g":140, "b":101 } ],
[ 40, { "r":128, "g":128, "b":255 } ],
[ 41, { "r":128, "g":128, "b":255 } ],
[ 42, { "r":128, "g":128, "b":255 } ],
[ 43, { "r":128, "g":128, "b":255 } ],
[ 44, { "r":0, "g":0, "b":172 } ],
[ 45, { "r":0, "g":0, "b":144 } ],
[ 46, { "r":32, "g":32, "b":112 } ],
[ 47, { "r":0, "g":0, "b":80 } ],
[ 48, { "r":0, "g":0, "b":64 } ],
[ 49, { "r":32, "g":32, "b":56 } ],
[ 50, { "r":64, "g":64, "b":144 } ],
[ 127, { "r":0, "g":0, "b":0 } ],
[ 129, { "r":181, "g":219, "b":136 } ],
[ 130, { "r":255, "g":188, "b":64 } ],
[ 131, { "r":136, "g":136, "b":136 } ],
[ 132, { "r":45, "g":142, "b":73 } ],
[ 133, { "r":51, "g":142, "b":19 } ],
[ 134, { "r":47, "g":255, "b":18 } ],
[ 140, { "r":180, "g":20, "b":220 } ],
[ 149, { "r":123, "g":13, "b":49 } ],
[ 151, { "r":138, "g":179, "b":63 } ],
[ 155, { "r":88, "g":156, "b":108 } ],
[ 156, { "r":71, "g":15, "b":90 } ],
[ 157, { "r":104, "g":121, "b":66 } ],
[ 158, { "r":89, "g":125, "b":114 } ],
[ 160, { "r":129, "g":142, "b":121 } ],
[ 161, { "r":109, "g":119, "b":102 } ],
[ 162, { "r":120, "g":52, "b":120 } ],
[ 163, { "r":229, "g":218, "b":135 } ],
[ 164, { "r":207, "g":197, "b":140 } ],
[ 165, { "r":255, "g":109, "b":61 } ],
[ 166, { "r":216, "g":191, "b":141 } ],
[ 167, { "r":242, "g":180, "b":141 } ],
[ 168, { "r":118, "g":142, "b":20 } ],
[ 169, { "r":59, "g":71, "b":10 } ],
[ 170, { "r":82, "g":41, "b":33 } ],
[ 171, { "r":221, "g":8, "b":8 } ],
[ 172, { "r":73, "g":144, "b":123 } ] ] }
|
amidst
|
src\main\java\amidst\Amidst.java
|
package amidst;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledByAny;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.gui.crash.CrashWindow;
import amidst.logging.AmidstLogger;
import amidst.logging.AmidstMessageBox;
import amidst.logging.FileLogger;
import amidst.mojangapi.file.DotMinecraftDirectoryNotFoundException;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.ParserProperties;
import java.awt.EventQueue;
import java.awt.image.BufferedImage;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.prefs.Preferences;
/**
* The entry point class to the Amidst application.
*/
@NotThreadSafe
public class Amidst {
/**
* A list of icon images for windows.
*/
public static final List<BufferedImage> BUFFERED_IMAGES = List.of(
ResourceLoader.getImage("/amidst/icon/amidst-16x16.png"),
ResourceLoader.getImage("/amidst/icon/amidst-32x32.png"),
ResourceLoader.getImage("/amidst/icon/amidst-48x48.png"),
ResourceLoader.getImage("/amidst/icon/amidst-64x64.png"),
ResourceLoader.getImage("/amidst/icon/amidst-128x128.png"),
ResourceLoader.getImage("/amidst/icon/amidst-256x256.png")
);
/**
* The version of Amidst running.
*/
public static final AmidstVersion VERSION = AmidstVersion.from(ResourceLoader.getProperties("/amidst/metadata.properties"));
/**
* The entry point to the Amidst application.
*
* @param args command line arguments (see the wiki)
*/
@CalledOnlyBy(AmidstThread.STARTUP)
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler((thread, e) -> handleCrash(e, thread));
// Parse CLI arguments
CommandLineParameters parameters = new CommandLineParameters();
CmdLineParser parser = new CmdLineParser(
parameters,
ParserProperties.defaults().withShowDefaults(false).withUsageWidth(120).withOptionSorter(null));
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.out.println(VERSION.createLongVersionString());
System.err.println(e.getMessage());
parser.printUsage(System.out);
System.exit(2);
}
// initialize file logging
if (parameters.logFile != null) {
AmidstLogger.info("using log file: '" + parameters.logFile + "'");
AmidstLogger.addListener("file", new FileLogger(parameters.logFile));
}
String versionString = VERSION.createLongVersionString();
// Printing the help guide prints and exits
if (parameters.printHelp) {
System.out.println(versionString);
parser.printUsage(System.out);
return;
}
// Printing the version prints and exits
if (parameters.printVersion) {
System.out.println(versionString);
return;
}
// Log system information
AmidstLogger.info(versionString);
AmidstLogger.info("Current system time: " + new Timestamp(new Date().getTime()));
AmidstLogger.info(createPropertyString("os.name"));
AmidstLogger.info(createPropertyString("os.version"));
AmidstLogger.info(createPropertyString("os.arch"));
AmidstLogger.info(createPropertyString("java.version"));
AmidstLogger.info(createPropertyString("java.vendor"));
AmidstLogger.info(createPropertyString("sun.arch.data.model"));
// Start application
EventQueue.invokeLater(() -> {
AmidstSettings settings = new AmidstSettings(Preferences.userNodeForPackage(Amidst.class));
try {
settings.lookAndFeel.get().tryApply();
new Application(parameters, settings).run();
} catch (DotMinecraftDirectoryNotFoundException e) {
AmidstLogger.warn(e);
AmidstMessageBox.displayError(
"Please install Minecraft",
"Amidst is not able to find your '.minecraft' directory, but it requires a working Minecraft installation.");
} catch (Exception e) {
handleCrash(e, Thread.currentThread());
}
});
}
private static String createPropertyString(String key) {
StringBuilder b = new StringBuilder();
b.append("System.getProperty(\"");
b.append(key);
b.append("\") == '");
b.append(System.getProperty(key));
b.append("'");
return b.toString();
}
/**
* On an uncaught exception, this logs it and shows a new window.
*
* @param e the uncaught exception
* @param thread the thread Amidst crashed on
*/
@CalledByAny
private static void handleCrash(Throwable e, Thread thread) {
String message = "Amidst has encounted an uncaught exception on the thread " + thread;
try {
AmidstLogger.crash(e, message);
CrashWindow.showAfterCrash();
} catch (Throwable t) {
System.err.println("Amidst crashed!");
System.err.println(message);
e.printStackTrace();
}
}
}
|
amidst
|
src\main\java\amidst\AmidstSettings.java
|
package amidst;
import java.util.prefs.Preferences;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.ThreadSafe;
import amidst.gui.main.AmidstLookAndFeel;
import amidst.mojangapi.world.Dimension;
import amidst.mojangapi.world.WorldType;
import amidst.settings.Setting;
import amidst.settings.biomeprofile.BiomeProfile;
import amidst.settings.biomeprofile.BiomeProfileSelection;
@ThreadSafe
public class AmidstSettings {
public final Setting<Dimension> dimension;
public final Setting<Boolean> showGrid;
public final Setting<Boolean> showSlimeChunks;
public final Setting<Boolean> showSpawn;
public final Setting<Boolean> showStrongholds;
public final Setting<Boolean> showPlayers;
public final Setting<Boolean> showVillages;
public final Setting<Boolean> showTemples;
public final Setting<Boolean> showMineshafts;
public final Setting<Boolean> showOceanMonuments;
public final Setting<Boolean> showWoodlandMansions;
public final Setting<Boolean> showOceanFeatures;
public final Setting<Boolean> showNetherFortresses;
public final Setting<Boolean> showEndCities;
public final Setting<Boolean> smoothScrolling;
public final Setting<Boolean> fragmentFading;
public final Setting<Boolean> maxZoom;
public final Setting<Boolean> showFPS;
public final Setting<Boolean> showScale;
public final Setting<Boolean> showDebug;
public final Setting<Boolean> useHybridScaling;
public final Setting<Integer> threads;
public final Setting<AmidstLookAndFeel> lookAndFeel;
public final Setting<String> lastProfile;
public final Setting<String> worldType;
public final Setting<String> lastBiomeExportPath;
public final Setting<String> lastScreenshotPath;
/**
* This is not persisted.
*/
public final BiomeProfileSelection biomeProfileSelection;
@CalledOnlyBy(AmidstThread.EDT)
public AmidstSettings(Preferences preferences) {
// @formatter:off
dimension = Setting.createDimension(preferences, "dimension", Dimension.OVERWORLD);
showGrid = Setting.createBoolean( preferences, "grid", false);
showSlimeChunks = Setting.createBoolean( preferences, "slimeChunks", false);
showSpawn = Setting.createBoolean( preferences, "spawnIcon", true);
showStrongholds = Setting.createBoolean( preferences, "strongholdIcons", true);
showPlayers = Setting.createBoolean( preferences, "playerIcons", true);
showVillages = Setting.createBoolean( preferences, "villageIcons", true);
showTemples = Setting.createBoolean( preferences, "templeIcons", true);
showMineshafts = Setting.createBoolean( preferences, "mineshaftIcons", false);
showOceanMonuments = Setting.createBoolean( preferences, "oceanMonumentIcons", true);
showWoodlandMansions = Setting.createBoolean( preferences, "woodlandMansionIcons", true);
showOceanFeatures = Setting.createBoolean( preferences, "oceanFeaturesIcons", true);
showNetherFortresses = Setting.createBoolean( preferences, "netherFortressIcons", false);
showEndCities = Setting.createBoolean( preferences, "endCityIcons", false);
smoothScrolling = Setting.createBoolean( preferences, "mapFlicking", true);
fragmentFading = Setting.createBoolean( preferences, "mapFading", true);
maxZoom = Setting.createBoolean( preferences, "maxZoom", true);
showFPS = Setting.createBoolean( preferences, "showFPS", true);
showScale = Setting.createBoolean( preferences, "showScale", true);
showDebug = Setting.createBoolean( preferences, "showDebug", false);
useHybridScaling = Setting.createBoolean( preferences, "useHybridScaling", true);
threads = Setting.createInteger( preferences, "threads", (Runtime.getRuntime().availableProcessors() / 2) + 1);
lookAndFeel = Setting.createEnum( preferences, "lookAndFeel", AmidstLookAndFeel.DEFAULT);
lastProfile = Setting.createString( preferences, "profile", "");
worldType = Setting.createString( preferences, "worldType", WorldType.PROMPT_EACH_TIME);
lastBiomeExportPath = Setting.createString( preferences, "lastBiomeExportPath", "");
lastScreenshotPath = Setting.createString( preferences, "lastScreenshotPath", "");
biomeProfileSelection = new BiomeProfileSelection(BiomeProfile.getDefaultProfile());
// @formatter:on
}
}
|
amidst
|
src\main\java\amidst\AmidstVersion.java
|
package amidst;
import amidst.documentation.Immutable;
import java.util.Properties;
@Immutable
public class AmidstVersion {
public static AmidstVersion from(Properties properties) {
return new AmidstVersion(
Integer.parseInt(properties.getProperty("amidst.version.major")),
Integer.parseInt(properties.getProperty("amidst.version.minor")),
Integer.parseInt(properties.getProperty("amidst.version.patch")),
properties.getProperty("amidst.version.preReleaseSuffix"));
}
private final int major;
private final int minor;
private final int patch;
private final String preReleaseSuffix;
public AmidstVersion(int major, int minor, int patch) {
this(major, minor, patch, null);
}
public AmidstVersion(int major, int minor, int patch, String preReleaseSuffix) {
this.major = major;
this.minor = minor;
this.patch = patch;
this.preReleaseSuffix = preReleaseSuffix;
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int getPatch() {
return patch;
}
public String getPreReleaseSuffix() {
return preReleaseSuffix;
}
public boolean isNewerMajorVersionThan(AmidstVersion old) {
return major > old.major;
}
public boolean isNewerMinorVersionThan(AmidstVersion old) {
return major == old.major && minor > old.minor;
}
public boolean isNewerPatchVersionThan(AmidstVersion old) {
return major == old.major && minor == old.minor && patch > old.patch;
}
public boolean isSameVersionButOldPreReleaseAndNewStable(AmidstVersion old) {
return isSameVersion(old) && old.isPreRelease() && !isPreRelease();
}
public boolean isSameVersion(AmidstVersion old) {
return major == old.major && minor == old.minor && patch == old.patch;
}
public boolean isPreRelease() {
return preReleaseSuffix != null && !preReleaseSuffix.isEmpty();
}
public String createLongVersionString() {
return "Amidst " + createVersionString();
}
public String createVersionString() {
String version = "v" + major + "." + minor;
if (patch != 0) {
version += "." + patch;
}
if (isPreRelease()) {
version += "-" + preReleaseSuffix;
}
return version;
}
}
|
amidst
|
src\main\java\amidst\Application.java
|
package amidst;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.FragmentManager;
import amidst.fragment.layer.LayerBuilder;
import amidst.gui.license.LicenseWindow;
import amidst.gui.main.MainWindow;
import amidst.gui.main.MainWindowDialogs;
import amidst.gui.main.UpdatePrompt;
import amidst.gui.main.viewer.BiomeSelection;
import amidst.gui.main.viewer.Zoom;
import amidst.gui.profileselect.ProfileSelectWindow;
import amidst.mojangapi.LauncherProfileRunner;
import amidst.mojangapi.RunningLauncherProfile;
import amidst.mojangapi.file.*;
import amidst.mojangapi.minecraftinterface.MinecraftInterfaceCreationException;
import amidst.mojangapi.world.SeedHistoryLogger;
import amidst.mojangapi.world.WorldBuilder;
import amidst.parsing.FormatException;
import amidst.settings.biomeprofile.BiomeProfileDirectory;
import amidst.threading.ThreadMaster;
import javax.swing.SwingUtilities;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
/**
* The actual Amidst application, holding its state.
*/
@NotThreadSafe
public class Application {
private final LauncherProfileRunner launcherProfileRunner;
/**
* The main window object.
*/
private volatile MainWindow mainWindow;
private volatile ProfileSelectWindow profileSelectWindow;
private volatile Optional<LauncherProfile> selectedLauncherProfile;
private final ThreadMaster threadMaster = new ThreadMaster();
private final LayerBuilder layerBuilder = new LayerBuilder();
private final BiomeSelection biomeSelection = new BiomeSelection();
private final AmidstSettings settings;
private final MinecraftInstallation minecraftInstallation;
private final BiomeProfileDirectory biomeProfileDirectory;
private final VersionListProvider versionListProvider;
private final Zoom zoom;
private final FragmentManager fragmentManager;
/**
* The versions of minecraft available to amidst.
*/
private final List<Version> versions;
/**
* Creates a new Amidst application instance.
*
* @param parameters the command line parameters passed into the executable
* @param settings user settings
* @throws FormatException if the JSON parser fails
* @throws IOException if the JSON parser fails
*/
@CalledOnlyBy(AmidstThread.EDT)
public Application(CommandLineParameters parameters, AmidstSettings settings) throws FormatException, IOException {
this.settings = settings;
minecraftInstallation = MinecraftInstallation.newLocalMinecraftInstallation(parameters.dotMinecraftDirectory);
selectedLauncherProfile = parameters.getInitialLauncherProfile(minecraftInstallation);
WorldBuilder worldBuilder = new WorldBuilder(new PlayerInformationCache(), SeedHistoryLogger.from(parameters.seedHistoryFile));
launcherProfileRunner = new LauncherProfileRunner(worldBuilder, parameters.getInitialWorldOptions());
biomeProfileDirectory = BiomeProfileDirectory.create(parameters.biomeProfilesDirectory);
versionListProvider = new VersionListProvider(threadMaster.getWorkerExecutor());
versions = Version.newLocalVersionList();
zoom = new Zoom(settings.maxZoom);
fragmentManager = new FragmentManager(layerBuilder.getConstructors(), layerBuilder.getNumberOfLayers(), settings.threads);
}
/**
* Opens the profile select window, or a pre-selected launcher profile,
* if it is set.
* <p>
* This also checks for updates in the background.
*
* @throws MinecraftInterfaceCreationException
*/
@CalledOnlyBy(AmidstThread.EDT)
public void run() throws MinecraftInterfaceCreationException {
UpdatePrompt.from(Amidst.VERSION, threadMaster.getWorkerExecutor(), null, true).check();
if (selectedLauncherProfile.isPresent()) {
displayMainWindow(launcherProfileRunner.run(selectedLauncherProfile.get()));
} else {
displayProfileSelectWindow();
}
}
/**
* Checks for updates in the foreground.
*
* @param dialogs
*/
@CalledOnlyBy(AmidstThread.EDT)
public void checkForUpdates(MainWindowDialogs dialogs) {
UpdatePrompt.from(Amidst.VERSION, threadMaster.getWorkerExecutor(), dialogs, false).check();
}
/**
* Shows the {@link MainWindow} to the user.
* <p>
* This disposes of the profile select window if it is visible,
* and any previous main window.
*
* @param runningLauncherProfile
* @return the window object that was shown
*/
@CalledOnlyBy(AmidstThread.EDT)
public MainWindow displayMainWindow(RunningLauncherProfile runningLauncherProfile) {
selectedLauncherProfile = Optional.of(runningLauncherProfile.getLauncherProfile());
MainWindow m = new MainWindow(
this,
settings,
minecraftInstallation,
runningLauncherProfile,
biomeProfileDirectory,
zoom,
layerBuilder,
fragmentManager,
biomeSelection,
threadMaster);
if (mainWindow != null) {
mainWindow.dispose();
}
mainWindow = m;
if (profileSelectWindow != null) {
profileSelectWindow.dispose();
profileSelectWindow = null;
}
return mainWindow;
}
/**
* Creates and shows a profile selection window.
* <p>
* This disposes the main window if it is visible, and any previous
* profile select window.
*/
@CalledOnlyBy(AmidstThread.EDT)
public void displayProfileSelectWindow() {
ProfileSelectWindow window = new ProfileSelectWindow(
this,
threadMaster.getWorkerExecutor(),
versions,
versionListProvider,
minecraftInstallation,
launcherProfileRunner,
settings);
if (profileSelectWindow != null) {
profileSelectWindow.dispose();
}
profileSelectWindow = window;
if (mainWindow != null) {
mainWindow.dispose();
mainWindow = null;
}
}
/**
* Creates and shows a new {@link LicenseWindow}.
*/
@CalledOnlyBy(AmidstThread.EDT)
public void displayLicenseWindow() {
new LicenseWindow();
}
/**
* Disposes of the application windows and exits the application.
*/
@CalledOnlyBy(AmidstThread.EDT)
public void exitGracefully() {
dispose();
System.exit(0);
}
/**
* Disposes of the profile select window and the main window,
* setting them to {@code null}.
*/
@CalledOnlyBy(AmidstThread.EDT)
public void dispose() {
if (profileSelectWindow != null) {
profileSelectWindow.dispose();
profileSelectWindow = null;
}
if (mainWindow != null) {
mainWindow.dispose();
mainWindow = null;
}
}
/**
* Disposes of the profile select and main windows, and runs {@link #run()}.
*/
@CalledOnlyBy(AmidstThread.EDT)
public void restart() {
dispose();
SwingUtilities.invokeLater(() -> {
try {
run();
} catch (MinecraftInterfaceCreationException e) {
throw new RuntimeException("Unexpected exception while restarting Amidst", e);
}
});
}
}
|
amidst
|
src\main\java\amidst\CommandLineParameters.java
|
package amidst;
import java.nio.file.Path;
import java.util.Optional;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.OptionDef;
import org.kohsuke.args4j.spi.OptionHandler;
import org.kohsuke.args4j.spi.Parameters;
import org.kohsuke.args4j.spi.Setter;
import amidst.documentation.ThreadSafe;
import amidst.mojangapi.file.LauncherProfile;
import amidst.mojangapi.file.MinecraftInstallation;
import amidst.mojangapi.world.WorldOptions;
import amidst.mojangapi.world.WorldSeed;
import amidst.mojangapi.world.WorldType;
/**
* An instance of this class will be created to hold the command line
* parameters. Afterwards, the assigned values should not be modified.
*/
@ThreadSafe
public class CommandLineParameters {
// @formatter:off
@Option(
name = "-mcpath",
usage = "location of the '.minecraft' directory.",
metaVar = "<directory>"
)
public volatile Path dotMinecraftDirectory;
@Option(
name = "-mcjar",
usage = "location of the minecraft jar file",
metaVar = "<file>",
depends = { "-mcjson" },
forbids = { "-profile" }
)
public volatile Path minecraftJarFile;
@Option(
name = "-mcjson",
usage = "location of the minecraft json file",
metaVar = "<file>",
depends = { "-mcjar" },
forbids = { "-profile" }
)
public volatile Path minecraftJsonFile;
@Option(
name = "-profile",
usage = "name of profile to select",
metaVar = "<name>",
forbids = { "-mcjar", "-mcjson" }
)
public volatile String profileName;
@Option(
name = "-biome-profiles",
usage = "location of the biome profile directory",
metaVar = "<directory>"
)
public volatile Path biomeProfilesDirectory;
@Option(
name = "-history",
usage = "location of the seed history file",
metaVar = "<file>"
)
public volatile Path seedHistoryFile;
@Option(
name = "-log",
usage = "location of the log file",
metaVar = "<file>"
)
public volatile Path logFile;
@Option(
name = "-seed",
handler = SeedHandler.class,
usage = "initial seed to use",
metaVar = "<string>"
)
public volatile WorldSeed initialSeed;
@Option(
name = "-world-type",
handler = WorldTypeHandler.class,
usage = "world type for the initial seed",
metaVar = "<string>",
depends = { "-seed" }
)
public volatile WorldType initialWorldType;
@Option(
name = "-help",
usage = "print usage information"
)
public volatile boolean printHelp;
@Option(
name = "-version",
usage = "print version"
)
public volatile boolean printVersion;
// @formatter:on
public Optional<WorldOptions> getInitialWorldOptions() {
if (initialSeed == null) {
return Optional.empty();
}
return Optional.of(new WorldOptions(initialSeed, initialWorldType != null ? initialWorldType : WorldType.DEFAULT));
}
public Optional<LauncherProfile> getInitialLauncherProfile(MinecraftInstallation minecraftInstallation) {
if (profileName != null) {
return minecraftInstallation.tryGetLauncherProfileFromName(profileName);
}
if (minecraftJarFile != null) {
return minecraftInstallation.tryReadLauncherProfile(minecraftJarFile, minecraftJsonFile);
}
return Optional.empty();
}
public static class SeedHandler extends OptionHandler<WorldSeed> {
public SeedHandler(CmdLineParser cmdLineParser, OptionDef optionDef, Setter<WorldSeed> setter) {
super(cmdLineParser, optionDef, setter);
}
@Override
public int parseArguments(Parameters params) throws CmdLineException {
WorldSeed seed = WorldSeed.fromUserInput(params.getParameter(0));
setter.addValue(seed);
return 1;
}
@Override
public String getDefaultMetaVariable() {
return "STRING";
}
}
public static class WorldTypeHandler extends OptionHandler<WorldType> {
public WorldTypeHandler(CmdLineParser cmdLineParser, OptionDef optionDef, Setter<WorldType> setter) {
super(cmdLineParser, optionDef, setter);
}
@Override
public int parseArguments(Parameters params) throws CmdLineException {
String param = params.getParameter(0);
WorldType type = WorldType.findInstance(param);
if(type == null) {
throw new CmdLineException(owner, "Invalid WorldType: '" + param + "'", null);
}
setter.addValue(type);
return 1;
}
@Override
public String getDefaultMetaVariable() {
return "STRING";
}
}
}
|
amidst
|
src\main\java\amidst\FeatureToggles.java
|
package amidst;
import amidst.documentation.Immutable;
@Immutable
public enum FeatureToggles {
;
public static final boolean SEED_SEARCH = false;
}
|
amidst
|
src\main\java\amidst\ResourceLoader.java
|
package amidst;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import javax.imageio.ImageIO;
import amidst.documentation.Immutable;
import amidst.documentation.NotNull;
@Immutable
public enum ResourceLoader {
;
@NotNull
public static URL getResourceURL(String name) throws IllegalArgumentException {
URL result = ResourceLoader.class.getResource(name);
if (result == null) {
// This is always a developer error, because a resource was not
// included in the jar file.
throw new IllegalArgumentException("unable to load resource: '" + name + "'");
}
return result;
}
public static BufferedImage getImage(String name) {
try {
return ImageIO.read(getResourceURL(name));
} catch (IOException e) {
// This is always a developer error, because a resource was not
// included in the jar file.
throw new IllegalArgumentException("unable to load resource: '" + name + "'", e);
}
}
public static Properties getProperties(String name) {
try (InputStream stream = getResourceAsStream(name)) {
Properties properties = new Properties();
properties.load(stream);
return properties;
} catch (IOException e) {
// This is always a developer error, because a resource was not
// included in the jar file.
throw new IllegalArgumentException("unable to load resource: '" + name + "'", e);
}
}
public static String getResourceAsString(String name) throws IOException {
try (InputStreamReader reader = new InputStreamReader(getResourceAsStream(name), StandardCharsets.UTF_8)) {
char[] buffer = new char[1024];
int length;
StringBuilder result = new StringBuilder();
while ((length = reader.read(buffer)) != -1) {
result.append(buffer, 0, length);
}
return result.toString();
}
}
public static InputStream getResourceAsStream(String filename) {
return new BufferedInputStream(ResourceLoader.class.getResourceAsStream(filename));
}
}
|
amidst
|
src\main\java\amidst\clazz\Classes.java
|
package amidst.clazz;
import java.io.FileNotFoundException;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import amidst.clazz.real.JarFileParsingException;
import amidst.clazz.real.RealClass;
import amidst.clazz.real.RealClasses;
import amidst.clazz.symbolic.SymbolicClass;
import amidst.clazz.symbolic.SymbolicClassGraphCreationException;
import amidst.clazz.symbolic.SymbolicClasses;
import amidst.clazz.symbolic.declaration.SymbolicClassDeclaration;
import amidst.clazz.translator.ClassTranslator;
import amidst.documentation.Immutable;
import amidst.logging.AmidstLogger;
@Immutable
public enum Classes {
;
public static Map<String, SymbolicClass> createSymbolicClassMap(
Path path,
URLClassLoader classLoader,
ClassTranslator translator)
throws FileNotFoundException,
JarFileParsingException,
SymbolicClassGraphCreationException,
ClassNotFoundException {
AmidstLogger.info("Reading {}", path.getFileName());
List<RealClass> realClasses = RealClasses.fromJarFile(path);
AmidstLogger.info("Jar load complete.");
AmidstLogger.info("Searching for classes...");
Map<SymbolicClassDeclaration, String> realClassNamesBySymbolicClassDeclaration = translator
.translate(realClasses);
AmidstLogger.info("Class search complete.");
AmidstLogger.info("Loading classes...");
Map<String, SymbolicClass> result = SymbolicClasses.from(realClassNamesBySymbolicClassDeclaration, classLoader);
AmidstLogger.info("Classes loaded.");
return result;
}
public static Map<SymbolicClassDeclaration, Integer> countMatches(Path jarFile, ClassTranslator translator)
throws FileNotFoundException,
JarFileParsingException {
AmidstLogger.info("Checking {}", jarFile.getFileName());
List<RealClass> realClasses = RealClasses.fromJarFile(jarFile);
Map<SymbolicClassDeclaration, List<RealClass>> map = translator.translateToAllMatching(realClasses);
Map<SymbolicClassDeclaration, Integer> result = new HashMap<>();
for (Entry<SymbolicClassDeclaration, List<RealClass>> entry : map.entrySet()) {
result.put(entry.getKey(), entry.getValue().size());
if (entry.getValue().isEmpty()) {
AmidstLogger.warn("{} has no matching class", entry.getKey().getSymbolicClassName());
} else if (entry.getValue().size() > 1) {
StringBuilder builder = new StringBuilder();
for (RealClass realClass : entry.getValue()) {
builder.append(", ").append(realClass.getRealClassName());
}
AmidstLogger.warn("{} has multiple matching classes: {}",
entry.getKey().getSymbolicClassName(), builder.toString().substring(2));
}
}
return result;
}
}
|
amidst
|
src\main\java\amidst\documentation\AmidstThread.java
|
package amidst.documentation;
import amidst.logging.FileLogger;
/**
* Each entry of this enum describes one type of thread that will ever exist in
* the project. It is only used for documentation purposes.
*/
public enum AmidstThread {
/**
* The thread that calls the main method at application startup. This will
* do some initialization. Afterwards it calls the EDT to create and start
* the application. So this thread dies pretty quickly.
*/
STARTUP,
/**
* This thread constantly causes the EDT to repaint the map, however it does
* not execute any other code by itself.
*/
REPAINTER,
/**
* This thread is the Event Dispatch Thread used by Swing and AWT. All GUI
* events are executed in this thread. Also, the drawing of the GUI is
* executed by this thread. This thread should not be used to execute long
* running tasks.
*/
EDT,
/**
* This thread constantly loads, reloads and recycles fragments, because it
* takes to long to do this in the EDT. Since this thread and the EDT
* constantly read from and write to the fragments and fragment graph, extra
* care must be used in this part of the application.
*/
FRAGMENT_LOADER,
/**
* This is actually a pool of thread that are created and removed as needed.
* They are used to execute tasks that take to long for the EDT and belong
* to no other thread, e.g. the loading of skins. After a worker has
* finished the background task, it should pass its result to the EDT to
* display the result to the user.
*/
WORKER,
/**
* The file logger also uses a single threaded scheduled executor service to
* actually write the logging messages to the file. However, this thread
* should never leave the class {@link FileLogger}.
*/
FILE_LOGGER;
}
|
amidst
|
src\main\java\amidst\documentation\CalledByAny.java
|
package amidst.documentation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is similar to the annotation {@link CalledBy}. However, it
* specifies that not assumption was made that only a specific thread calls this
* constructor or method.
*/
@Retention(RetentionPolicy.SOURCE)
@Documented
@Target({ ElementType.CONSTRUCTOR, ElementType.METHOD })
public @interface CalledByAny {
}
|
amidst
|
src\main\java\amidst\documentation\CalledOnlyBy.java
|
package amidst.documentation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation indicates that the constructor or method it is attached to
* can ONLY be called by the given thread.
*/
@Retention(RetentionPolicy.SOURCE)
@Documented
@Target({ ElementType.CONSTRUCTOR, ElementType.METHOD })
public @interface CalledOnlyBy {
AmidstThread value();
}
|
amidst
|
src\main\java\amidst\documentation\GsonConstructor.java
|
package amidst.documentation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is added to no argument-constructors that are used by gson to
* deserialize object instances.
*/
@Retention(RetentionPolicy.SOURCE)
@Documented
@Target(ElementType.CONSTRUCTOR)
public @interface GsonConstructor {
}
|
amidst
|
src\main\java\amidst\documentation\Immutable.java
|
package amidst.documentation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation indicates that instance of this type cannot be modified after
* instantiation. This also implies that the type is thread safe.
*/
@Retention(RetentionPolicy.SOURCE)
@Documented
@Target(ElementType.TYPE)
public @interface Immutable {
}
|
amidst
|
src\main\java\amidst\documentation\NotNull.java
|
package amidst.documentation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is added to methods that will never return null.
*/
@Retention(RetentionPolicy.SOURCE)
@Documented
@Target({ ElementType.METHOD, ElementType.PARAMETER })
public @interface NotNull {
}
|
amidst
|
src\main\java\amidst\documentation\NotThreadSafe.java
|
package amidst.documentation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation indicates that the type it is attached was not designed with
* thread safety in mind. Thus, it should be used from only a single thread or
* if it is used in a multi-threaded environment, the using class has to ensure
* thread safety.
*/
@Retention(RetentionPolicy.SOURCE)
@Documented
@Target(ElementType.TYPE)
public @interface NotThreadSafe {
}
|
amidst
|
src\main\java\amidst\documentation\ThreadSafe.java
|
package amidst.documentation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation indicates that the type it is attached to is thread-safe.
* However, objects of this type might have a modifiable state. For unmodifiable
* types, use the {@link Immutable} annotation. You can read this annotation as
* if {@link CalledByAny} was used on all constructors and methods of this type.
*/
@Retention(RetentionPolicy.SOURCE)
@Documented
@Target(ElementType.TYPE)
public @interface ThreadSafe {
}
|
amidst
|
src\main\java\amidst\fragment\ClosestWorldIconFinder.java
|
package amidst.fragment;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.layer.LayerDeclaration;
import amidst.mojangapi.world.coordinates.CoordinatesInWorld;
import amidst.mojangapi.world.icon.WorldIcon;
@NotThreadSafe
public class ClosestWorldIconFinder {
private final FragmentGraph graph;
private final Iterable<LayerDeclaration> declarations;
private final CoordinatesInWorld positionInWorld;
private WorldIcon closestIcon;
private double closestDistanceSq;
@CalledOnlyBy(AmidstThread.EDT)
public ClosestWorldIconFinder(
FragmentGraph graph,
Iterable<LayerDeclaration> declarations,
CoordinatesInWorld positionInWorld,
double maxDistanceInWorld) {
this.graph = graph;
this.declarations = declarations;
this.positionInWorld = positionInWorld;
this.closestIcon = null;
this.closestDistanceSq = maxDistanceInWorld * maxDistanceInWorld;
find();
}
@CalledOnlyBy(AmidstThread.EDT)
private void find() {
for (FragmentGraphItem fragmentGraphItem : graph) {
Fragment fragment = fragmentGraphItem.getFragment();
for (LayerDeclaration declaration : declarations) {
if (declaration.isVisible()) {
int layerId = declaration.getLayerId();
for (WorldIcon icon : fragment.getWorldIcons(layerId)) {
updateClosest(icon);
}
}
}
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void updateClosest(WorldIcon icon) {
double distanceSq = icon.getCoordinates().getDistanceSq(positionInWorld);
if (closestDistanceSq > distanceSq) {
closestDistanceSq = distanceSq;
closestIcon = icon;
}
}
@CalledOnlyBy(AmidstThread.EDT)
public boolean hasResult() {
return closestIcon != null;
}
@CalledOnlyBy(AmidstThread.EDT)
public WorldIcon getWorldIcon() {
return closestIcon;
}
@CalledOnlyBy(AmidstThread.EDT)
public double getDistance() {
return Math.sqrt(closestDistanceSq);
}
}
|
amidst
|
src\main\java\amidst\fragment\Fragment.java
|
package amidst.fragment;
import java.awt.image.BufferedImage;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.function.UnaryOperator;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.ThreadSafe;
import amidst.gui.main.viewer.Drawer;
import amidst.mojangapi.world.coordinates.CoordinatesInWorld;
import amidst.mojangapi.world.coordinates.Resolution;
import amidst.mojangapi.world.icon.WorldIcon;
import amidst.mojangapi.world.oracle.BiomeDataOracle;
import amidst.mojangapi.world.oracle.EndIsland;
/**
* This class contains nearly no logic but only simple and atomic getters and
* setters. </br>
* </br>
* The life-cycle of a Fragment is quite complex to prevent the garbage
* collection from running too often. When a fragment is no longer needed it
* will be kept available in a queue, so it can be reused later on. The
* life-cycle consists of the three flags: isInitialized, isLoading, and
* isLoaded. isInitialized can be set to true from any thread, however setting
* isInitialized to false as well as any modification to isLoading and isLoaded
* will always be called from the fragment loading thread, to ensure a
* consistent state. Also, isInitialized will only be set to true again after it
* was set to false. It is not possible that isLoading or isLoaded is true while
* isInitialized is false. It is also not possible for isLoaded to be true while
* isLoading is true. </br>
* </br>
* It is possible that a thread that uses the data in the fragment continues to
* use them after isLoaded is set to false. However, all write operations are
* called from either the fragment loading thread, the threads from
* {@link FragmentManager#fragWorkers}, or the EDT during theconstruction of
* the fragment. While the fragment is constructed it will only be accessible
* by one thread. An exception to that rule is the instance variable alpha.
* It is altered from the drawing thread, however this should not cause any
* issues. </br>
* </br>
* Immediately after a new instance of this class is created, it is passed to
* all FragmentConstructors. At that point in time, no other thread can access
* the fragment, so the whole construction process is single-threaded. After the
* fragment is constructed it will be available to use in the fragment graph. As
* soon as it is requested, its isInitialized variable will be set to true by
* the requesting thread. Also, it is enqueued to the loading queue. Note, that
* the fragment is still not loaded, but used in the fragment graph and thus
* used by the {@link Drawer}. Sometime after the fragment was requested, it
* will go through the loading process, because it was enqueued to the loading
* queue. </br>
* </br>
* During the loading process, the fragment loader thread will first check to
* make sure that there are threads open in the fragment worker thread pool. If
* it finds any threads that aren't executing anything, it will be passed to a
* fragment worker to be loaded. When the fragment worker starts, it checks to
* see if the fragment is already loading. If it is not, the isLoading variable
* is set to true. This is to make sure that only one thread is loading the
* fragment at a time. </br>
* </br>
* When this is done, the isLoaded variable will be set to true. This allows the
* drawer to actually draw the fragment. The complete drawing process is
* executed in the event dispatch thread. When the fragment is no longer visible
* on the screen it will be removed from the fragment graph. However, since it
* holds a data-structure that is quite heavy to allocate and garbage-collect,
* the fragment will be recycled so it can be reused later. This recycling is
* done by enqueuing the fragment to the recycle queue. The recycle queue is
* processed by the fragment loading thread with a very high priority. Even
* though the fragment loading thread only calls the method
* {@link Fragment#recycle()} and enqueues the fragment to the available queue,
* it is important that this is done by the fragment loading queue. This is,
* because if any other thread sets the isLoaded variable to false, it might be
* set to true by the fragment loading thread afterwards, because the fragment
* was not yet loaded. This problem is solved by modifying the isLoaded variable
* only in the fragment loading thread. This issue only arises, since the
* fragment is already used in the fragment graph, before it is loaded. As soon
* as it is used in the fragment graph it, can be recycled. This often leads to
* a situation where a not yet loaded fragment gets recycled. The isInitialized
* variable is altered by the thread that requests the new fragment, which is
* different from the fragment loading thread. This is not an issue, since all
* fragments in the available queue have both variables isInitialized and
* isLoaded set to false. They are also not used in the fragment graph or
* enqueued in the recycle queue. Therefore, there cannot be a race condition
* because the isInitialized variable will only be set to false when it is
* recycled.
*/
@ThreadSafe
public class Fragment {
public static final int SIZE = Resolution.FRAGMENT.getStep();
private final AtomicReference<State> state;
private volatile CoordinatesInWorld corner;
private volatile float alpha;
private volatile short[][] biomeData;
private volatile List<EndIsland> endIslands;
private final AtomicReferenceArray<BufferedImage> images;
private final AtomicReferenceArray<List<WorldIcon>> worldIcons;
public Fragment(int numberOfLayers) {
this.state = new AtomicReference<State>(State.UNINITIALIZED);
this.images = new AtomicReferenceArray<>(numberOfLayers);
this.worldIcons = new AtomicReferenceArray<>(numberOfLayers);
}
public void setAlpha(float alpha) {
this.alpha = alpha;
}
public float getAlpha() {
return alpha;
}
public void initBiomeData(int width, int height) {
biomeData = new short[width][height];
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
public void populateBiomeData(BiomeDataOracle biomeDataOracle) {
int width = biomeData.length;
int height = width == 0 ? 0 : biomeData[0].length;
biomeDataOracle.getBiomeData(corner, width, height, true, data -> {
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
biomeData[i][j] = (short) data[j * width + i];
}
}
});
}
public short getBiomeDataAt(int x, int y) {
return biomeData[x][y];
}
public void setEndIslands(List<EndIsland> endIslands) {
this.endIslands = endIslands;
}
public List<EndIsland> getEndIslands() {
return endIslands;
}
public BufferedImage getAndSetImage(int layerId, BufferedImage image) {
return images.getAndSet(layerId, image);
}
public void putImage(int layerId, BufferedImage image) {
images.set(layerId, image);
}
public BufferedImage getImage(int layerId) {
return images.get(layerId);
}
public void putWorldIcons(int layerId, List<WorldIcon> icons) {
worldIcons.set(layerId, icons);
}
public List<WorldIcon> getWorldIcons(int layerId) {
if (state.get().equals(State.LOADED)) {
List<WorldIcon> result = worldIcons.get(layerId);
if (result != null) {
return result;
}
}
return Collections.emptyList();
}
public void setState(State state) {
this.state.set(state);
}
public State getState() {
return this.state.get();
}
public State getAndSetState(State state) {
return this.state.getAndSet(state);
}
public State updateAndGetState(UnaryOperator<State> updateFunction) {
return this.state.updateAndGet(updateFunction);
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
// can only be recycled if it's not loading
public boolean tryRecycle() {
return this.state.updateAndGet(s -> s.equals(State.LOADING) ? State.LOADING : State.UNINITIALIZED).equals(State.UNINITIALIZED);
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
// can only be recycled if it's not loading
public boolean tryRecycleNotLoaded() {
return this.state.updateAndGet(s -> s.equals(State.LOADING) || s.equals(State.LOADED) ? s : State.UNINITIALIZED).equals(State.UNINITIALIZED);
}
public void setCorner(CoordinatesInWorld corner) {
this.corner = corner;
}
public CoordinatesInWorld getCorner() {
return corner;
}
public static enum State {
UNINITIALIZED,
INITIALIZED,
LOADING,
LOADED;
}
}
|
amidst
|
src\main\java\amidst\fragment\FragmentCache.java
|
package amidst.fragment;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.ThreadSafe;
import amidst.fragment.constructor.FragmentConstructor;
import amidst.logging.AmidstLogger;
@ThreadSafe
public class FragmentCache {
private static final int NEW_FRAGMENTS_PER_REQUEST = 1024;
private final List<Fragment> cache = new LinkedList<>();
private final ConcurrentLinkedQueue<Fragment> availableQueue;
private final ConcurrentLinkedQueue<Fragment> loadingQueue;
private final Iterable<FragmentConstructor> constructors;
private final int numberOfLayers;
@CalledOnlyBy(AmidstThread.EDT)
public FragmentCache(
ConcurrentLinkedQueue<Fragment> availableQueue,
ConcurrentLinkedQueue<Fragment> loadingQueue,
Iterable<FragmentConstructor> constructors,
int numberOfLayers) {
this.availableQueue = availableQueue;
this.loadingQueue = loadingQueue;
this.constructors = constructors;
this.numberOfLayers = numberOfLayers;
}
@CalledOnlyBy(AmidstThread.EDT)
public synchronized void increaseSize() {
AmidstLogger.info(
"increasing fragment cache size from " + cache.size() + " to "
+ (cache.size() + NEW_FRAGMENTS_PER_REQUEST));
requestNewFragments();
AmidstLogger.info("fragment cache size increased to " + cache.size());
}
@CalledOnlyBy(AmidstThread.EDT)
private void requestNewFragments() {
for (int i = 0; i < NEW_FRAGMENTS_PER_REQUEST; i++) {
Fragment fragment = new Fragment(numberOfLayers);
construct(fragment);
cache.add(fragment);
availableQueue.offer(fragment);
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void construct(Fragment fragment) {
for (FragmentConstructor constructor : constructors) {
constructor.construct(fragment);
}
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
public synchronized void reloadAll() {
loadingQueue.clear();
for (Fragment fragment : cache) {
loadingQueue.offer(fragment);
}
}
@CalledOnlyBy(AmidstThread.EDT)
public synchronized void clear() {
AmidstLogger.info("fragment cache cleared");
cache.clear();
}
@CalledOnlyBy(AmidstThread.EDT)
public int size() {
return cache.size();
}
}
|
amidst
|
src\main\java\amidst\fragment\FragmentGraph.java
|
package amidst.fragment;
import java.util.Iterator;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.layer.LayerDeclaration;
import amidst.mojangapi.world.coordinates.CoordinatesInWorld;
import amidst.mojangapi.world.icon.WorldIcon;
import amidst.util.Lazy;
@NotThreadSafe
public class FragmentGraph implements Iterable<FragmentGraphItem> {
private final Iterable<LayerDeclaration> declarations;
private final FragmentManager fragmentManager;
private int fragmentsPerRow;
private int fragmentsPerColumn;
private final Lazy<FragmentGraphItem> topLeftFragment = Lazy.from(this::createOrigin);
@CalledOnlyBy(AmidstThread.EDT)
public FragmentGraph(Iterable<LayerDeclaration> declarations, FragmentManager fragmentManager) {
this.declarations = declarations;
this.fragmentManager = fragmentManager;
}
@CalledOnlyBy(AmidstThread.EDT)
public void init(CoordinatesInWorld coordinates) {
topLeftFragment.setToValue(create(coordinates));
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem createOrigin() {
return create(CoordinatesInWorld.origin());
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem create(CoordinatesInWorld coordinates) {
recycleAll();
fragmentsPerRow = 1;
fragmentsPerColumn = 1;
return new FragmentGraphItem(fragmentManager.requestFragment(coordinates.toFragmentCorner()));
}
@CalledOnlyBy(AmidstThread.EDT)
public void adjust(int newLeft, int newAbove, int newRight, int newBelow) {
fragmentsPerRow = fragmentsPerRow + newLeft + newRight;
fragmentsPerColumn = fragmentsPerColumn + newAbove + newBelow;
topLeftFragment
.replaceWithValue(f -> f.adjustRowsAndColumns(newAbove, newBelow, newLeft, newRight, fragmentManager));
}
@CalledOnlyBy(AmidstThread.EDT)
public void dispose() {
recycleAll();
}
@CalledOnlyBy(AmidstThread.EDT)
private void recycleAll() {
topLeftFragment.ifInitialized(f -> f.recycleAll(fragmentManager));
}
@CalledOnlyBy(AmidstThread.EDT)
public int getFragmentsPerRow() {
return fragmentsPerRow;
}
@CalledOnlyBy(AmidstThread.EDT)
public int getFragmentsPerColumn() {
return fragmentsPerColumn;
}
@CalledOnlyBy(AmidstThread.EDT)
public CoordinatesInWorld getCorner() {
return topLeftFragment.getOrCreateValue().getFragment().getCorner();
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
public Iterator<FragmentGraphItem> iterator() {
return topLeftFragment.getOrCreateValue().iterator();
}
@CalledOnlyBy(AmidstThread.EDT)
public WorldIcon getClosestWorldIcon(CoordinatesInWorld coordinates, double maxDistanceInWorld) {
return new ClosestWorldIconFinder(this, declarations, coordinates, maxDistanceInWorld).getWorldIcon();
}
@CalledOnlyBy(AmidstThread.EDT)
public Fragment getFragmentAt(CoordinatesInWorld coordinates) {
CoordinatesInWorld corner = coordinates.toFragmentCorner();
for (FragmentGraphItem fragmentGraphItem : topLeftFragment.getOrCreateValue()) {
Fragment fragment = fragmentGraphItem.getFragment();
if (corner.equals(fragment.getCorner())) {
return fragment;
}
}
return null;
}
}
|
amidst
|
src\main\java\amidst\fragment\FragmentGraphItem.java
|
package amidst.fragment;
import java.util.Iterator;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
@NotThreadSafe
public class FragmentGraphItem implements Iterable<FragmentGraphItem> {
/**
* This is an Iterator that is fail safe in the sense that it will never
* throw a NullPointerException or ConcurrentModificationException when the
* fragment graph is altered while the iterator is used. However, the
* elements returned by this iterator will fit the old state or the new
* state or something in between. This should be good enough for our use
* cases.
*/
@NotThreadSafe
private static class FragmentGraphItemIterator implements Iterator<FragmentGraphItem> {
private FragmentGraphItem rowStart;
private FragmentGraphItem currentNode;
public FragmentGraphItemIterator(FragmentGraphItem fragment) {
rowStart = fragment.getFirstColumn().getFirstRow();
currentNode = rowStart;
}
@Override
public boolean hasNext() {
return currentNode != null;
}
@Override
public FragmentGraphItem next() {
FragmentGraphItem result = currentNode;
updateCurrentNode();
return result;
}
private void updateCurrentNode() {
currentNode = currentNode.rightFragment;
if (currentNode == null) {
rowStart = rowStart.belowFragment;
currentNode = rowStart;
}
}
}
private final Fragment fragment;
private volatile FragmentGraphItem leftFragment = null;
private volatile FragmentGraphItem rightFragment = null;
private volatile FragmentGraphItem aboveFragment = null;
private volatile FragmentGraphItem belowFragment = null;
@CalledOnlyBy(AmidstThread.EDT)
public FragmentGraphItem(Fragment fragment) {
this.fragment = fragment;
}
@CalledOnlyBy(AmidstThread.EDT)
public Fragment getFragment() {
return fragment;
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
public Iterator<FragmentGraphItem> iterator() {
return new FragmentGraphItemIterator(this);
}
@CalledOnlyBy(AmidstThread.EDT)
public boolean isEndOfLine() {
return rightFragment == null;
}
@CalledOnlyBy(AmidstThread.EDT)
public void recycleAll(FragmentManager manager) {
FragmentGraphItem topLeft = getFirstColumn().getFirstRow();
while (topLeft != null) {
FragmentGraphItem next = topLeft.belowFragment;
topLeft.deleteFirstRow(manager);
topLeft = next;
}
}
/**
* Returns the new fragment in the top left corner, but never null.
*/
@CalledOnlyBy(AmidstThread.EDT)
public FragmentGraphItem adjustRowsAndColumns(
int newAbove,
int newBelow,
int newLeft,
int newRight,
FragmentManager manager) {
FragmentGraphItem firstColumn = getFirstColumn();
FragmentGraphItem topLeft = firstColumn.getFirstRow();
topLeft = topLeft.createOrRemoveRowsAbove(manager, newAbove);
topLeft.getLastRow().createOrRemoveRowsBelow(manager, newBelow);
topLeft = topLeft.createOrRemoveColumnsLeft(manager, newLeft);
topLeft.getLastColumn().createOrRemoveColumnsRight(manager, newRight);
return topLeft;
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem createOrRemoveRowsAbove(FragmentManager manager, int newAbove) {
FragmentGraphItem topLeft = this;
for (int i = 0; i < newAbove; i++) {
topLeft.createFirstRow(manager);
topLeft = topLeft.aboveFragment;
}
for (int i = 0; i < -newAbove; i++) {
FragmentGraphItem next = topLeft.belowFragment;
topLeft.deleteFirstRow(manager);
topLeft = next;
}
return topLeft;
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem createOrRemoveRowsBelow(FragmentManager manager, int newBelow) {
FragmentGraphItem bottomLeft = this;
for (int i = 0; i < newBelow; i++) {
bottomLeft.createLastRow(manager);
bottomLeft = bottomLeft.belowFragment;
}
for (int i = 0; i < -newBelow; i++) {
FragmentGraphItem next = bottomLeft.aboveFragment;
bottomLeft.deleteLastRow(manager);
bottomLeft = next;
}
return bottomLeft;
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem createOrRemoveColumnsLeft(FragmentManager manager, int newLeft) {
FragmentGraphItem topLeft = this;
for (int i = 0; i < newLeft; i++) {
topLeft.createFirstColumn(manager);
topLeft = topLeft.leftFragment;
}
for (int i = 0; i < -newLeft; i++) {
FragmentGraphItem next = topLeft.rightFragment;
topLeft.deleteFirstColumn(manager);
topLeft = next;
}
return topLeft;
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem createOrRemoveColumnsRight(FragmentManager manager, int newRight) {
FragmentGraphItem topRight = this;
for (int i = 0; i < newRight; i++) {
topRight.createLastColumn(manager);
topRight = topRight.rightFragment;
}
for (int i = 0; i < -newRight; i++) {
FragmentGraphItem next = topRight.leftFragment;
topRight.deleteLastColumn(manager);
topRight = next;
}
return topRight;
}
@CalledOnlyBy(AmidstThread.EDT)
private void createFirstRow(FragmentManager manager) {
FragmentGraphItem above = createAbove(manager);
FragmentGraphItem below = rightFragment;
while (below != null) {
above = above.createRight(manager);
above.connectBelow(below);
below = below.rightFragment;
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void createLastRow(FragmentManager manager) {
FragmentGraphItem below = createBelow(manager);
FragmentGraphItem above = rightFragment;
while (above != null) {
below = below.createRight(manager);
below.connectAbove(above);
above = above.rightFragment;
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void createFirstColumn(FragmentManager manager) {
FragmentGraphItem left = createLeft(manager);
FragmentGraphItem right = belowFragment;
while (right != null) {
left = left.createBelow(manager);
left.connectRight(right);
right = right.belowFragment;
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void createLastColumn(FragmentManager manager) {
FragmentGraphItem right = createRight(manager);
FragmentGraphItem left = belowFragment;
while (left != null) {
right = right.createBelow(manager);
right.connectLeft(left);
left = left.belowFragment;
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void deleteFirstRow(FragmentManager manager) {
FragmentGraphItem current = this;
while (current != null) {
current.disconnectBelow();
FragmentGraphItem right = current.disconnectRight();
current.recycle(manager);
current = right;
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void deleteLastRow(FragmentManager manager) {
FragmentGraphItem current = this;
while (current != null) {
current.disconnectAbove();
FragmentGraphItem right = current.disconnectRight();
current.recycle(manager);
current = right;
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void deleteFirstColumn(FragmentManager manager) {
FragmentGraphItem current = this;
while (current != null) {
current.disconnectRight();
FragmentGraphItem below = current.disconnectBelow();
current.recycle(manager);
current = below;
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void deleteLastColumn(FragmentManager manager) {
FragmentGraphItem current = this;
while (current != null) {
current.disconnectLeft();
FragmentGraphItem below = current.disconnectBelow();
current.recycle(manager);
current = below;
}
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem getFirstRow() {
FragmentGraphItem result = this;
while (result.aboveFragment != null) {
result = result.aboveFragment;
}
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem getLastRow() {
FragmentGraphItem result = this;
while (result.belowFragment != null) {
result = result.belowFragment;
}
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem getFirstColumn() {
FragmentGraphItem result = this;
while (result.leftFragment != null) {
result = result.leftFragment;
}
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem getLastColumn() {
FragmentGraphItem result = this;
while (result.rightFragment != null) {
result = result.rightFragment;
}
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem connectAbove(FragmentGraphItem above) {
above.belowFragment = this;
aboveFragment = above;
return above;
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem connectBelow(FragmentGraphItem below) {
below.aboveFragment = this;
belowFragment = below;
return below;
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem connectLeft(FragmentGraphItem left) {
left.rightFragment = this;
leftFragment = left;
return left;
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem connectRight(FragmentGraphItem right) {
right.leftFragment = this;
rightFragment = right;
return right;
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem disconnectAbove() {
if (aboveFragment != null) {
aboveFragment.belowFragment = null;
}
FragmentGraphItem result = aboveFragment;
aboveFragment = null;
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem disconnectBelow() {
if (belowFragment != null) {
belowFragment.aboveFragment = null;
}
FragmentGraphItem result = belowFragment;
belowFragment = null;
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem disconnectLeft() {
if (leftFragment != null) {
leftFragment.rightFragment = null;
}
FragmentGraphItem result = leftFragment;
leftFragment = null;
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem disconnectRight() {
if (rightFragment != null) {
rightFragment.leftFragment = null;
}
FragmentGraphItem result = rightFragment;
rightFragment = null;
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem createAbove(FragmentManager manager) {
return connectAbove(createFragmentGraphItem(manager, 0, -Fragment.SIZE));
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem createBelow(FragmentManager manager) {
return connectBelow(createFragmentGraphItem(manager, 0, Fragment.SIZE));
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem createLeft(FragmentManager manager) {
return connectLeft(createFragmentGraphItem(manager, -Fragment.SIZE, 0));
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem createRight(FragmentManager manager) {
return connectRight(createFragmentGraphItem(manager, Fragment.SIZE, 0));
}
@CalledOnlyBy(AmidstThread.EDT)
private FragmentGraphItem createFragmentGraphItem(FragmentManager manager, int xInWorld, int yInWorld) {
return new FragmentGraphItem(manager.requestFragment(fragment.getCorner().add(xInWorld, yInWorld)));
}
@CalledOnlyBy(AmidstThread.EDT)
private void recycle(FragmentManager manager) {
manager.recycleFragment(fragment);
}
}
|
amidst
|
src\main\java\amidst\fragment\FragmentManager.java
|
package amidst.fragment;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.constructor.FragmentConstructor;
import amidst.fragment.layer.LayerManager;
import amidst.mojangapi.world.Dimension;
import amidst.mojangapi.world.coordinates.CoordinatesInWorld;
import amidst.settings.Setting;
@NotThreadSafe
public class FragmentManager {
private final ConcurrentLinkedQueue<Fragment> availableQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedQueue<Fragment> loadingQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedQueue<Fragment> recycleQueue = new ConcurrentLinkedQueue<>();
private final FragmentCache cache;
private final Setting<Integer> threadsSetting;
private ThreadPoolExecutor fragWorkers;
@CalledOnlyBy(AmidstThread.EDT)
public FragmentManager(Iterable<FragmentConstructor> constructors, int numberOfLayers, Setting<Integer> threadsSetting) {
this.cache = new FragmentCache(availableQueue, loadingQueue, constructors, numberOfLayers);
this.threadsSetting = threadsSetting;
this.fragWorkers = createThreadPool();
}
public ThreadPoolExecutor createThreadPool() {
return (ThreadPoolExecutor) Executors.newFixedThreadPool(threadsSetting.get(), new ThreadFactory() {
private int num;
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "Fragment-Worker-" + num++);
}
});
}
@CalledOnlyBy(AmidstThread.EDT)
public Fragment requestFragment(CoordinatesInWorld coordinates) {
Fragment fragment;
while ((fragment = availableQueue.poll()) == null) {
cache.increaseSize();
}
fragment.setCorner(coordinates);
fragment.setState(Fragment.State.INITIALIZED);
loadingQueue.offer(fragment);
return fragment;
}
@CalledOnlyBy(AmidstThread.EDT)
public void recycleFragment(Fragment fragment) {
recycleQueue.offer(fragment);
}
@CalledOnlyBy(AmidstThread.EDT)
public FragmentQueueProcessor createQueueProcessor(LayerManager layerManager, Setting<Dimension> dimensionSetting) {
return new FragmentQueueProcessor(
availableQueue,
loadingQueue,
recycleQueue,
cache,
layerManager,
fragWorkers,
dimensionSetting);
}
@CalledOnlyBy(AmidstThread.EDT)
public int getAvailableQueueSize() {
return availableQueue.size();
}
@CalledOnlyBy(AmidstThread.EDT)
public int getLoadingQueueSize() {
return loadingQueue.size();
}
@CalledOnlyBy(AmidstThread.EDT)
public int getRecycleQueueSize() {
return recycleQueue.size();
}
@CalledOnlyBy(AmidstThread.EDT)
public void clear() {
cache.clear();
availableQueue.clear();
loadingQueue.clear();
recycleQueue.clear();
}
@CalledOnlyBy(AmidstThread.EDT)
public void restartThreadPool() {
fragWorkers.shutdownNow();
this.fragWorkers = createThreadPool();
}
@CalledOnlyBy(AmidstThread.EDT)
public int getCacheSize() {
return cache.size();
}
}
|
amidst
|
src\main\java\amidst\fragment\FragmentQueueProcessor.java
|
package amidst.fragment;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.LockSupport;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledByAny;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.Fragment.State;
import amidst.fragment.layer.LayerManager;
import amidst.mojangapi.world.Dimension;
import amidst.settings.Setting;
@NotThreadSafe
public class FragmentQueueProcessor {
private final ConcurrentLinkedQueue<Fragment> availableQueue;
private final ConcurrentLinkedQueue<Fragment> loadingQueue;
private final ConcurrentLinkedQueue<Fragment> recycleQueue;
private final FragmentCache cache;
private final LayerManager layerManager;
private final ThreadPoolExecutor fragWorkers;
private final Setting<Dimension> dimensionSetting;
@CalledByAny
public FragmentQueueProcessor(
ConcurrentLinkedQueue<Fragment> availableQueue,
ConcurrentLinkedQueue<Fragment> loadingQueue,
ConcurrentLinkedQueue<Fragment> recycleQueue,
FragmentCache cache,
LayerManager layerManager,
ThreadPoolExecutor fragWorkers,
Setting<Dimension> dimensionSetting) {
this.availableQueue = availableQueue;
this.loadingQueue = loadingQueue;
this.recycleQueue = recycleQueue;
this.cache = cache;
this.layerManager = layerManager;
this.dimensionSetting = dimensionSetting;
this.fragWorkers = fragWorkers;
}
private static final int PARK_MILLIS = 1000;
/**
* It is important that the dimension setting is the same while a fragment
* is loaded by different fragment loaders. This is why the dimension
* setting is read by the fragment loader thread.
*/
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
public void processQueues() {
final Thread flThread = Thread.currentThread(); // the fragment loader thread
Dimension dimension = dimensionSetting.get();
updateLayerManager(dimension);
processRecycleQueue();
/*
* We queue fragments to the thread pool only when a thread isn't working.
* This keeps the thread pool queue small and doesn't make the fragment
* loading thread think we're done when we're still processing fragments.
* While the latter does happen a small amount with this setup, it's not
* to the extent of if we were pushing to the thread pool queue as fast
* as possible.
*/
int maxSize = fragWorkers.getMaximumPoolSize();
while (loadingQueue.isEmpty() == false) {
if (fragWorkers.getActiveCount() < maxSize) {
fragWorkers.execute(() -> {
Fragment f = loadingQueue.poll();
if (f != null && dimension.equals(dimensionSetting.get())) {
loadFragment(dimension, f);
updateLayerManager(dimension);
processRecycleQueue();
LockSupport.unpark(flThread);
}
});
} else {
LockSupport.parkNanos(PARK_MILLIS * 1000000); // if for some reason unpark was never called, unpark after time expires
}
}
layerManager.clearInvalidatedLayers();
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
private void updateLayerManager(Dimension dimension) {
if (layerManager.updateAll(dimension)) {
cache.reloadAll();
}
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
private void processRecycleQueue() {
Fragment fragment;
while ((fragment = recycleQueue.poll()) != null) {
recycleFragment(fragment);
}
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
private void loadFragment(Dimension dimension, Fragment fragment) {
if (fragment.getState().equals(Fragment.State.LOADED)) {
layerManager.reloadInvalidated(dimension, fragment);
} else if (!fragment.getState().equals(Fragment.State.UNINITIALIZED)
&& !fragment.getAndSetState(Fragment.State.LOADING).equals(Fragment.State.LOADING)) {
//If it's not loading, set loading and continue. If it is already loading, don't continue.
layerManager.loadAll(dimension, fragment);
fragment.setState(State.LOADED);
}
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
private void recycleFragment(Fragment fragment) {
if (fragment.tryRecycle()) {
removeFromLoadingQueue(fragment);
availableQueue.offer(fragment);
}
}
// TODO: Check performance with and without this. It is not needed, since
// loadFragment checks for isInitialized(). It helps to keep the
// loadingQueue small, but it costs time to remove fragments from the queue.
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
private void removeFromLoadingQueue(Object fragment) {
while (loadingQueue.remove(fragment)) {
// noop
}
}
}
|
amidst
|
src\main\java\amidst\logging\AmidstLogger.java
|
package amidst.logging;
import java.util.HashMap;
import java.util.Map;
import amidst.documentation.ThreadSafe;
// TODO: switch to standard logging framework like slf4j + log4j?
@ThreadSafe
public class AmidstLogger {
private static final String DEBUG_TAG = "debug";
private static final String INFO_TAG = "info";
private static final String WARNING_TAG = "warning";
private static final String ERROR_TAG = "error";
private static final String CRASH_TAG = "crash";
private static final ConsoleLogger CONSOLE_LOGGER = new ConsoleLogger();
private static final InMemoryLogger IN_MEMORY_LOGGER = new InMemoryLogger();
private static final Object LOG_LOCK = new Object();
private static final Map<String, Logger> LOGGER = createLoggerMap();
private static Map<String, Logger> createLoggerMap() {
Map<String, Logger> result = new HashMap<>();
result.put("console", CONSOLE_LOGGER);
result.put("master", IN_MEMORY_LOGGER);
return result;
}
public static void addListener(String name, Logger logger) {
synchronized (LOG_LOCK) {
LOGGER.put(name, logger);
}
}
public static void removeListener(String name) {
synchronized (LOG_LOCK) {
LOGGER.remove(name);
}
}
public static void debug(Throwable e) {
log(DEBUG_TAG, MessageFormatter.format(e));
}
public static void debug(String message) {
log(DEBUG_TAG, MessageFormatter.format(message));
}
public static void debug(String message, Object part1, Object... parts) {
log(DEBUG_TAG, MessageFormatter.format(message, part1, parts));
}
public static void debug(Throwable e, String message) {
log(DEBUG_TAG, MessageFormatter.format(message));
log(DEBUG_TAG, MessageFormatter.format(e));
}
public static void debug(Throwable e, String message, Object part1, Object... parts) {
log(DEBUG_TAG, MessageFormatter.format(message, part1, parts));
log(DEBUG_TAG, MessageFormatter.format(e));
}
public static void info(Throwable e) {
log(INFO_TAG, MessageFormatter.format(e));
}
public static void info(String message) {
log(INFO_TAG, MessageFormatter.format(message));
}
public static void info(String message, Object part1, Object... parts) {
log(INFO_TAG, MessageFormatter.format(message, part1, parts));
}
public static void info(Throwable e, String message) {
log(INFO_TAG, MessageFormatter.format(message));
log(INFO_TAG, MessageFormatter.format(e));
}
public static void info(Throwable e, String message, Object part1, Object... parts) {
log(INFO_TAG, MessageFormatter.format(message, part1, parts));
log(INFO_TAG, MessageFormatter.format(e));
}
public static void warn(Throwable e) {
log(WARNING_TAG, MessageFormatter.format(e));
}
public static void warn(String message) {
log(WARNING_TAG, MessageFormatter.format(message));
}
public static void warn(String message, Object part1, Object... parts) {
log(WARNING_TAG, MessageFormatter.format(message, part1, parts));
}
public static void warn(Throwable e, String message) {
log(WARNING_TAG, MessageFormatter.format(message));
log(WARNING_TAG, MessageFormatter.format(e));
}
public static void warn(Throwable e, String message, Object part1, Object... parts) {
log(WARNING_TAG, MessageFormatter.format(message, part1, parts));
log(WARNING_TAG, MessageFormatter.format(e));
}
public static void error(Throwable e) {
log(ERROR_TAG, MessageFormatter.format(e));
}
public static void error(String message) {
log(ERROR_TAG, MessageFormatter.format(message));
}
public static void error(String message, Object part1, Object... parts) {
log(ERROR_TAG, MessageFormatter.format(message, part1, parts));
}
public static void error(Throwable e, String message) {
log(ERROR_TAG, MessageFormatter.format(message));
log(ERROR_TAG, MessageFormatter.format(e));
}
public static void error(Throwable e, String message, Object part1, Object... parts) {
log(ERROR_TAG, MessageFormatter.format(message, part1, parts));
log(ERROR_TAG, MessageFormatter.format(e));
}
public static void crash(Throwable e) {
log(CRASH_TAG, MessageFormatter.format(e));
}
public static void crash(String message) {
log(CRASH_TAG, MessageFormatter.format(message));
}
public static void crash(String message, Object part1, Object... parts) {
log(CRASH_TAG, MessageFormatter.format(message, part1, parts));
}
public static void crash(Throwable e, String message) {
log(CRASH_TAG, MessageFormatter.format(message));
log(CRASH_TAG, MessageFormatter.format(e));
}
public static void crash(Throwable e, String message, Object part1, Object... parts) {
log(CRASH_TAG, MessageFormatter.format(message, part1, parts));
log(CRASH_TAG, MessageFormatter.format(e));
}
private static void log(String tag, String message) {
synchronized (LOG_LOCK) {
for (Logger listener : LOGGER.values()) {
listener.log(tag, message);
}
}
}
public static String getAllMessages() {
synchronized (LOG_LOCK) {
return IN_MEMORY_LOGGER.getContents();
}
}
}
|
amidst
|
src\main\java\amidst\logging\AmidstMessageBox.java
|
package amidst.logging;
import java.awt.Component;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
@NotThreadSafe
public enum AmidstMessageBox {
;
public static void displayError(String title, Throwable e) {
displayMessageBox(title, MessageFormatter.format(e), JOptionPane.ERROR_MESSAGE);
}
public static void displayError(String title, Throwable e, String message) {
displayMessageBox(title, MessageFormatter.format(e, message), JOptionPane.ERROR_MESSAGE);
}
public static void displayError(String title, Throwable e, String message, Object part1, Object[] parts) {
displayMessageBox(title, MessageFormatter.format(e, message, part1, parts), JOptionPane.ERROR_MESSAGE);
}
public static void displayError(String title, String message) {
displayMessageBox(title, MessageFormatter.format(message), JOptionPane.ERROR_MESSAGE);
}
public static void displayError(String title, String message, Object part1, Object[] parts) {
displayMessageBox(title, MessageFormatter.format(message, part1, parts), JOptionPane.ERROR_MESSAGE);
}
public static void displayInfo(String title, String message) {
displayMessageBox(title, MessageFormatter.format(message), JOptionPane.INFORMATION_MESSAGE);
}
public static void displayInfo(String title, String message, Object part1, Object[] parts) {
displayMessageBox(title, MessageFormatter.format(message, part1, parts), JOptionPane.INFORMATION_MESSAGE);
}
public static void displayError(Component parent, String title, Throwable e) {
displayMessageBox(parent, title, MessageFormatter.format(e), JOptionPane.ERROR_MESSAGE);
}
public static void displayError(Component parent, String title, Throwable e, String message) {
displayMessageBox(parent, title, MessageFormatter.format(e, message), JOptionPane.ERROR_MESSAGE);
}
public static void displayWarning(String title, String message) {
displayMessageBox(title, MessageFormatter.format(message), JOptionPane.WARNING_MESSAGE);
}
public static void displayWarning(String title, String message, Object part1, Object[] parts) {
displayMessageBox(title, MessageFormatter.format(message, part1, parts), JOptionPane.WARNING_MESSAGE);
}
public static void displayWarning(Component parent, String title, String message) {
displayMessageBox(parent, title, MessageFormatter.format(message), JOptionPane.WARNING_MESSAGE);
}
public static void displayWarning(Component parent, String title, String message, Object part1, Object[] parts) {
displayMessageBox(
parent,
title,
MessageFormatter.format(message, part1, parts),
JOptionPane.WARNING_MESSAGE);
}
public static void displayError(
Component parent,
String title,
Throwable e,
String message,
String part1,
String[] parts) {
displayMessageBox(parent, title, MessageFormatter.format(e, message, part1, parts), JOptionPane.ERROR_MESSAGE);
}
public static void displayError(Component parent, String title, String message) {
displayMessageBox(parent, title, MessageFormatter.format(message), JOptionPane.ERROR_MESSAGE);
}
public static void displayError(Component parent, String title, String message, Object part1, Object[] parts) {
displayMessageBox(parent, title, MessageFormatter.format(message, part1, parts), JOptionPane.ERROR_MESSAGE);
}
public static void displayInfo(Component parent, String title, String message) {
displayMessageBox(parent, title, MessageFormatter.format(message), JOptionPane.INFORMATION_MESSAGE);
}
public static void displayInfo(Component parent, String title, String message, Object part1, Object[] parts) {
displayMessageBox(
parent,
title,
MessageFormatter.format(message, part1, parts),
JOptionPane.INFORMATION_MESSAGE);
}
private static void displayMessageBox(String title, String message, int type) {
displayMessageBox(null, title, message, type);
}
private static void displayMessageBox(Component parent, String title, String message, int type) {
SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(parent, message, title, type));
}
@CalledOnlyBy(AmidstThread.EDT)
public static boolean askToConfirmYesNo(String title, String message) {
return askToConfirmYesNo(null, title, message);
}
@CalledOnlyBy(AmidstThread.EDT)
public static boolean askToConfirmYesNo(Component parent, String title, String message) {
return JOptionPane
.showConfirmDialog(parent, message, title, JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
}
}
|
amidst
|
src\main\java\amidst\logging\ConsoleLogger.java
|
package amidst.logging;
import amidst.documentation.NotThreadSafe;
@NotThreadSafe
public class ConsoleLogger implements Logger {
@Override
public void log(String tag, String message) {
System.out.println("[" + tag + "] " + message);
}
}
|
amidst
|
src\main\java\amidst\logging\FileLogger.java
|
package amidst.logging;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.sql.Timestamp;
import java.util.Date;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
@NotThreadSafe
public class FileLogger implements Logger {
private final ConcurrentLinkedQueue<String> logMessageQueue = new ConcurrentLinkedQueue<>();
private final Path file;
private final ScheduledExecutorService executor;
@CalledOnlyBy(AmidstThread.STARTUP)
public FileLogger(Path file) {
this.file = file;
this.executor = createExecutor();
if (ensureFileExists()) {
writeWelcomeMessageToFile();
start();
}
}
@CalledOnlyBy(AmidstThread.STARTUP)
private ScheduledExecutorService createExecutor() {
return Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setPriority(Thread.MIN_PRIORITY);
return thread;
}
});
}
@CalledOnlyBy(AmidstThread.STARTUP)
private boolean ensureFileExists() {
try {
Files.createFile(file);
} catch (FileAlreadyExistsException e){
if (Files.isDirectory(file)) {
disableBecauseFileIsDirectory();
return false;
} else {
// log file already exists; nothing to do
}
} catch (IOException e) {
disableBecauseFileCreationThrowsException(e);
return false;
}
return true;
}
@CalledOnlyBy(AmidstThread.STARTUP)
private void disableBecauseFileCreationThrowsException(IOException e) {
AmidstLogger.warn(e, "Unable to create new file at: {} disabling logging to file.", file);
}
@CalledOnlyBy(AmidstThread.STARTUP)
private void disableBecauseFileIsDirectory() {
AmidstLogger.warn("Unable to log at path: {} because location is a directory.", file);
}
@CalledOnlyBy(AmidstThread.STARTUP)
private void writeWelcomeMessageToFile() {
log("log", "New FileLogger started.");
}
@CalledOnlyBy(AmidstThread.STARTUP)
private void start() {
executor.scheduleWithFixedDelay(new Runnable() {
@CalledOnlyBy(AmidstThread.FILE_LOGGER)
@Override
public void run() {
processQueue();
}
}, 0, 100, TimeUnit.MILLISECONDS);
}
@CalledOnlyBy(AmidstThread.FILE_LOGGER)
private void processQueue() {
if (!logMessageQueue.isEmpty() && Files.isRegularFile(file)) {
writeLogMessages();
}
}
@CalledOnlyBy(AmidstThread.FILE_LOGGER)
private void writeLogMessages() {
try (BufferedWriter writer = Files.newBufferedWriter(file,
StandardOpenOption.WRITE, StandardOpenOption.APPEND)) {
String msg = null;
while((msg = logMessageQueue.poll()) != null) {
writer.write(msg);
}
} catch (IOException e) {
AmidstLogger.warn(e, "Unable to write to log file.");
}
}
@Override
public void log(String tag, String message) {
String currentTime = new Timestamp(new Date().getTime()).toString();
StringBuilder builder = new StringBuilder()
.append(currentTime)
.append(" [")
.append(tag)
.append("] ")
.append(message)
.append("\r\n");
logMessageQueue.add(builder.toString());
}
}
|
amidst
|
src\main\java\amidst\logging\InMemoryLogger.java
|
package amidst.logging;
import amidst.documentation.NotThreadSafe;
@NotThreadSafe
public class InMemoryLogger implements Logger {
private StringBuffer buffer = new StringBuffer();
@Override
public void log(String tag, String message) {
buffer.append("[").append(tag).append("] ").append(message).append("\n");
}
public String getContents() {
return buffer.toString();
}
}
|
amidst
|
src\main\java\amidst\logging\Logger.java
|
package amidst.logging;
public interface Logger {
void log(String tag, String message);
}
|
amidst
|
src\main\java\amidst\logging\MessageFormatter.java
|
package amidst.logging;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Objects;
import amidst.documentation.Immutable;
@Immutable
public enum MessageFormatter {
;
public static String format(Throwable e, String message) {
return format(message) + "\n\n" + format(e);
}
public static String format(Throwable e, String message, Object part1, Object[] parts) {
return format(message, part1, parts) + "\n\n" + format(e);
}
public static String format(Object message) {
return String.valueOf(message);
}
public static String format(Throwable e) {
if (e != null) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
return writer.toString();
} else {
return "null";
}
}
public static String format(String message, Object part1, Object... parts) {
Objects.requireNonNull(message, "the message cannot be null");
int expectedNumberOfMessageParts = 2 + parts.length;
String[] messageParts = message.split("\\{\\}", expectedNumberOfMessageParts);
if (messageParts.length == 0) {
return "";
} else if (messageParts.length == 1) {
return messageParts[0];
} else {
StringBuilder b = new StringBuilder();
b.append(messageParts[0]);
b.append(format(part1));
b.append(messageParts[1]);
for (int i = 2; i < messageParts.length; i++) {
b.append(format(parts[i - 2]));
b.append(messageParts[i]);
}
return b.toString();
}
}
}
|
amidst
|
src\main\java\amidst\mojangapi\LauncherProfileRunner.java
|
package amidst.mojangapi;
import java.util.Optional;
import amidst.documentation.Immutable;
import amidst.mojangapi.file.LauncherProfile;
import amidst.mojangapi.minecraftinterface.MinecraftInterfaceCreationException;
import amidst.mojangapi.world.WorldBuilder;
import amidst.mojangapi.world.WorldOptions;
@Immutable
public class LauncherProfileRunner {
private final WorldBuilder worldBuilder;
private Optional<WorldOptions> initialWorldOptions;
public LauncherProfileRunner(WorldBuilder worldBuilder, Optional<WorldOptions> initialWorldOptions) {
this.worldBuilder = worldBuilder;
this.initialWorldOptions = initialWorldOptions;
}
public RunningLauncherProfile run(LauncherProfile launcherProfile) throws MinecraftInterfaceCreationException {
return RunningLauncherProfile.from(worldBuilder, launcherProfile, initialWorldOptions);
}
}
|
amidst
|
src\main\java\amidst\mojangapi\RunningLauncherProfile.java
|
package amidst.mojangapi;
import java.io.IOException;
import java.util.Optional;
import amidst.documentation.ThreadSafe;
import amidst.mojangapi.file.LauncherProfile;
import amidst.mojangapi.file.SaveGame;
import amidst.mojangapi.minecraftinterface.LoggingMinecraftInterface;
import amidst.mojangapi.minecraftinterface.MinecraftInterface;
import amidst.mojangapi.minecraftinterface.MinecraftInterfaceCreationException;
import amidst.mojangapi.minecraftinterface.MinecraftInterfaceException;
import amidst.mojangapi.minecraftinterface.MinecraftInterfaces;
import amidst.mojangapi.minecraftinterface.RecognisedVersion;
import amidst.mojangapi.world.World;
import amidst.mojangapi.world.WorldBuilder;
import amidst.mojangapi.world.WorldOptions;
@ThreadSafe
public class RunningLauncherProfile {
public static RunningLauncherProfile from(WorldBuilder worldBuilder, LauncherProfile launcherProfile, Optional<WorldOptions> initialWorldOptions)
throws MinecraftInterfaceCreationException {
return new RunningLauncherProfile(
worldBuilder,
launcherProfile,
new LoggingMinecraftInterface(MinecraftInterfaces.fromLocalProfile(launcherProfile)), initialWorldOptions);
}
private final WorldBuilder worldBuilder;
private final LauncherProfile launcherProfile;
private final MinecraftInterface minecraftInterface;
private final Optional<WorldOptions> initialWorldOptions;
public RunningLauncherProfile(
WorldBuilder worldBuilder,
LauncherProfile launcherProfile,
MinecraftInterface minecraftInterface,
Optional<WorldOptions> initialWorldOptions) {
this.worldBuilder = worldBuilder;
this.launcherProfile = launcherProfile;
this.minecraftInterface = minecraftInterface;
this.initialWorldOptions = initialWorldOptions;
}
public LauncherProfile getLauncherProfile() {
return launcherProfile;
}
public Optional<WorldOptions> getInitialWorldOptions() {
return initialWorldOptions;
}
public RecognisedVersion getRecognisedVersion() {
return minecraftInterface.getRecognisedVersion();
}
public RunningLauncherProfile createSilentPlayerlessCopy() {
try {
return RunningLauncherProfile.from(WorldBuilder.createSilentPlayerless(), launcherProfile, null);
} catch (MinecraftInterfaceCreationException e) {
// This will not happen normally, because we already successfully
// created the same LocalMinecraftInterface once before.
throw new RuntimeException("exception while duplicating the RunningLauncherProfile", e);
}
}
public synchronized World createWorld(WorldOptions worldOptions)
throws MinecraftInterfaceException {
return worldBuilder.from(minecraftInterface, worldOptions);
}
public synchronized World createWorldFromSaveGame(SaveGame saveGame)
throws IOException, MinecraftInterfaceException {
return worldBuilder.fromSaveGame(minecraftInterface, saveGame);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.