Skip to content

Commit

Permalink
Fixes, experimental support for Connector/Forge
Browse files Browse the repository at this point in the history
  • Loading branch information
Patbox committed Sep 4, 2023
1 parent 8d5bedd commit 768af0c
Show file tree
Hide file tree
Showing 38 changed files with 414 additions and 86 deletions.
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ allprojects {
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
modCompileOnly "net.fabricmc:fabric-loader:${project.loader_version}"
modLocalRuntime "net.fabricmc:fabric-loader:${project.loader_version}"

annotationProcessor("io.github.llamalad7:mixinextras-fabric:${mixin_extras_version}")
}

loom {
Expand Down
3 changes: 2 additions & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@ fabric_version=0.83.0+1.20.1

maven_group = eu.pb4

mod_version = 0.5.14
mod_version = 0.5.15

minecraft_version_supported = ">=1.20-"

packet_tweaker_version = 0.4.0+1.19.4
mixin_extras_version = 0.2.0-rc.1

is_stable = true
1 change: 0 additions & 1 deletion polymer-autohost/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ dependencies {
localRuntime (project(path: ':polymer-virtual-entity', configuration: 'namedElements'))
modLocalRuntime("xyz.nucleoid:server-translations-api:2.0.0-beta.2+1.19.4-pre2")


project(":polymer-core").afterEvaluate {
testmodImplementation project(":polymer-core").sourceSets.testmod.output
}
Expand Down
2 changes: 1 addition & 1 deletion polymer-common/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ dependencies {
modApi include("xyz.nucleoid:packet-tweaker:${packet_tweaker_version}") {
transitive(false)
}
modApi(include(annotationProcessor("com.llamalad7.mixinextras:mixinextras-fabric:0.2.0-beta.9")))
modApi(include(annotationProcessor("io.github.llamalad7:mixinextras-fabric:${mixin_extras_version}")))
modCompileOnly "xyz.nucleoid:disguiselib-fabric:1.2.2"
modCompileOnly "org.geysermc.floodgate:api:2.2.0-SNAPSHOT"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,14 @@ public static boolean hasResourcePack(@Nullable ServerPlayerEntity player) {
|| (CommonImpl.IS_CLIENT && ClientUtils.isResourcePackLoaded());
}

public static boolean isServerBound() {
if (CommonImpl.IS_CLIENT) {
return ClientUtils.isSingleplayer();
}

return true;
}

public interface ResourcePackChangeCallback {
void onResourcePackChange(ServerPlayNetworkHandler handler, boolean oldStatus, boolean newStatus);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ public static void addContributor(Person person) {
static {
new CompatStatus();

if (CompatStatus.FORGE_CONNECTOR) {
LOGGER.warn("==================================================================================");
LOGGER.warn("Polymer (" + VERSION + ") support for Connector/Forge is highly experimental!");
LOGGER.warn("Things might not work correctly if at all, so you are on your own!");
LOGGER.warn("=================================================================================");
}

var config = loadConfig("common", CommonConfig.class);
CORE_COMMAND_MINIMAL_OP = config.coreCommandOperatorLevel;
DEVELOPER_MODE = config.enableDevTools || DEV_ENV;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ public final class CompatStatus {
public static final boolean QUILT_ITEM_GROUP = LOADER.isModLoaded("quilt_item_group");
public static final boolean QUILT_REGISTRY = LOADER.isModLoaded("quilt_registry");

public static final boolean FORGE_CONNECTOR = LOADER.isModLoaded("connectormod");

public static final boolean POLYMC = LOADER.isModLoaded("polymc");
public static final boolean LITHIUM = LOADER.isModLoaded("lithium");
public static final boolean DISGUISELIB = LOADER.isModLoaded("disguiselib");
Expand Down
2 changes: 1 addition & 1 deletion polymer-core/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ dependencies {
modCompileOnly "mcp.mobius.waila:wthit:fabric-5.1.3"

//modCompileOnly "me.shedaniel:RoughlyEnoughItems-api-fabric:9.1.530"
modCompileOnly /*modLocalRuntime*/ ("me.shedaniel:RoughlyEnoughItems-fabric:10.0.592")
modCompileOnly /*modLocalRuntime*/ ("me.shedaniel:RoughlyEnoughItems-fabric:12.0.645")
modCompileOnly /*modLocalRuntime*/("dev.emi:emi-fabric:1.0.19+1.20.1")

//modCompileOnlyApi modLocalRuntime("mezz.jei:jei-1.19-common:11.0.0.206")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ public static ItemStack createItemStack(ItemStack itemStack, TooltipContext tool
NbtList lore = new NbtList();

if (itemStack.getNbt() != null) {
out.getNbt().put(PolymerItemUtils.REAL_TAG, itemStack.getNbt());
out.getNbt().put(PolymerItemUtils.REAL_TAG, removeStackMarker(itemStack.getNbt()));
assert out.getNbt() != null;
cmd = cmd == -1 && itemStack.getNbt().contains("CustomModelData") ? itemStack.getNbt().getInt("CustomModelData") : cmd;

Expand Down Expand Up @@ -512,6 +512,24 @@ public static ItemStack createItemStack(ItemStack itemStack, TooltipContext tool
});
}

private static NbtElement removeStackMarker(NbtElement nbt) {
if (nbt instanceof NbtCompound compound) {
var out = new NbtCompound();
for (var entry : compound.getKeys()) {
out.put(entry, removeStackMarker(compound.get(entry)));
}
return out;
} else if (nbt instanceof NbtList list) {
var out = new NbtList();
for (var entry : list) {
out.add(removeStackMarker(entry));
}
return out;
}

return nbt;
}

/**
* This method is minimal wrapper around {@link PolymerItem#getPolymerItem(ItemStack, ServerPlayerEntity)} to make sure
* It gets replaced if it represents other PolymerItem
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,6 @@ public static ItemStack convertStack(ItemStack representation, ServerPlayerEntit
}

public static ItemStack convertStack(ItemStack representation, ServerPlayerEntity player, TooltipContext context) {
return ServerTranslationUtils.parseFor(player.networkHandler, PolyMcUtils.toVanilla(PolymerItemUtils.getPolymerItemStack(representation, context, player), player));
return ServerTranslationUtils.parseFor(player.networkHandler, PolyMcUtils.toVanilla(PolymerItemUtils.getPolymerItemStack(representation, context, player), player));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ public static void tick() {
regInfo.append(", ");
}

regInfo.append("BS: " + InternalClientRegistry.BLOCK_STATES.mapSize());
regInfo.append("BS: ").append(InternalClientRegistry.BLOCK_STATES.mapSize());

debugRegistryInfo = regInfo.toString();

Expand All @@ -330,7 +330,7 @@ public static void clear() {
try {
((ClientItemGroupExtension) group).polymer$clearStacks();
} catch (Throwable e) {
e.printStackTrace();
PolymerImpl.LOGGER.warn("Can't clear stacks of ItemGroup!", e);
}
}
}
Expand All @@ -339,7 +339,7 @@ public static void clear() {
ItemGroupsAccessor.callUpdateEntries(ItemGroupsAccessor.getDisplayContext());
}
} catch (Throwable e) {
e.printStackTrace();
PolymerImpl.LOGGER.warn("Can't update entries of ItemGroups!", e);
}
});
PolymerClientUtils.ON_CLEAR.invoke(EventRunners.RUN);
Expand All @@ -352,17 +352,7 @@ public static void clearTabs(Predicate<InternalClientItemGroup> removePredicate)
ITEM_GROUPS.removeIf(removePredicate);
CreativeInventoryScreenAccessor.setSelectedTab(ItemGroups.getDefaultTab());

if (CompatStatus.FABRIC_ITEM_GROUP) {
try {
/*ItemGroupHelper.sortedGroups = validated.stream().sorted((a, b) -> {
if (a.isSpecial() && !b.isSpecial()) return 1;
if (!a.isSpecial() && b.isSpecial()) return -1;
return 0;
}).toList();*/
} catch (Throwable e) {

}

if (CompatStatus.FABRIC_ITEM_GROUP && !CompatStatus.FORGE_CONNECTOR) {
try {
var f1 = CreativeInventoryScreen.class.getDeclaredField("fabric_currentPage");
f1.setAccessible(true);
Expand All @@ -388,7 +378,18 @@ public static void clearTabs(Predicate<InternalClientItemGroup> removePredicate)
PolymerImpl.LOGGER.error("Failed to change item group page (QUILT)!", e);
}
}
}

if (CompatStatus.FORGE_CONNECTOR) {
try {
var f1 = Class.forName("net.minecraftforge.common.CreativeModeTabRegistry").getDeclaredField("SORTED_TABS");
f1.setAccessible(true);
((List<ItemGroup>) f1.get(null)).removeIf((x) -> x instanceof InternalClientItemGroup ig && removePredicate.test(ig));
} catch (Throwable e) {
if (PolymerImpl.LOG_MORE_ERRORS) {
PolymerImpl.LOGGER.error("Failed to change item group page (FORGE)!", e);
}
}
}

int count = Registries.ITEM_GROUP.size() - 4;
Expand All @@ -408,11 +409,11 @@ public static void clearTabs(Predicate<InternalClientItemGroup> removePredicate)

private static void setItemGroupPage(ItemGroup group, int page) {
((ClientItemGroupExtension) group).polymerCore$setPage(page);
if (CompatStatus.FABRIC_ITEM_GROUP) {
if (CompatStatus.FABRIC_ITEM_GROUP && !CompatStatus.FORGE_CONNECTOR) {
try {
((net.fabricmc.fabric.impl.itemgroup.FabricItemGroup) group).setPage(page);
} catch (Throwable e) {
e.printStackTrace();
PolymerImpl.LOGGER.warn("Couldn't set page of ItemGroup (FABRIC)", e);
}
}
}
Expand All @@ -432,6 +433,19 @@ public static void createItemGroup(Identifier id, Text name, ItemStack icon) {

var group = new InternalClientItemGroup(row, c, id, name, icon);
ITEM_GROUPS.set(id, group);

if (CompatStatus.FORGE_CONNECTOR) {
try {
var f1 = Class.forName("net.minecraftforge.common.CreativeModeTabRegistry").getDeclaredField("SORTED_TABS");
f1.setAccessible(true);
((List<ItemGroup>) f1.get(null)).add(group);
} catch (Throwable e) {
if (PolymerImpl.LOG_MORE_ERRORS) {
PolymerImpl.LOGGER.error("Failed to change item group page (FORGE)!", e);
}
}
}

setItemGroupPage(group, page);
} catch(Throwable e) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public static void register() {
));
}));
registerPacketHandler(ServerPackets.SYNC_BLOCKSTATE, (handler, version, buf) -> handleGenericSync(handler, version, buf, PolymerBlockStateEntry::read,
(entry) -> InternalClientRegistry.BLOCK_STATES.set(new ClientPolymerBlock.State(entry.states(), InternalClientRegistry.BLOCKS.get(entry.blockId()), blockStateOrNull(entry.states(), InternalClientRegistry.BLOCKS.get(entry.blockId()))), entry.numId())));
(entry) -> InternalClientRegistry.BLOCK_STATES.set(new ClientPolymerBlock.State(entry.properties(), InternalClientRegistry.BLOCKS.get(entry.blockId()), blockStateOrNull(entry.properties(), InternalClientRegistry.BLOCKS.get(entry.blockId()))), entry.numId())));

registerPacketHandler(ServerPackets.SYNC_ENTITY, (handler, version, buf) -> handleGenericSync(handler, version, buf, PolymerEntityEntry::read,
(entry) -> InternalClientRegistry.ENTITY_TYPES.set(entry.identifier(), entry.rawId(), new ClientPolymerEntityType(entry.identifier(), entry.name(), Registries.ENTITY_TYPE.get(entry.identifier())))));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@ public static BlockState toVanilla(BlockState state, ServerPlayerEntity player)
}

public static ItemStack toVanilla(ItemStack stack, ServerPlayerEntity player) {
if (CompatStatus.POLYMC) {
if (CompatStatus.POLYMC && !stack.isEmpty()) {
var out = PolyMapProvider.getPolyMap(player).getClientItem(stack, player, ItemLocation.INVENTORY);
if (!ItemStack.canCombine(stack, out) && !stack.isEmpty()) {
if (!ItemStack.canCombine(stack, out)) {
out = out.copy();
out.setSubNbt("PolyMcOriginal", stack.writeNbt(new NbtCompound()));
return out;
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
package eu.pb4.polymer.core.impl.interfaces;

import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NbtByte;
import net.minecraft.nbt.NbtElement;

public interface ItemStackAwareNbtCompound {
String MARKER_KEY = "$$polymer:itemstack";
NbtElement MARKER_VALUE = NbtByte.of((byte) 1);
default void polymerCore$setItemStack(boolean bool) {};
default boolean polymerCore$getItemStack() {
return false;
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ public interface PolymerIdList<T> {
int polymer$getOffset();
void polymer$clear();

int polymer$getVanillaBitCount();
int polymer$getNonPolymerBitCount();

void polymer$setReorderLock(boolean value);
boolean polymer$getReorderLock();
int polymer$getVanillaBitCount();
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,19 +54,19 @@ public static void sendBlockUpdate(ServerPlayNetworkHandler player, BlockPos pos

}

public static void sendMultiBlockUpdate(ServerPlayNetworkHandler player, ChunkSectionPos chunkPos, short[] positions, BlockState[] blockSTATE_IDS) {
public static void sendMultiBlockUpdate(ServerPlayNetworkHandler player, ChunkSectionPos chunkPos, short[] positions, BlockState[] blockStates) {
var version = PolymerServerNetworking.getSupportedVersion(player, ServerPackets.WORLD_CHUNK_SECTION_UPDATE);

if (version > -1) {
var list = new LongArrayList();

for (int i = 0; i < blockSTATE_IDS.length; i++) {
if (PolymerImplUtils.POLYMER_STATES.contains(blockSTATE_IDS[i])) {
list.add(((long) Block.STATE_IDS.getRawId(blockSTATE_IDS[i])) << 12 | positions[i]);
for (int i = 0; i < blockStates.length; i++) {
if (PolymerImplUtils.POLYMER_STATES.contains(blockStates[i])) {
list.add(((long) Block.STATE_IDS.getRawId(blockStates[i])) << 12 | positions[i]);
}
}

if (list.size() != 0) {
if (!list.isEmpty()) {
var buf = buf(version);
buf.writeChunkSectionPos(chunkPos);
buf.writeVarInt(list.size());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@
import java.util.Map;

@ApiStatus.Internal
public record PolymerBlockStateEntry(Map<String, String> states, int numId, int blockId) implements BufferWritable {
public record PolymerBlockStateEntry(Map<String, String> properties, int numId, int blockId) implements BufferWritable {
public static final IdentityHashMap<BlockState, PolymerBlockStateEntry> CACHE = new IdentityHashMap<>();

public void write(PacketByteBuf buf, int version, ServerPlayNetworkHandler handler) {
buf.writeVarInt(numId);
buf.writeVarInt(blockId);
buf.writeMap(states, PacketByteBuf::writeString, PacketByteBuf::writeString);
buf.writeMap(properties, PacketByteBuf::writeString, PacketByteBuf::writeString);
}

public static PolymerBlockStateEntry of(BlockState state, ServerPlayNetworkHandler player, int version) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package eu.pb4.polymer.core.mixin.block.packet;

import com.llamalad7.mixinextras.injector.ModifyReceiver;
import eu.pb4.polymer.core.api.block.PolymerBlockUtils;
import eu.pb4.polymer.core.api.utils.PolymerUtils;
import eu.pb4.polymer.core.impl.ClientMetadataKeys;
import eu.pb4.polymer.core.impl.PolymerImpl;
import eu.pb4.polymer.core.impl.interfaces.PolymerIdList;
import eu.pb4.polymer.networking.api.PolymerServerNetworking;
import net.minecraft.block.Block;
Expand All @@ -12,46 +14,46 @@
import net.minecraft.util.collection.PaletteStorage;
import net.minecraft.world.chunk.IdListPalette;
import net.minecraft.world.chunk.Palette;
import net.minecraft.world.chunk.PalettedContainer;
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.ModifyArg;
import org.spongepowered.asm.mixin.injection.Redirect;

@Mixin(targets = "net/minecraft/world/chunk/PalettedContainer$Data")
public class PalettedContainerDataMixin<T> {
@Shadow @Final private Palette<T> palette;
@Mixin(PalettedContainer.Data.class)
public abstract class PalettedContainerDataMixin<T> {
@Shadow public abstract Palette<T> palette();

@Shadow @Final private PaletteStorage storage;

@ModifyArg(method = "writePacket", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/PacketByteBuf;writeLongArray([J)Lnet/minecraft/network/PacketByteBuf;"), require = 0)
private long[] polymer$replaceData(long[] initialReturn) {
if (this.palette instanceof IdListPalette<T> && this.palette.get(0) instanceof BlockState) {
var palette = (IdListPalette<BlockState>) this.palette;
@ModifyReceiver(method = "writePacket", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/collection/PaletteStorage;getData()[J"), require = 0)
private PaletteStorage polymer$replaceData(PaletteStorage storage) {
var palette = this.palette();
if (palette instanceof IdListPalette<T> && palette.get(0) instanceof BlockState) {
var player = PolymerUtils.getPlayerContext();
if (player == null) {
return initialReturn;
return storage;
}
int bits;

var playerBitCount = PolymerServerNetworking.getMetadata(player.networkHandler, ClientMetadataKeys.BLOCKSTATE_BITS, NbtInt.TYPE);
if (playerBitCount == null) {
bits = ((PolymerIdList<?>) Block.STATE_IDS).polymer$getVanillaBitCount();
bits = PolymerImpl.SYNC_MODDED_ENTRIES_POLYMC
? ((PolymerIdList<?>) Block.STATE_IDS).polymer$getVanillaBitCount()
: ((PolymerIdList<?>) Block.STATE_IDS).polymer$getNonPolymerBitCount();
} else {
bits = playerBitCount.intValue();
}
final var instance = new PackedIntegerArray(this.storage.getElementBits(), this.storage.getSize(), initialReturn);
final int size = instance.getSize();
final int size = storage.getSize();
var data = new PackedIntegerArray(bits, size);

var stateMap = Block.STATE_IDS;

for (int i = 0; i < size; i++) {
data.set(i, palette.index(PolymerBlockUtils.getPolymerBlockState(palette.get(instance.get(i)), player)));
data.set(i, stateMap.getRawId(PolymerBlockUtils.getPolymerBlockState(stateMap.get(storage.get(i)), player)));
}

return data.getData();
return data;
}

return initialReturn;
return storage;
}
}
Loading

0 comments on commit 768af0c

Please sign in to comment.