Compare commits

..

1 Commits

Author SHA1 Message Date
ZacSharp
1101a8498a v1.10.3 2025-05-13 19:55:44 +02:00
85 changed files with 794 additions and 1220 deletions

View File

@@ -17,10 +17,10 @@ jobs:
with:
fetch-depth: 0
- name: Set up JDK 21
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: '21'
java-version: '17'
distribution: 'temurin'
cache: gradle

View File

@@ -12,10 +12,10 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Set up JDK 21
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: '21'
java-version: '17'
distribution: 'temurin'
- name: Grant execute permission for gradlew

View File

@@ -5,7 +5,7 @@ ENV DEBIAN_FRONTEND noninteractive
RUN apt update -y
RUN apt install \
openjdk-21-jdk \
openjdk-17-jdk \
git \
--assume-yes

View File

@@ -56,7 +56,7 @@ The recommended Java versions by Minecraft version are
| 1.12.2 - 1.16.5 | 8 |
| 1.17.1 | 16 |
| 1.18.2 - 1.20.4 | 17 |
| 1.20.5 - 1.21.5 | 21 |
| 1.20.5 - 1.21.4 | 21 |
Download java: https://adoptium.net/

View File

@@ -82,8 +82,6 @@ allprojects {
compileOnly "org.ow2.asm:asm:${project.asm_version}"
implementation "dev.babbaj:nether-pathfinder:${project.nether_pathfinder_version}"
implementation 'com.google.code.findbugs:jsr305:3.0.2'
}
unimined.minecraft(sourceSets.main, true) {
@@ -92,9 +90,7 @@ allprojects {
mappings {
intermediary()
mojmap()
parchment("1.21.4", "2025.03.23")
devFallbackNamespace "official"
parchment("2023.06.26")
}
}

View File

@@ -40,5 +40,5 @@ dependencies {
implementation group: 'com.google.code.gson', name: 'gson', version: '2.9.0'
implementation group: 'commons-io', name: 'commons-io', version: '2.7'
implementation group: 'xyz.wagyourtail.unimined', name: 'xyz.wagyourtail.unimined.gradle.plugin', version: '1.2.9'
implementation group: 'xyz.wagyourtail.unimined', name: 'xyz.wagyourtail.unimined.gradle.plugin', version: '1.0.5'
}

View File

@@ -78,7 +78,7 @@ components.java {
}
task proguard(type: ProguardTask) {
proguardVersion "7.4.2"
proguardVersion "7.2.1"
compType "fabric"
}

View File

@@ -1,3 +1,4 @@
{
"schemaVersion": 1,
"id": "baritone",
@@ -23,9 +24,10 @@
"mixins": [
"mixins.baritone.json"
],
"depends": {
"fabricloader": ">=0.14.22",
"minecraft": ["1.21.9", "1.21.10"]
"fabricloader": ">=0.11.0",
"minecraft": ">=1.20 <=1.20.1"
},
"custom": {
"modmenu": {

View File

@@ -25,7 +25,11 @@ plugins {
archivesBaseName = archivesBaseName + "-forge"
unimined.minecraft {
minecraftForge {
mappings {
devFallbackNamespace "intermediary"
}
forge {
loader project.forge_version
mixinConfig ["mixins.baritone.json"]
}
@@ -95,7 +99,7 @@ components.java {
}
task proguard(type: ProguardTask) {
proguardVersion "7.4.2"
proguardVersion "7.2.1"
compType "forge"
}

View File

@@ -6,7 +6,7 @@
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
modLoader="javafml" #mandatory
# A version range to match for said mod loader - for regular FML @Mod it will be the forge version
loaderVersion="[48,)" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions.
loaderVersion="[46,)" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions.
license="https://raw.githubusercontent.com/cabaletta/baritone/1.16.2/LICENSE"
# A URL to refer people to when problems occur with this mod
issueTrackerURL="https://github.com/cabaletta/baritone/issues" #optional
@@ -35,6 +35,6 @@ A Minecraft pathfinder bot.
modId="minecraft"
mandatory=true
# This version range declares a minimum of the current minecraft version up to but not including the next major version
versionRange="[1.21.9, 1.21.10]"
versionRange="[1.20,1.20.1]"
ordering="NONE"
side="BOTH"

View File

@@ -1,24 +1,22 @@
org.gradle.jvmargs=-Xmx4G
available_loaders=fabric,neoforge,forge,tweaker
available_loaders=fabric,forge,tweaker
mod_version=1.16.0
mod_version=1.10.3
maven_group=baritone
archives_base_name=baritone
java_version=21
java_version=17
minecraft_version=1.21.10
minecraft_version=1.20.1
forge_version=60.0.0
forge_version=47.0.1
neoforge_version=1-beta
fabric_version=0.17.2
fabric_version=0.14.18
nether_pathfinder_version=1.4.1
// These dependencies are used for common and tweaker
// while mod loaders usually ship their own version
mixin_version=0.8.5
asm_version=9.7
asm_version=9.3

View File

@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -1,130 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
import baritone.gradle.task.CreateDistTask
import baritone.gradle.task.ProguardTask
plugins {
id "com.github.johnrengelman.shadow" version "8.0.0"
}
archivesBaseName = archivesBaseName + "-neoforge"
unimined.minecraft {
neoForge {
loader project.neoforge_version
mixinConfig ["mixins.baritone.json"]
}
minecraftRemapper.config {
// neoforge adds 1 conflict, where 2 interfaces have a method with the same name on yarn/mojmap,
// but the method has different names in the intermediary mappings.
// this is a conflict because they have a class that extends both interfaces.
// this shouldn't be a problem as long as named mappings don't make the name of those 2 methods different.
ignoreConflicts(true)
}
}
//loom {
// forge {
// mixinConfig 'mixins.baritone.json'
// }
//}
configurations {
common
shadowCommon // Don't use shadow from the shadow plugin because we don't want IDEA to index this.
compileClasspath.extendsFrom common
runtimeClasspath.extendsFrom common
}
dependencies {
// because of multiple sourcesets `common project(":")` doesn't work
for (sourceSet in rootProject.sourceSets) {
if (sourceSet == rootProject.sourceSets.test) continue
if (sourceSet == rootProject.sourceSets.schematica_api) continue
common sourceSet.output
shadowCommon sourceSet.output
}
shadowCommon "dev.babbaj:nether-pathfinder:${project.nether_pathfinder_version}"
}
processResources {
inputs.property "version", project.version
filesMatching("META-INF/neoforge.mods.toml") {
expand "version": project.version
}
}
shadowJar {
configurations = [project.configurations.shadowCommon]
archiveClassifier.set "dev-shadow"
}
remapJar {
inputFile.set shadowJar.archiveFile
dependsOn shadowJar
archiveClassifier.set null
}
jar {
archiveClassifier.set "dev"
manifest {
attributes(
'MixinConfigs': 'mixins.baritone.json',
"MixinConnector": "baritone.launch.BaritoneMixinConnector",
'Implementation-Title': 'Baritone',
'Implementation-Version': version,
)
}
}
components.java {
withVariantsFromConfiguration(project.configurations.shadowRuntimeElements) {
skip()
}
}
task proguard(type: ProguardTask) {
proguardVersion "7.4.2"
compType "neoforge"
}
task createDist(type: CreateDistTask, dependsOn: proguard) {
compType "neoforge"
}
build.finalizedBy(createDist)
publishing {
publications {
mavenFabric(MavenPublication) {
artifactId = rootProject.archives_base_name + "-" + project.name
from components.java
}
}
// See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing.
repositories {
// Add repositories to publish to here.
}
}

View File

@@ -1,18 +0,0 @@
#
# This file is part of Baritone.
#
# Baritone is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Baritone is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Baritone. If not, see <https://www.gnu.org/licenses/>.
#
loom.platform=forge

View File

@@ -1,25 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.fml.common.Mod;
@Mod(value = "baritoe", dist = Dist.CLIENT)
public class BaritoneForgeModXD {
}

View File

@@ -1,43 +0,0 @@
# This is an example neoforge.mods.toml file. It contains the data relating to the loading mods.
# There are several mandatory fields (#mandatory), and many more that are optional (#optional).
# The overall format is standard TOML format, v0.5.0.
# Note that there are a couple of TOML lists in this file.
# Find more information on toml format here: https://github.com/toml-lang/toml
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
modLoader="javafml" #mandatory
# A version range to match for said mod loader - for regular FML @Mod it will be the forge version
loaderVersion="[1,)" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions.
license="https://raw.githubusercontent.com/cabaletta/baritone/1.16.2/LICENSE"
# A URL to refer people to when problems occur with this mod
issueTrackerURL="https://github.com/cabaletta/baritone/issues" #optional
# A list of mods - how many allowed here is determined by the individual mod loader
[[mods]] #mandatory
# The modid of the mod
modId="baritoe" #mandatory
# The version number of the mod - there's a few well known ${} variables useable here or just hardcode it
version="${version}" #mandatory
# A display name for the mod
displayName="Baritone" #mandatory
# A URL for the "homepage" for this mod, displayed in the mod UI
displayURL="https://github.com/cabaletta/baritone" #optional
# A file name (in the root of the mod JAR) containing a logo for display
#logoFile="examplemod.png" #optional
# A text field displayed in the mod UI
credits="Hat Gamers" #optional
# A text field displayed in the mod UI
authors="leijurv, Brady" #optional
# The description text for the mod (multi line!) (#mandatory)
description='''
A Minecraft pathfinder bot.
'''
[[dependencies.baritoe]]
modId="minecraft"
type="required"
# This version range declares a minimum of the current minecraft version up to but not including the next major version
versionRange="[1.21.9, 1.21.10]"
ordering="NONE"
side="BOTH"
[[mixins]]
config = "mixins.baritone.json"

View File

@@ -1,6 +0,0 @@
{
"pack": {
"description": "null",
"pack_format": 8
}
}

View File

@@ -41,7 +41,7 @@
# setting names are reflected from field names, so keep field names
-keepclassmembers class baritone.api.Settings {
public <fields>;
public <fields>;
}
# need to keep mixin names
@@ -346,4 +346,4 @@
public int length();
public java.lang.String substring(int);
public java.lang.String substring(int,int);
}
}

View File

@@ -673,6 +673,13 @@ public final class Settings {
*/
public final Setting<Boolean> logAsToast = new Setting<>(false);
/**
* The time of how long the message in the pop-up will display
* <p>
* If below 1000L (1sec), it's better to disable this
*/
public final Setting<Long> toastTimer = new Setting<>(5000L);
/**
* Print all the debug messages to chat
*/

View File

@@ -30,7 +30,7 @@ public enum BlockById implements IDatatypeFor<Block> {
@Override
public Block get(IDatatypeContext ctx) throws CommandException {
ResourceLocation id = ResourceLocation.parse(ctx.getConsumer().getString());
ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString());
Block block;
if ((block = BuiltInRegistries.BLOCK.getOptional(id).orElse(null)) == null) {
throw new IllegalArgumentException("no block found by that id");

View File

@@ -30,7 +30,7 @@ public enum EntityClassById implements IDatatypeFor<EntityType> {
@Override
public EntityType get(IDatatypeContext ctx) throws CommandException {
ResourceLocation id = ResourceLocation.parse(ctx.getConsumer().getString());
ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString());
EntityType entity;
if ((entity = BuiltInRegistries.ENTITY_TYPE.getOptional(id).orElse(null)) == null) {
throw new IllegalArgumentException("no entity found by that id");

View File

@@ -77,7 +77,7 @@ public enum ForBlockOptionalMeta implements IDatatypeFor<BlockOptionalMeta> {
properties = parts[1];
}
Block block = BuiltInRegistries.BLOCK.getOptional(ResourceLocation.parse(blockId)).orElse(null);
Block block = BuiltInRegistries.BLOCK.getOptional(new ResourceLocation(blockId)).orElse(null);
if (block == null) {
// This block doesn't exist so there's no properties to complete.
return Stream.empty();

View File

@@ -30,7 +30,7 @@ public enum ItemById implements IDatatypeFor<Item> {
@Override
public Item get(IDatatypeContext ctx) throws CommandException {
ResourceLocation id = ResourceLocation.parse(ctx.getConsumer().getString());
ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString());
Item item;
if ((item = BuiltInRegistries.ITEM.getOptional(id).orElse(null)) == null) {
throw new IllegalArgumentException("No item found by that id");

View File

@@ -21,16 +21,17 @@ import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.exception.CommandException;
import baritone.api.command.exception.CommandInvalidTypeException;
import baritone.api.utils.Helper;
import java.awt.*;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.MutableComponent;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
public class Paginator<E> implements Helper {
public final List<E> entries;
@@ -77,10 +78,12 @@ public class Paginator<E> implements Helper {
MutableComponent prevPageComponent = Component.literal("<<");
if (hasPrevPage) {
prevPageComponent.setStyle(prevPageComponent.getStyle()
.withClickEvent(new ClickEvent.RunCommand(
.withClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
String.format("%s %d", commandPrefix, page - 1)
))
.withHoverEvent(new HoverEvent.ShowText(
.withHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT,
Component.literal("Click to view previous page")
)));
} else {
@@ -89,8 +92,9 @@ public class Paginator<E> implements Helper {
MutableComponent nextPageComponent = Component.literal(">>");
if (hasNextPage) {
nextPageComponent.setStyle(nextPageComponent.getStyle()
.withClickEvent(new ClickEvent.RunCommand(String.format("%s %d", commandPrefix, page + 1)))
.withHoverEvent(new HoverEvent.ShowText(
.withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, String.format("%s %d", commandPrefix, page + 1)))
.withHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT,
Component.literal("Click to view next page")
)));
} else {

View File

@@ -157,7 +157,7 @@ public final class BetterBlockPos extends BlockPos {
@Override
public BetterBlockPos relative(Direction dir) {
Vec3i vec = dir.getUnitVec3i();
Vec3i vec = dir.getNormal();
return new BetterBlockPos(x + vec.getX(), y + vec.getY(), z + vec.getZ());
}
@@ -166,7 +166,7 @@ public final class BetterBlockPos extends BlockPos {
if (dist == 0) {
return this;
}
Vec3i vec = dir.getUnitVec3i();
Vec3i vec = dir.getNormal();
return new BetterBlockPos(x + vec.getX() * dist, y + vec.getY() * dist, z + vec.getZ() * dist);
}

View File

@@ -18,31 +18,26 @@
package baritone.api.utils;
import baritone.api.utils.accessor.IItemStack;
import baritone.api.utils.accessor.ILootTable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.netty.util.concurrent.ThreadPerTaskExecutor;
import net.minecraft.client.Minecraft;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.LayeredRegistryAccess;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.core.BlockPos;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.RegistryLayer;
import net.minecraft.server.ReloadableServerRegistries;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.progress.ChunkProgressListener;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.VanillaPackResources;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.CloseableResourceManager;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.tags.TagLoader;
import net.minecraft.server.packs.resources.ReloadableResourceManager;
import net.minecraft.util.Unit;
import net.minecraft.world.RandomSequences;
import net.minecraft.world.flag.FeatureFlagSet;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.CustomSpawner;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
@@ -51,9 +46,10 @@ import net.minecraft.world.level.block.state.properties.Property;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.ServerLevelData;
import net.minecraft.world.level.storage.loot.BuiltInLootTables;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootDataManager;
import net.minecraft.world.level.storage.loot.LootParams;
import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import net.minecraft.world.phys.Vec3;
@@ -79,6 +75,7 @@ public final class BlockOptionalMeta {
private final Set<BlockState> blockstates;
private final ImmutableSet<Integer> stateHashes;
private final ImmutableSet<Integer> stackHashes;
private static LootDataManager lootTables;
private static Map<Block, List<Item>> drops = new HashMap<>();
public BlockOptionalMeta(@Nonnull Block block) {
@@ -221,21 +218,43 @@ public final class BlockOptionalMeta {
return null;
}
public static LootDataManager getManager() {
if (lootTables == null) {
MultiPackResourceManager resources = new MultiPackResourceManager(PackType.SERVER_DATA, List.of(getVanillaServerPack()));
ReloadableResourceManager resourceManager = new ReloadableResourceManager(PackType.SERVER_DATA);
lootTables = new LootDataManager();
resourceManager.registerReloadListener(lootTables);
try {
resourceManager.createReload(new ThreadPerTaskExecutor(Thread::new), new ThreadPerTaskExecutor(Thread::new), CompletableFuture.completedFuture(Unit.INSTANCE), resources.listPacks().toList()).done().get();
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
return lootTables;
}
private static synchronized List<Item> drops(Block b) {
return drops.computeIfAbsent(b, block -> {
Optional<ResourceKey<LootTable>> optionalLootTableKey = block.getLootTable();
if (optionalLootTableKey.isEmpty()) {
ResourceLocation lootTableLocation = block.getLootTable();
if (lootTableLocation == BuiltInLootTables.EMPTY) {
return Collections.emptyList();
} else {
List<Item> items = new ArrayList<>();
try {
ServerLevel lv2 = ServerLevelStub.fastCreate();
LootParams.Builder lv5 = new LootParams.Builder(lv2)
.withParameter(LootContextParams.ORIGIN, Vec3.ZERO)
.withParameter(LootContextParams.BLOCK_STATE, b.defaultBlockState())
.withParameter(LootContextParams.TOOL, new ItemStack(Items.NETHERITE_PICKAXE, 1));
getDrops(block, lv5).stream().map(ItemStack::getItem).forEach(items::add);
getManager().getLootTable(lootTableLocation).getRandomItemsRaw(
new LootContext.Builder(
new LootParams.Builder(ServerLevelStub.fastCreate())
.withParameter(LootContextParams.ORIGIN, Vec3.atLowerCornerOf(BlockPos.ZERO))
.withParameter(LootContextParams.TOOL, ItemStack.EMPTY)
.withOptionalParameter(LootContextParams.BLOCK_ENTITY, null)
.withParameter(LootContextParams.BLOCK_STATE, block.defaultBlockState())
.create(LootContextParamSets.BLOCK)
).withOptionalRandomSeed(1L)
.create(null),
stack -> items.add(stack.getItem())
);
} catch (Exception e) {
e.printStackTrace();
}
@@ -244,25 +263,12 @@ public final class BlockOptionalMeta {
});
}
private static List<ItemStack> getDrops(Block state, LootParams.Builder params) {
Optional<ResourceKey<LootTable>> lv = state.getLootTable();
if (lv.isEmpty()) {
return Collections.emptyList();
} else {
LootParams lv2 = params.withParameter(LootContextParams.BLOCK_STATE, state.defaultBlockState()).create(LootContextParamSets.BLOCK);
ServerLevelStub lv3 = (ServerLevelStub) lv2.getLevel();
LootTable lv4 = lv3.holder().getLootTable(lv.get());
return((ILootTable) lv4).invokeGetRandomItems(new LootContext.Builder(lv2).withOptionalRandomSeed(1).create(null));
}
}
public static class ServerLevelStub extends ServerLevel {
private static class ServerLevelStub extends ServerLevel {
private static Minecraft client = Minecraft.getInstance();
private static Unsafe unsafe = getUnsafe();
private static CompletableFuture<RegistryAccess> registryAccess = load();
public ServerLevelStub(MinecraftServer $$0, Executor $$1, LevelStorageSource.LevelStorageAccess $$2, ServerLevelData $$3, ResourceKey<Level> $$4, LevelStem $$5, boolean $$6, long $$7, List<CustomSpawner> $$8, boolean $$9, @Nullable RandomSequences $$10) {
super($$0, $$1, $$2, $$3, $$4, $$5, $$6, $$7, $$8, $$9, $$10);
public ServerLevelStub(MinecraftServer $$0, Executor $$1, LevelStorageSource.LevelStorageAccess $$2, ServerLevelData $$3, ResourceKey<Level> $$4, LevelStem $$5, ChunkProgressListener $$6, boolean $$7, long $$8, List<CustomSpawner> $$9, boolean $$10, @Nullable RandomSequences $$11) {
super($$0, $$1, $$2, $$3, $$4, $$5, $$6, $$7, $$8, $$9, $$10, $$11);
}
@Override
@@ -279,15 +285,6 @@ public final class BlockOptionalMeta {
}
}
@Override
public RegistryAccess registryAccess() {
return registryAccess.join();
}
public ReloadableServerRegistries.Holder holder() {
return new ReloadableServerRegistries.Holder(registryAccess().freeze());
}
public static Unsafe getUnsafe() {
try {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
@@ -298,34 +295,5 @@ public final class BlockOptionalMeta {
}
}
public static CompletableFuture<RegistryAccess> load() {
// Simplified from {@link net.minecraft.server.WorldLoader#load()}
CloseableResourceManager closeableResourceManager = new MultiPackResourceManager(
PackType.SERVER_DATA,
List.of(ServerPacksSource.createVanillaPackSource())
);
LayeredRegistryAccess<RegistryLayer> baseLayeredRegistry = RegistryLayer.createRegistryAccess();
List<Registry.PendingTags<?>> pendingTags = TagLoader.loadTagsForExistingRegistries(
closeableResourceManager, baseLayeredRegistry.getLayer(RegistryLayer.STATIC)
);
List<HolderLookup.RegistryLookup<?>> worldGenRegistryLookupList = TagLoader.buildUpdatedLookups(
baseLayeredRegistry.getAccessForLoading(RegistryLayer.WORLDGEN),
pendingTags
);
LayeredRegistryAccess<RegistryLayer> layeredRegistryAccess = baseLayeredRegistry.replaceFrom(
RegistryLayer.WORLDGEN,
RegistryDataLoader.load(
closeableResourceManager,
worldGenRegistryLookupList,
RegistryDataLoader.WORLDGEN_REGISTRIES
)
);
return ReloadableServerRegistries.reload(
layeredRegistryAccess,
pendingTags,
closeableResourceManager,
Minecraft.getInstance()
).thenApply(r -> r.layers().compositeAccess());
}
}
}

View File

@@ -21,7 +21,6 @@ import baritone.api.BaritoneAPI;
import baritone.api.Settings;
import net.minecraft.client.Minecraft;
import net.minecraft.core.Direction;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.core.Vec3i;
import net.minecraft.core.registries.BuiltInRegistries;
@@ -246,8 +245,8 @@ public class SettingsUtil {
BlockUtils::blockToString
),
ITEM(
Item.class,
str -> BuiltInRegistries.ITEM.get(ResourceLocation.parse(str.trim())).map(Holder.Reference::value).orElse(null),
Item.class,
str -> BuiltInRegistries.ITEM.get(new ResourceLocation(str.trim())), // TODO this now returns AIR on failure instead of null, is that an issue?
item -> BuiltInRegistries.ITEM.getKey(item).toString()
),
LIST() {

View File

@@ -1,28 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.utils.accessor;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.storage.loot.LootContext;
public interface ILootTable {
ObjectArrayList<ItemStack> invokeGetRandomItems(LootContext context);
}

View File

@@ -17,13 +17,65 @@
package baritone.api.utils.gui;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.toasts.SystemToast;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.toasts.Toast;
import net.minecraft.client.gui.components.toasts.ToastComponent;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
public class BaritoneToast implements Toast {
private String title;
private String subtitle;
private long firstDrawTime;
private boolean newDisplay;
private long totalShowTime;
public BaritoneToast(Component titleComponent, Component subtitleComponent, long totalShowTime) {
this.title = titleComponent.getString();
this.subtitle = subtitleComponent == null ? null : subtitleComponent.getString();
this.totalShowTime = totalShowTime;
}
public Visibility render(GuiGraphics gui, ToastComponent toastGui, long delta) {
if (this.newDisplay) {
this.firstDrawTime = delta;
this.newDisplay = false;
}
//TODO: check
gui.blit(new ResourceLocation("textures/gui/toasts.png"), 0, 0, 0, 32, 160, 32);
if (this.subtitle == null) {
gui.drawString(toastGui.getMinecraft().font, this.title, 18, 12, -11534256);
} else {
gui.drawString(toastGui.getMinecraft().font, this.title, 18, 7, -11534256);
gui.drawString(toastGui.getMinecraft().font, this.subtitle, 18, 18, -16777216);
}
return delta - this.firstDrawTime < totalShowTime ? Visibility.SHOW : Visibility.HIDE;
}
public void setDisplayedText(Component titleComponent, Component subtitleComponent) {
this.title = titleComponent.getString();
this.subtitle = subtitleComponent == null ? null : subtitleComponent.getString();
this.newDisplay = true;
}
public static void addOrUpdate(ToastComponent toast, Component title, Component subtitle, long totalShowTime) {
BaritoneToast baritonetoast = toast.getToast(BaritoneToast.class, new Object());
if (baritonetoast == null) {
toast.addToast(new BaritoneToast(title, subtitle, totalShowTime));
} else {
baritonetoast.setDisplayedText(title, subtitle);
}
}
public class BaritoneToast {
private static final SystemToast.SystemToastId BARITONE_TOAST_ID = new SystemToast.SystemToastId(5000L);
public static void addOrUpdate(Component title, Component subtitle) {
SystemToast.addOrUpdate(Minecraft.getInstance().getToastManager(), BARITONE_TOAST_ID, title, subtitle);
addOrUpdate(Minecraft.getInstance().getToasts(), title, subtitle, baritone.api.BaritoneAPI.getSettings().toastTimer.value);
}
}

View File

@@ -27,16 +27,15 @@ import baritone.api.event.events.type.EventState;
import baritone.api.utils.Pair;
import baritone.cache.CachedChunk;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientCommonPacketListenerImpl;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.client.multiplayer.CommonListenerCookie;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.core.BlockPos;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.game.*;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.block.state.BlockState;
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;
@@ -49,7 +48,7 @@ import java.util.List;
* @since 8/3/2018
*/
@Mixin(ClientPacketListener.class)
public abstract class MixinClientPlayNetHandler extends ClientCommonPacketListenerImpl {
public class MixinClientPlayNetHandler {
// unused lol
/*@Inject(
@@ -75,9 +74,9 @@ public abstract class MixinClientPlayNetHandler extends ClientCommonPacketListen
}
}*/
protected MixinClientPlayNetHandler(final Minecraft arg, final Connection arg2, final CommonListenerCookie arg3) {
super(arg, arg2, arg3);
}
@Shadow
@Final
private Minecraft minecraft;
@Inject(
method = "sendChat(Ljava/lang/String;)V",
@@ -125,7 +124,7 @@ public abstract class MixinClientPlayNetHandler extends ClientCommonPacketListen
LocalPlayer player = ibaritone.getPlayerContext().player();
if (player != null && player.connection == (ClientPacketListener) (Object) this) {
ibaritone.getGameEventHandler().onChunkEvent(
new ChunkEvent(EventState.PRE, ChunkEvent.Type.UNLOAD, packet.pos().x, packet.pos().z)
new ChunkEvent(EventState.PRE, ChunkEvent.Type.UNLOAD, packet.getX(), packet.getZ())
);
}
}
@@ -140,7 +139,7 @@ public abstract class MixinClientPlayNetHandler extends ClientCommonPacketListen
LocalPlayer player = ibaritone.getPlayerContext().player();
if (player != null && player.connection == (ClientPacketListener) (Object) this) {
ibaritone.getGameEventHandler().onChunkEvent(
new ChunkEvent(EventState.POST, ChunkEvent.Type.UNLOAD, packet.pos().x, packet.pos().z)
new ChunkEvent(EventState.POST, ChunkEvent.Type.UNLOAD, packet.getX(), packet.getZ())
);
}
}

View File

@@ -23,41 +23,21 @@ import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.SprintStateEvent;
import baritone.api.event.events.type.EventState;
import baritone.behavior.LookBehavior;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.world.entity.player.Abilities;
import net.minecraft.world.entity.player.Input;
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.Group;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
/**
* @author Brady
* @since 8/1/2018
*/
@Mixin(LocalPlayer.class)
public class MixinClientPlayerEntity {
@Unique
private static final MethodHandle MAY_FLY = baritone$resolveMayFly();
@Unique
private static MethodHandle baritone$resolveMayFly() {
try {
var lookup = MethodHandles.publicLookup();
return lookup.findVirtual(LocalPlayer.class, "mayFly", MethodType.methodType(boolean.class));
} catch (NoSuchMethodException e) {
return null;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Inject(
method = "tick",
@@ -81,7 +61,6 @@ public class MixinClientPlayerEntity {
target = "net/minecraft/world/entity/player/Abilities.mayfly:Z"
)
)
@Group(name = "mayFly", min = 1, max = 1)
private boolean isAllowFlying(Abilities capabilities) {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((LocalPlayer) (Object) this);
if (baritone == null) {
@@ -90,33 +69,17 @@ public class MixinClientPlayerEntity {
return !baritone.getPathingBehavior().isPathing() && capabilities.mayfly;
}
@Redirect(
method = "aiStep",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/client/player/LocalPlayer;mayFly()Z"
)
)
@Group(name = "mayFly", min = 1, max = 1)
private boolean onMayFlyNeoforge(LocalPlayer instance) throws Throwable {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((LocalPlayer) (Object) this);
if (baritone == null) {
return (boolean) MAY_FLY.invokeExact(instance);
}
return !baritone.getPathingBehavior().isPathing() && (boolean) MAY_FLY.invokeExact(instance);
}
@Redirect(
method = "aiStep",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/world/entity/player/Input;sprint()Z"
target = "net/minecraft/client/KeyMapping.isDown()Z"
)
)
private boolean redirectSprintInput(final Input instance) {
private boolean isKeyDown(KeyMapping keyBinding) {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((LocalPlayer) (Object) this);
if (baritone == null) {
return instance.sprint();
return keyBinding.isDown();
}
SprintStateEvent event = new SprintStateEvent();
baritone.getGameEventHandler().onPlayerSprintState(event);
@@ -127,7 +90,7 @@ public class MixinClientPlayerEntity {
// hitting control shouldn't make all bots sprint
return false;
}
return instance.sprint();
return keyBinding.isDown();
}
@Inject(

View File

@@ -32,7 +32,6 @@ import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.Optional;
@@ -82,13 +81,13 @@ public abstract class MixinLivingEntity extends Entity {
}
@Inject(
method = "updateFallFlyingMovement",
method = "travel",
at = @At(
value = "INVOKE",
target = "net/minecraft/world/entity/LivingEntity.getLookAngle()Lnet/minecraft/world/phys/Vec3;"
)
)
private void onPreElytraMove(Vec3 direction, final CallbackInfoReturnable<Vec3> cir) {
private void onPreElytraMove(Vec3 direction, CallbackInfo ci) {
this.getBaritone().ifPresent(baritone -> {
this.elytraRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.MOTION_UPDATE, this.getYRot(), this.getXRot());
baritone.getGameEventHandler().onPlayerRotationMove(this.elytraRotationEvent);
@@ -98,14 +97,14 @@ public abstract class MixinLivingEntity extends Entity {
}
@Inject(
method = "travelFallFlying",
method = "travel",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/world/entity/LivingEntity;move(Lnet/minecraft/world/entity/MoverType;Lnet/minecraft/world/phys/Vec3;)V",
target = "net/minecraft/world/entity/LivingEntity.move(Lnet/minecraft/world/entity/MoverType;Lnet/minecraft/world/phys/Vec3;)V",
shift = At.Shift.AFTER
)
)
private void onPostElytraMove(final CallbackInfo ci) {
private void onPostElytraMove(Vec3 direction, CallbackInfo ci) {
if (this.elytraRotationEvent != null) {
this.setYRot(this.elytraRotationEvent.getOriginal().getYaw());
this.setXRot(this.elytraRotationEvent.getOriginal().getPitch());

View File

@@ -19,28 +19,41 @@ package baritone.launch.mixins;
import baritone.api.utils.BlockOptionalMeta;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.ReloadableServerRegistries;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootDataManager;
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.Redirect;
@Mixin(LootContext.Builder.class)
public abstract class MixinLootContextBuilder {
public class MixinLootContext {
@Shadow public abstract ServerLevel getLevel();
@Redirect(method = "create", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;reloadableRegistries()Lnet/minecraft/server/ReloadableServerRegistries$Holder;"))
private ReloadableServerRegistries.Holder create(MinecraftServer instance) {
if (instance != null) {
return instance.reloadableRegistries();
@Redirect(
method = "create",
at = @At(
value = "INVOKE",
target = "net/minecraft/server/level/ServerLevel.getServer()Lnet/minecraft/server/MinecraftServer;"
)
)
private MinecraftServer getServer(ServerLevel world) {
if (world == null) {
return null;
}
if (getLevel() instanceof BlockOptionalMeta.ServerLevelStub sls) {
return sls.holder();
}
return null;
return world.getServer();
}
@Redirect(
method = "create",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/server/MinecraftServer;getLootData()Lnet/minecraft/world/level/storage/loot/LootDataManager;"
)
)
private LootDataManager getLootTableManager(MinecraftServer server) {
if (server == null) {
return BlockOptionalMeta.getManager();
}
return server.getLootData();
}
}

View File

@@ -1,34 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.api.utils.accessor.ILootTable;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootTable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
@Mixin(LootTable.class)
public abstract class MixinLootTable implements ILootTable {
@Invoker
public abstract ObjectArrayList<ItemStack> invokeGetRandomItems(LootContext context);
}

View File

@@ -130,7 +130,7 @@ public class MixinMinecraft {
method = "setLevel",
at = @At("HEAD")
)
private void preLoadWorld(final ClientLevel world, final CallbackInfo ci) {
private void preLoadWorld(ClientLevel world, CallbackInfo ci) {
// If we're unloading the world but one doesn't exist, ignore it
if (this.level == null && world == null) {
return;
@@ -150,7 +150,7 @@ public class MixinMinecraft {
method = "setLevel",
at = @At("RETURN")
)
private void postLoadWorld(final ClientLevel world, final CallbackInfo ci) {
private void postLoadWorld(ClientLevel world, CallbackInfo ci) {
// still fire event for both null, as that means we've just finished exiting a world
// mc.world changing is only the primary baritone
@@ -171,8 +171,9 @@ public class MixinMinecraft {
),
slice = @Slice(
from = @At(
value = "INVOKE",
target = "Lnet/minecraft/client/gui/components/DebugScreenOverlay;showDebugScreen()Z"
value = "FIELD",
opcode = Opcodes.GETFIELD,
target = "Lnet/minecraft/client/Options;renderDebug:Z"
),
to = @At(
value = "CONSTANT",

View File

@@ -22,9 +22,11 @@ import baritone.api.IBaritone;
import baritone.api.event.events.PacketEvent;
import baritone.api.event.events.type.EventState;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import net.minecraft.network.Connection;
import net.minecraft.network.PacketSendListener;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.PacketFlow;
import org.spongepowered.asm.mixin.Final;
@@ -52,7 +54,7 @@ public class MixinNetworkManager {
method = "sendPacket",
at = @At("HEAD")
)
private void preDispatchPacket(final Packet<?> packet, final ChannelFutureListener channelFutureListener, final boolean flush, final CallbackInfo ci) {
private void preDispatchPacket(Packet<?> packet, PacketSendListener packetSendListener, CallbackInfo ci) {
if (this.receiving != PacketFlow.CLIENTBOUND) {
return;
}
@@ -68,7 +70,7 @@ public class MixinNetworkManager {
method = "sendPacket",
at = @At("RETURN")
)
private void postDispatchPacket(Packet<?> packet, ChannelFutureListener packetSendListener, boolean flush, CallbackInfo ci) {
private void postDispatchPacket(Packet<?> packet, PacketSendListener packetSendListener, CallbackInfo ci) {
if (this.receiving != PacketFlow.CLIENTBOUND) {
return;
}

View File

@@ -1,35 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.utils.accessor.IRenderPipelines;
import com.mojang.blaze3d.pipeline.RenderPipeline;
import net.minecraft.client.renderer.RenderPipelines;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(RenderPipelines.class)
public class MixinRenderPipelines implements IRenderPipelines {
@Final @Shadow
private static RenderPipeline.Snippet LINES_SNIPPET;
public RenderPipeline.Snippet getLinesSnippet() {
return LINES_SNIPPET;
}
}

View File

@@ -21,33 +21,43 @@ import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.event.events.ChatEvent;
import baritone.utils.accessor.IGuiScreen;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Style;
import org.spongepowered.asm.mixin.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 java.net.URI;
import static baritone.api.command.IBaritoneChatControl.FORCE_COMMAND_PREFIX;
@Mixin(Screen.class)
public abstract class MixinScreen implements IGuiScreen {
@Override
@Invoker("openLink")
public abstract void openLinkInvoker(URI url);
//TODO: switch to enum extention with mixin 9.0 or whenever Mumfrey gets around to it
@Inject(method = "handleClickEvent", at = @At(value = "HEAD"), cancellable = true)
public void handleCustomClickEvent(final Minecraft minecraft, final ClickEvent clickEvent, final CallbackInfo ci) {
@Inject(at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;error(Ljava/lang/String;Ljava/lang/Object;)V", remap = false, ordinal = 1), method = "handleComponentClicked", cancellable = true)
public void handleCustomClickEvent(Style style, CallbackInfoReturnable<Boolean> cir) {
ClickEvent clickEvent = style.getClickEvent();
if (clickEvent == null) {
return;
}
if (!(clickEvent instanceof ClickEvent.RunCommand(String command))) return;
if (!command.startsWith(FORCE_COMMAND_PREFIX)) {
String command = clickEvent.getValue();
if (command == null || !command.startsWith(FORCE_COMMAND_PREFIX)) {
return;
}
IBaritone baritone = BaritoneAPI.getProvider().getPrimaryBaritone();
if (baritone != null) {
baritone.getGameEventHandler().onSendChatMessage(new ChatEvent(command));
}
ci.cancel();
cir.setReturnValue(true);
cir.cancel();
}
}

View File

@@ -20,18 +20,17 @@ package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.event.events.RenderEvent;
import com.mojang.blaze3d.buffers.GpuBufferSlice;
import com.mojang.blaze3d.resource.GraphicsResourceAllocator;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Camera;
import net.minecraft.client.DeltaTracker;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.LevelRenderer;
import net.minecraft.client.renderer.LightTexture;
import org.joml.Matrix4f;
import org.joml.Vector4f;
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 org.spongepowered.asm.mixin.injection.callback.LocalCapture;
/**
* @author Brady
@@ -42,13 +41,12 @@ public class MixinWorldRenderer {
@Inject(
method = "renderLevel",
at = @At("RETURN")
at = @At("RETURN"),
locals = LocalCapture.CAPTURE_FAILSOFT
)
private void onStartHand(final GraphicsResourceAllocator graphicsResourceAllocator, final DeltaTracker deltaTracker, final boolean bl, final Camera camera, final Matrix4f matrix4f, final Matrix4f matrix4f2, final Matrix4f matrix4f3, final GpuBufferSlice gpuBufferSlice, final Vector4f vector4f, final boolean bl2, final CallbackInfo ci) {
private void onStartHand(PoseStack matrixStackIn, float partialTicks, long finishTimeNano, boolean drawBlockOutline, Camera activeRenderInfoIn, GameRenderer gameRendererIn, LightTexture lightmapIn, Matrix4f projectionIn, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
PoseStack poseStack = new PoseStack();
poseStack.mulPose(matrix4f);
ibaritone.getGameEventHandler().onRenderPass(new RenderEvent(deltaTracker.getGameTimeDeltaPartialTick(false), poseStack, matrix4f2));
ibaritone.getGameEventHandler().onRenderPass(new RenderEvent(partialTicks, matrixStackIn, projectionIn));
}
}
}
}

View File

@@ -18,17 +18,13 @@
"MixinFireworkRocketEntity",
"MixinItemStack",
"MixinLivingEntity",
"MixinLootContextBuilder",
"MixinLootTable",
"MixinLootContext",
"MixinMinecraft",
"MixinNetworkManager",
"MixinPalettedContainer",
"MixinPalettedContainer$Data",
"MixinPlayerController",
"MixinRenderPipelines",
"MixinScreen",
"MixinWorldRenderer"
],
"mixins": [
]
}

View File

@@ -24,13 +24,13 @@ import baritone.utils.ToolSet;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.core.Direction;
import net.minecraft.core.NonNullList;
import net.minecraft.core.component.DataComponents;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.inventory.ClickType;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.DiggerItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.PickaxeItem;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.block.Block;
@@ -38,7 +38,6 @@ import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.Vec3;
import java.util.ArrayList;
import java.util.OptionalInt;
import java.util.Random;
@@ -69,7 +68,7 @@ public final class InventoryBehavior extends Behavior implements Helper {
if (firstValidThrowaway() >= 9) { // aka there are none on the hotbar, but there are some in main inventory
requestSwapWithHotBar(firstValidThrowaway(), 8);
}
int pick = bestToolAgainst(Blocks.STONE);
int pick = bestToolAgainst(Blocks.STONE, PickaxeItem.class);
if (pick >= 9) {
requestSwapWithHotBar(pick, 0);
}
@@ -93,7 +92,7 @@ public final class InventoryBehavior extends Behavior implements Helper {
// we're using 0 and 8 for pickaxe and throwaway
ArrayList<Integer> candidates = new ArrayList<>();
for (int i = 1; i < 8; i++) {
if (ctx.player().getInventory().getNonEquipmentItems().get(i).isEmpty() && !disallowedHotbar.test(i)) {
if (ctx.player().getInventory().items.get(i).isEmpty() && !disallowedHotbar.test(i)) {
candidates.add(i);
}
}
@@ -127,7 +126,7 @@ public final class InventoryBehavior extends Behavior implements Helper {
}
private int firstValidThrowaway() { // TODO offhand idk
NonNullList<ItemStack> invy = ctx.player().getInventory().getNonEquipmentItems();
NonNullList<ItemStack> invy = ctx.player().getInventory().items;
for (int i = 0; i < invy.size(); i++) {
if (Baritone.settings().acceptableThrowawayItems.value.contains(invy.get(i).getItem())) {
return i;
@@ -136,8 +135,8 @@ public final class InventoryBehavior extends Behavior implements Helper {
return -1;
}
private int bestToolAgainst(Block against) {
NonNullList<ItemStack> invy = ctx.player().getInventory().getNonEquipmentItems();
private int bestToolAgainst(Block against, Class<? extends DiggerItem> cla$$) {
NonNullList<ItemStack> invy = ctx.player().getInventory().items;
int bestInd = -1;
double bestSpeed = -1;
for (int i = 0; i < invy.size(); i++) {
@@ -148,7 +147,7 @@ public final class InventoryBehavior extends Behavior implements Helper {
if (Baritone.settings().itemSaver.value && (stack.getDamageValue() + Baritone.settings().itemSaverThreshold.value) >= stack.getMaxDamage() && stack.getMaxDamage() > 1) {
continue;
}
if (stack.getItem().components().has(DataComponents.TOOL)) {
if (cla$$.isInstance(stack.getItem())) {
double speed = ToolSet.calculateSpeedVsBlock(stack, against.defaultBlockState()); // takes into account enchants
if (speed > bestSpeed) {
bestSpeed = speed;
@@ -190,7 +189,7 @@ public final class InventoryBehavior extends Behavior implements Helper {
public boolean throwaway(boolean select, Predicate<? super ItemStack> desired, boolean allowInventory) {
LocalPlayer p = ctx.player();
NonNullList<ItemStack> inv = p.getInventory().getNonEquipmentItems();
NonNullList<ItemStack> inv = p.getInventory().items;
for (int i = 0; i < 9; i++) {
ItemStack item = inv.get(i);
// this usage of settings() is okay because it's only called once during pathing
@@ -200,12 +199,12 @@ public final class InventoryBehavior extends Behavior implements Helper {
// acceptableThrowawayItems to the CalculationContext
if (desired.test(item)) {
if (select) {
p.getInventory().setSelectedSlot(i);
p.getInventory().selected = i;
}
return true;
}
}
if (desired.test(p.getItemBySlot(EquipmentSlot.OFFHAND))) {
if (desired.test(p.getInventory().offhand.get(0))) {
// main hand takes precedence over off hand
// that means that if we have block A selected in main hand and block B in off hand, right clicking places block B
// we've already checked above ^ and the main hand can't possible have an acceptablethrowawayitem
@@ -213,9 +212,9 @@ public final class InventoryBehavior extends Behavior implements Helper {
// so not a shovel, not a hoe, not a block, etc
for (int i = 0; i < 9; i++) {
ItemStack item = inv.get(i);
if (item.isEmpty() || item.getItem().components().has(DataComponents.TOOL)) {
if (item.isEmpty() || item.getItem() instanceof PickaxeItem) {
if (select) {
p.getInventory().setSelectedSlot(i);
p.getInventory().selected = i;
}
return true;
}
@@ -227,7 +226,7 @@ public final class InventoryBehavior extends Behavior implements Helper {
if (desired.test(inv.get(i))) {
if (select) {
requestSwapWithHotBar(i, 7);
p.getInventory().setSelectedSlot(7);
p.getInventory().selected = 7;
}
return true;
}

View File

@@ -33,18 +33,16 @@ import baritone.pathing.calc.AbstractNodeCostSearch;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.MovementHelper;
import baritone.pathing.path.PathExecutor;
import baritone.process.ElytraProcess;
import baritone.utils.PathRenderer;
import baritone.utils.PathingCommandContext;
import baritone.utils.pathing.Favoring;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.LinkedBlockingQueue;
import net.minecraft.core.BlockPos;
public final class PathingBehavior extends Behavior implements IPathingBehavior, Helper {
@@ -160,9 +158,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
queuePathEvent(PathEvent.AT_GOAL);
next = null;
if (Baritone.settings().disconnectOnArrival.value) {
if (ctx.world() instanceof ClientLevel clientLevel) {
clientLevel.disconnect(Component.literal("[Baritone] Arrived at goal!"));
}
ctx.world().disconnect();
}
return;
}

View File

@@ -73,10 +73,12 @@ public class WaypointBehavior extends Behavior {
MutableComponent component = Component.literal("Death position saved.");
component.setStyle(component.getStyle()
.withColor(ChatFormatting.WHITE)
.withHoverEvent(new HoverEvent.ShowText(
.withHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT,
Component.literal("Click to goto death")
))
.withClickEvent(new ClickEvent.RunCommand(
.withClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
String.format(
"%s%s goto %s @ %d",
FORCE_COMMAND_PREFIX,

View File

@@ -84,7 +84,7 @@ public final class ChunkPacker {
Block block = state.getBlock();
if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(block)) {
String name = BlockUtils.blockToString(block);
specialBlocks.computeIfAbsent(name, b -> new ArrayList<>()).add(new BlockPos(x, y+chunk.getMinY(), z));
specialBlocks.computeIfAbsent(name, b -> new ArrayList<>()).add(new BlockPos(x, y+chunk.getMinBuildHeight(), z));
}
}
}

View File

@@ -26,12 +26,19 @@ import baritone.api.utils.IPlayerContext;
import baritone.utils.accessor.IPalettedContainer;
import io.netty.buffer.Unpooled;
import net.minecraft.core.BlockPos;
import net.minecraft.core.IdMapper;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.util.BitStorage;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.*;
import net.minecraft.world.level.chunk.GlobalPalette;
import net.minecraft.world.level.chunk.ChunkSource;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.world.level.chunk.Palette;
import net.minecraft.world.level.chunk.PalettedContainer;
import net.minecraft.world.level.chunk.SingleValuePalette;
import java.util.ArrayList;
import java.util.List;
@@ -149,7 +156,7 @@ public enum FasterWorldScanner implements IWorldScanner {
long chunkX = (long) pos.x << 4;
long chunkZ = (long) pos.z << 4;
int playerSectionY = (ctx.playerFeet().y - ctx.world().getMinY()) >> 4;
int playerSectionY = (ctx.playerFeet().y - ctx.world().getMinBuildHeight()) >> 4;
return collectChunkSections(lookup, chunkProvider.getChunk(pos.x, pos.z, false), chunkX, chunkZ, playerSectionY).stream();
}
@@ -158,7 +165,7 @@ public enum FasterWorldScanner implements IWorldScanner {
private List<BlockPos> collectChunkSections(BlockOptionalMetaLookup lookup, LevelChunk chunk, long chunkX, long chunkZ, int playerSection) {
// iterate over sections relative to player
List<BlockPos> blocks = new ArrayList<>();
int chunkY = chunk.getMinY();
int chunkY = chunk.getMinBuildHeight();
LevelChunkSection[] sections = chunk.getSections();
int l = sections.length;
int i = playerSection - 1;
@@ -282,7 +289,7 @@ public enum FasterWorldScanner implements IWorldScanner {
return PALETTE_REGISTRY_SENTINEL;
} else {
FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer());
palette.write(buf, Block.BLOCK_STATE_REGISTRY);
palette.write(buf);
int size = buf.readVarInt();
BlockState[] states = new BlockState[size];
for (int i = 0; i < size; i++) {

View File

@@ -140,7 +140,7 @@ public class WorldProvider implements IWorldProvider {
String folderName;
final ServerData serverData = ctx.minecraft().getCurrentServer();
if (serverData != null) {
folderName = serverData.isRealm() ? "realms" : serverData.ip;
folderName = ctx.minecraft().isConnectedToRealms() ? "realms" : serverData.ip;
} else {
//replaymod causes null currentServer and false singleplayer.
System.out.println("World seems to be a replay. Not loading Baritone cache.");

View File

@@ -33,14 +33,13 @@ import baritone.behavior.Behavior;
import baritone.command.argument.ArgConsumer;
import baritone.command.argument.CommandArguments;
import baritone.command.manager.CommandManager;
import baritone.utils.accessor.IGuiScreen;
import net.minecraft.ChatFormatting;
import net.minecraft.Util;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.*;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.util.Tuple;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Locale;
import java.util.stream.Stream;
@@ -80,10 +79,12 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
MutableComponent component = Component.literal(String.format("> %s", toDisplay));
component.setStyle(component.getStyle()
.withColor(ChatFormatting.WHITE)
.withHoverEvent(new HoverEvent.ShowText(
.withHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT,
Component.literal("Click to rerun command")
))
.withClickEvent(new ClickEvent.RunCommand(
.withClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
FORCE_COMMAND_PREFIX + msg
)));
logDirect(component);
@@ -96,8 +97,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
return false;
} else if (msg.trim().equalsIgnoreCase("orderpizza")) {
try {
Util.getPlatform().openUri("https://www.dominos.com/en/pages/order/");
} catch (Exception ignored) {}
((IGuiScreen) ctx.minecraft().screen).openLinkInvoker(new URI("https://www.dominos.com/en/pages/order/"));
} catch (NullPointerException | URISyntaxException ignored) {}
return false;
}
if (msg.isEmpty()) {

View File

@@ -115,11 +115,11 @@ public class ElytraCommand extends Command {
clippy.append("Within a few hundred blocks of spawn/axis/highways/etc, the terrain is too fragmented to be predictable. Baritone Elytra will still work, just with backtracking. ");
clippy.append("However, once you get more than a few thousand blocks out, you should try ");
MutableComponent olderSeed = Component.literal("the older seed (click here)");
olderSeed.setStyle(olderSeed.getStyle().withUnderlined(true).withBold(true).withHoverEvent(new HoverEvent.ShowText(Component.literal(Baritone.settings().prefix.value + "set elytraNetherSeed " + OLD_2B2T_SEED))).withClickEvent(new ClickEvent.RunCommand(FORCE_COMMAND_PREFIX + "set elytraNetherSeed " + OLD_2B2T_SEED)));
olderSeed.setStyle(olderSeed.getStyle().withUnderlined(true).withBold(true).withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal(Baritone.settings().prefix.value + "set elytraNetherSeed " + OLD_2B2T_SEED))).withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, FORCE_COMMAND_PREFIX + "set elytraNetherSeed " + OLD_2B2T_SEED)));
clippy.append(olderSeed);
clippy.append(". Once you're further out into newer terrain generation (this includes everything up through 1.12), you should try ");
MutableComponent newerSeed = Component.literal("the newer seed (click here)");
newerSeed.setStyle(newerSeed.getStyle().withUnderlined(true).withBold(true).withHoverEvent(new HoverEvent.ShowText(Component.literal(Baritone.settings().prefix.value + "set elytraNetherSeed " + NEW_2B2T_SEED))).withClickEvent(new ClickEvent.RunCommand(FORCE_COMMAND_PREFIX + "set elytraNetherSeed " + NEW_2B2T_SEED)));
newerSeed.setStyle(newerSeed.getStyle().withUnderlined(true).withBold(true).withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal(Baritone.settings().prefix.value + "set elytraNetherSeed " + NEW_2B2T_SEED))).withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, FORCE_COMMAND_PREFIX + "set elytraNetherSeed " + NEW_2B2T_SEED)));
clippy.append(newerSeed);
clippy.append(". Once you get into 1.19 terrain, the terrain becomes unpredictable again, due to custom non-vanilla generation, and you should set #elytraPredictTerrain to false. ");
return clippy;
@@ -130,10 +130,10 @@ public class ElytraCommand extends Command {
gatekeep.append("To disable this message, enable the setting elytraTermsAccepted\n");
gatekeep.append("Baritone Elytra is an experimental feature. It is only intended for long distance travel in the Nether using fireworks for vanilla boost. It will not work with any other mods (\"hacks\") for non-vanilla boost. ");
MutableComponent gatekeep2 = Component.literal("If you want Baritone to attempt to take off from the ground for you, you can enable the elytraAutoJump setting (not advisable on laggy servers!). ");
gatekeep2.setStyle(gatekeep2.getStyle().withHoverEvent(new HoverEvent.ShowText(Component.literal(Baritone.settings().prefix.value + "set elytraAutoJump true"))));
gatekeep2.setStyle(gatekeep2.getStyle().withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal(Baritone.settings().prefix.value + "set elytraAutoJump true"))));
gatekeep.append(gatekeep2);
MutableComponent gatekeep3 = Component.literal("If you want Baritone to go slower, enable the elytraConserveFireworks setting and/or decrease the elytraFireworkSpeed setting. ");
gatekeep3.setStyle(gatekeep3.getStyle().withHoverEvent(new HoverEvent.ShowText(Component.literal(Baritone.settings().prefix.value + "set elytraConserveFireworks true\n" + Baritone.settings().prefix.value + "set elytraFireworkSpeed 0.6\n(the 0.6 number is just an example, tweak to your liking)"))));
gatekeep3.setStyle(gatekeep3.getStyle().withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal(Baritone.settings().prefix.value + "set elytraConserveFireworks true\n" + Baritone.settings().prefix.value + "set elytraFireworkSpeed 0.6\n(the 0.6 number is just an example, tweak to your liking)"))));
gatekeep.append(gatekeep3);
MutableComponent gatekeep4 = Component.literal("Baritone Elytra ");
MutableComponent red = Component.literal("wants to know the seed");

View File

@@ -25,6 +25,7 @@ import baritone.api.command.exception.CommandException;
import baritone.api.command.helpers.TabCompleteHelper;
import baritone.api.utils.BetterBlockPos;
import baritone.cache.CachedChunk;
import net.minecraft.core.Registry;
import net.minecraft.ChatFormatting;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.ClickEvent;
@@ -82,8 +83,8 @@ public class FindCommand extends Command {
baseComponent.setStyle(baseComponent.getStyle()
.withColor(ChatFormatting.GRAY)
.withInsertion(positionText)
.withClickEvent(new ClickEvent.RunCommand(command))
.withHoverEvent(new HoverEvent.ShowText(hoverComponent)));
.withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, command))
.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverComponent)));
return baseComponent;
}

View File

@@ -25,17 +25,19 @@ import baritone.api.command.exception.CommandException;
import baritone.api.command.exception.CommandNotFoundException;
import baritone.api.command.helpers.Paginator;
import baritone.api.command.helpers.TabCompleteHelper;
import java.awt.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.MutableComponent;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static baritone.api.command.IBaritoneChatControl.FORCE_COMMAND_PREFIX;
public class HelpCommand extends Command {
@@ -72,8 +74,8 @@ public class HelpCommand extends Command {
component.setStyle(component.getStyle().withColor(ChatFormatting.GRAY));
component.append(shortDescComponent);
component.setStyle(component.getStyle()
.withHoverEvent(new HoverEvent.ShowText(hoverComponent))
.withClickEvent(new ClickEvent.RunCommand(clickCommand)));
.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverComponent))
.withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, clickCommand)));
return component;
},
FORCE_COMMAND_PREFIX + label
@@ -89,7 +91,8 @@ public class HelpCommand extends Command {
command.getLongDesc().forEach(this::logDirect);
logDirect("");
MutableComponent returnComponent = Component.literal("Click to return to the help menu");
returnComponent.setStyle(returnComponent.getStyle().withClickEvent(new ClickEvent.RunCommand(
returnComponent.setStyle(returnComponent.getStyle().withClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
FORCE_COMMAND_PREFIX + label
)));
logDirect(returnComponent);

View File

@@ -40,10 +40,10 @@ public class RenderCommand extends Command {
int renderDistance = (ctx.minecraft().options.renderDistance().get() + 1) * 16;
ctx.minecraft().levelRenderer.setBlocksDirty(
origin.x - renderDistance,
ctx.world().getMinY(),
ctx.world().getMinBuildHeight(),
origin.z - renderDistance,
origin.x + renderDistance,
ctx.world().getMaxY(),
ctx.world().getMaxBuildHeight(),
origin.z + renderDistance
);
logDirect("Done");

View File

@@ -42,7 +42,7 @@ import baritone.api.utils.BlockOptionalMetaLookup;
import baritone.utils.BlockStateInterface;
import baritone.utils.IRenderer;
import baritone.utils.schematic.StaticSchematic;
import com.mojang.blaze3d.vertex.BufferBuilder;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Vec3i;
import net.minecraft.world.level.block.Blocks;
@@ -75,9 +75,9 @@ public class SelCommand extends Command {
float opacity = Baritone.settings().selectionOpacity.value;
float lineWidth = Baritone.settings().selectionLineWidth.value;
boolean ignoreDepth = Baritone.settings().renderSelectionIgnoreDepth.value;
BufferBuilder bufferBuilder = IRenderer.startLines(color, opacity, lineWidth);
IRenderer.emitAABB(bufferBuilder, event.getModelViewStack(), new AABB(pos1));
IRenderer.endLines(bufferBuilder, ignoreDepth);
IRenderer.startLines(color, opacity, lineWidth, ignoreDepth);
IRenderer.emitAABB(event.getModelViewStack(), new AABB(pos1, pos1.offset(1, 1, 1)));
IRenderer.endLines(ignoreDepth);
}
});
}

View File

@@ -31,8 +31,8 @@ import baritone.api.command.helpers.TabCompleteHelper;
import baritone.api.utils.SettingsUtil;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.MutableComponent;
@@ -108,8 +108,8 @@ public class SetCommand extends Command {
component.setStyle(component.getStyle().withColor(ChatFormatting.GRAY));
component.append(typeComponent);
component.setStyle(component.getStyle()
.withHoverEvent(new HoverEvent.ShowText(hoverComponent))
.withClickEvent(new ClickEvent.SuggestCommand(commandSuggestion)));
.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverComponent))
.withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, commandSuggestion)));
return component;
},
FORCE_COMMAND_PREFIX + "set " + arg + " " + search
@@ -188,10 +188,12 @@ public class SetCommand extends Command {
MutableComponent oldValueComponent = Component.literal(String.format("Old value: %s", oldValue));
oldValueComponent.setStyle(oldValueComponent.getStyle()
.withColor(ChatFormatting.GRAY)
.withHoverEvent(new HoverEvent.ShowText(
.withHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT,
Component.literal("Click to set the setting back to this value")
))
.withClickEvent(new ClickEvent.RunCommand(
.withClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
FORCE_COMMAND_PREFIX + String.format("set %s %s", setting.getName(), oldValue)
)));
logDirect(oldValueComponent);

View File

@@ -44,7 +44,7 @@ public class TunnelCommand extends Command {
int width = Integer.parseInt(args.getArgs().get(1).getValue());
int depth = Integer.parseInt(args.getArgs().get(2).getValue());
if (width < 1 || height < 2 || depth < 1 || height > ctx.world().getMaxY()){
if (width < 1 || height < 2 || depth < 1 || height > ctx.world().getMaxBuildHeight()){
logDirect("Width and depth must at least be 1 block; Height must at least be 2 blocks, and cannot be greater than the build limit.");
cont = false;
}

View File

@@ -34,17 +34,17 @@ import baritone.api.command.helpers.TabCompleteHelper;
import baritone.api.pathing.goals.Goal;
import baritone.api.pathing.goals.GoalBlock;
import baritone.api.utils.BetterBlockPos;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.MutableComponent;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.MutableComponent;
import static baritone.api.command.IBaritoneChatControl.FORCE_COMMAND_PREFIX;
@@ -75,10 +75,12 @@ public class WaypointsCommand extends Command {
component.append(nameComponent);
component.append(timestamp);
component.setStyle(component.getStyle()
.withHoverEvent(new HoverEvent.ShowText(
.withHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT,
Component.literal("Click to select")
))
.withClickEvent(new ClickEvent.RunCommand(
.withClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
String.format(
"%s%s %s %s @ %d",
FORCE_COMMAND_PREFIX,
@@ -158,7 +160,8 @@ public class WaypointsCommand extends Command {
}
deletedWaypoints.computeIfAbsent(baritone.getWorldProvider().getCurrentWorld(), k -> new ArrayList<>()).addAll(Arrays.<IWaypoint>asList(waypoints));
MutableComponent textComponent = Component.literal(String.format("Cleared %d waypoints, click to restore them", waypoints.length));
textComponent.setStyle(textComponent.getStyle().withClickEvent(new ClickEvent.RunCommand(
textComponent.setStyle(textComponent.getStyle().withClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
String.format(
"%s%s restore @ %s",
FORCE_COMMAND_PREFIX,
@@ -238,7 +241,8 @@ public class WaypointsCommand extends Command {
logDirect(transform.apply(waypoint));
logDirect(String.format("Position: %s", waypoint.getLocation()));
MutableComponent deleteComponent = Component.literal("Click to delete this waypoint");
deleteComponent.setStyle(deleteComponent.getStyle().withClickEvent(new ClickEvent.RunCommand(
deleteComponent.setStyle(deleteComponent.getStyle().withClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
String.format(
"%s%s delete %s @ %d",
FORCE_COMMAND_PREFIX,
@@ -248,7 +252,8 @@ public class WaypointsCommand extends Command {
)
)));
MutableComponent goalComponent = Component.literal("Click to set goal to this waypoint");
goalComponent.setStyle(goalComponent.getStyle().withClickEvent(new ClickEvent.RunCommand(
goalComponent.setStyle(goalComponent.getStyle().withClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
String.format(
"%s%s goal %s @ %d",
FORCE_COMMAND_PREFIX,
@@ -258,7 +263,8 @@ public class WaypointsCommand extends Command {
)
)));
MutableComponent recreateComponent = Component.literal("Click to show a command to recreate this waypoint");
recreateComponent.setStyle(recreateComponent.getStyle().withClickEvent(new ClickEvent.SuggestCommand(
recreateComponent.setStyle(recreateComponent.getStyle().withClickEvent(new ClickEvent(
ClickEvent.Action.SUGGEST_COMMAND,
String.format(
"%s%s save %s %s %s %s %s",
Baritone.settings().prefix.value, // This uses the normal prefix because it is run by the user.
@@ -271,7 +277,8 @@ public class WaypointsCommand extends Command {
)
)));
MutableComponent backComponent = Component.literal("Click to return to the waypoints list");
backComponent.setStyle(backComponent.getStyle().withClickEvent(new ClickEvent.RunCommand(
backComponent.setStyle(backComponent.getStyle().withClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
String.format(
"%s%s list",
FORCE_COMMAND_PREFIX,
@@ -286,7 +293,8 @@ public class WaypointsCommand extends Command {
ForWaypoints.waypoints(this.baritone).removeWaypoint(waypoint);
deletedWaypoints.computeIfAbsent(baritone.getWorldProvider().getCurrentWorld(), k -> new ArrayList<>()).add(waypoint);
MutableComponent textComponent = Component.literal("That waypoint has successfully been deleted, click to restore it");
textComponent.setStyle(textComponent.getStyle().withClickEvent(new ClickEvent.RunCommand(
textComponent.setStyle(textComponent.getStyle().withClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
String.format(
"%s%s restore @ %s",
FORCE_COMMAND_PREFIX,

View File

@@ -27,14 +27,11 @@ import baritone.utils.ToolSet;
import baritone.utils.pathing.BetterWorldBorder;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.enchantment.*;
import net.minecraft.world.item.enchantment.effects.EnchantmentAttributeEffect;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.item.enchantment.Enchantments;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
@@ -111,44 +108,19 @@ public class CalculationContext {
this.allowParkourAscend = Baritone.settings().allowParkourAscend.value;
this.assumeWalkOnWater = Baritone.settings().assumeWalkOnWater.value;
this.allowFallIntoLava = false; // Super secret internal setting for ElytraBehavior
// todo: technically there can now be datapack enchants that replace blocks with any other at any range
int frostWalkerLevel = 0;
for (EquipmentSlot slot : EquipmentSlot.values()) {
ItemEnchantments itemEnchantments = baritone.getPlayerContext()
.player()
.getItemBySlot(slot)
.getEnchantments();
for (Holder<Enchantment> enchant : itemEnchantments.keySet()) {
if (enchant.is(Enchantments.FROST_WALKER)) {
frostWalkerLevel = itemEnchantments.getLevel(enchant);
}
}
}
this.frostWalker = frostWalkerLevel;
this.frostWalker = EnchantmentHelper.getEnchantmentLevel(Enchantments.FROST_WALKER, baritone.getPlayerContext().player());
this.allowDiagonalDescend = Baritone.settings().allowDiagonalDescend.value;
this.allowDiagonalAscend = Baritone.settings().allowDiagonalAscend.value;
this.allowDownward = Baritone.settings().allowDownward.value;
this.minFallHeight = 3; // Minimum fall height used by MovementFall
this.maxFallHeightNoWater = Baritone.settings().maxFallHeightNoWater.value;
this.maxFallHeightBucket = Baritone.settings().maxFallHeightBucket.value;
float waterSpeedMultiplier = 1.0f;
OUTER: for (EquipmentSlot slot : EquipmentSlot.values()) {
ItemEnchantments itemEnchantments = baritone.getPlayerContext()
.player()
.getItemBySlot(slot)
.getEnchantments();
for (Holder<Enchantment> enchant : itemEnchantments.keySet()) {
List<EnchantmentAttributeEffect> effects = enchant.value()
.getEffects(EnchantmentEffectComponents.ATTRIBUTES);
for (EnchantmentAttributeEffect effect : effects) {
if (effect.attribute().is(Attributes.WATER_MOVEMENT_EFFICIENCY.unwrapKey().get())) {
waterSpeedMultiplier = effect.amount().calculate(itemEnchantments.getLevel(enchant));
break OUTER;
}
}
}
int depth = EnchantmentHelper.getDepthStrider(player);
if (depth > 3) {
depth = 3;
}
this.waterWalkSpeed = ActionCosts.WALK_ONE_IN_WATER_COST * (1 - waterSpeedMultiplier) + ActionCosts.WALK_ONE_BLOCK_COST * waterSpeedMultiplier;
float mult = depth / 3.0F;
this.waterWalkSpeed = ActionCosts.WALK_ONE_IN_WATER_COST * (1 - mult) + ActionCosts.WALK_ONE_BLOCK_COST * mult;
this.breakBlockAdditionalCost = Baritone.settings().blockBreakAdditionalPenalty.value;
this.backtrackCostFavoringCoefficient = Baritone.settings().backtrackCostFavoringCoefficient.value;
this.jumpPenalty = Baritone.settings().jumpPenalty.value;

View File

@@ -31,11 +31,7 @@ import baritone.utils.BlockStateInterface;
import baritone.utils.ToolSet;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Holder;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.Enchantments;
import net.minecraft.world.item.enchantment.ItemEnchantments;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.piston.MovingPistonBlock;
import net.minecraft.world.level.block.state.BlockState;
@@ -43,12 +39,17 @@ import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.level.block.state.properties.Half;
import net.minecraft.world.level.block.state.properties.SlabType;
import net.minecraft.world.level.block.state.properties.StairsShape;
import net.minecraft.world.level.material.*;
import net.minecraft.world.level.material.FlowingFluid;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.WaterFluid;
import net.minecraft.world.level.pathfinder.PathComputationType;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import java.util.List;
import java.util.Optional;
import static baritone.pathing.movement.Movement.HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP;
@@ -176,10 +177,15 @@ public interface MovementHelper extends ActionCosts, Helper {
if (block instanceof CauldronBlock) {
return NO;
}
if (state.isPathfindable(PathComputationType.LAND)) {
return YES;
} else {
return NO;
try { // A dodgy catch-all at the end, for most blocks with default behaviour this will work, however where blocks are special this will error out, and we can handle it when we have this information
if (state.isPathfindable(null, null, PathComputationType.LAND)) {
return YES;
} else {
return NO;
}
} catch (Throwable exception) {
System.out.println("The block " + state.getBlock().getName().getString() + " requires a special case due to the exception " + exception.getMessage());
return MAYBE;
}
}
@@ -222,7 +228,10 @@ public interface MovementHelper extends ActionCosts, Helper {
return fluidState.getType() instanceof WaterFluid;
}
return state.isPathfindable(PathComputationType.LAND);
// every block that overrides isPassable with anything more complicated than a "return true;" or "return false;"
// has already been accounted for above
// therefore it's safe to not construct a blockpos from our x, y, z ints and instead just pass null
return state.isPathfindable(bsi.access, BlockPos.ZERO, PathComputationType.LAND); // workaround for future compatibility =P
}
static Ternary fullyPassableBlockState(BlockState state) {
@@ -250,10 +259,16 @@ public interface MovementHelper extends ActionCosts, Helper {
}
// door, fence gate, liquid, trapdoor have been accounted for, nothing else uses the world or pos parameters
// at least in 1.12.2 vanilla, that is.....
if (state.isPathfindable(PathComputationType.LAND)) {
return YES;
} else {
return NO;
try { // A dodgy catch-all at the end, for most blocks with default behaviour this will work, however where blocks are special this will error out, and we can handle it when we have this information
if (state.isPathfindable(null, null, PathComputationType.LAND)) {
return YES;
} else {
return NO;
}
} catch (Throwable exception) {
// see PR #1087 for why
System.out.println("The block " + state.getBlock().getName().getString() + " requires a special case due to the exception " + exception.getMessage());
return MAYBE;
}
}
@@ -278,14 +293,11 @@ public interface MovementHelper extends ActionCosts, Helper {
if (fullyPassable == NO) {
return false;
}
return state.isPathfindable(PathComputationType.LAND);
return fullyPassablePosition(new BlockStateInterface(ctx), pos.getX(), pos.getY(), pos.getZ(), state); // meh
}
/**
* params retained for backwards compatibility
*/
static boolean fullyPassablePosition(BlockStateInterface bsi, int x, int y, int z, BlockState state) {
return state.isPathfindable(PathComputationType.LAND);
return state.isPathfindable(bsi.access, bsi.isPassableBlockPos.set(x, y, z), PathComputationType.LAND);
}
static boolean isReplaceable(int x, int y, int z, BlockState state, BlockStateInterface bsi) {
@@ -499,27 +511,14 @@ public interface MovementHelper extends ActionCosts, Helper {
static boolean canUseFrostWalker(CalculationContext context, BlockState state) {
return context.frostWalker != 0
&& state == FrostedIceBlock.meltsInto()
&& state.getValue(LiquidBlock.LEVEL) == 0;
&& ((Integer) state.getValue(LiquidBlock.LEVEL)) == 0;
}
static boolean canUseFrostWalker(IPlayerContext ctx, BlockPos pos) {
boolean hasFrostWalker = false;
OUTER: for (EquipmentSlot slot : EquipmentSlot.values()) {
ItemEnchantments itemEnchantments = ctx
.player()
.getItemBySlot(slot)
.getEnchantments();
for (Holder<Enchantment> enchant : itemEnchantments.keySet()) {
if (enchant.is(Enchantments.FROST_WALKER)) {
hasFrostWalker = true;
break OUTER;
}
}
}
BlockState state = BlockStateInterface.get(ctx, pos);
return hasFrostWalker
return EnchantmentHelper.hasFrostWalker(ctx.player())
&& state == FrostedIceBlock.meltsInto()
&& state.getValue(LiquidBlock.LEVEL) == 0;
&& ((Integer) state.getValue(LiquidBlock.LEVEL)) == 0;
}
/**
@@ -645,7 +644,7 @@ public interface MovementHelper extends ActionCosts, Helper {
*/
static void switchToBestToolFor(IPlayerContext ctx, BlockState b, ToolSet ts, boolean preferSilkTouch) {
if (Baritone.settings().autoTool.value && !Baritone.settings().assumeExternalAutoTool.value) {
ctx.player().getInventory().setSelectedSlot(ts.getBestSlot(b.getBlock(), preferSilkTouch));
ctx.player().getInventory().selected = ts.getBestSlot(b.getBlock(), preferSilkTouch);
}
}

View File

@@ -147,7 +147,7 @@ public class MovementDescend extends Movement {
int effectiveStartHeight = y;
for (int fallHeight = 3; true; fallHeight++) {
int newY = y - fallHeight;
if (newY < context.world.getMinY()) {
if (newY < context.world.getMinBuildHeight()) {
// when pathing in the end, where you could plausibly fall into the void
// this check prevents it from getting the block at y=(below whatever the minimum height is) and crashing
return false;

View File

@@ -30,6 +30,9 @@ import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState;
import baritone.pathing.movement.MovementState.MovementTarget;
import baritone.utils.pathing.MutableMoveResult;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Vec3i;
@@ -44,10 +47,6 @@ import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.WaterFluid;
import net.minecraft.world.phys.Vec3;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
public class MovementFall extends Movement {
private static final ItemStack STACK_BUCKET_WATER = new ItemStack(Items.WATER_BUCKET);
@@ -102,7 +101,7 @@ public class MovementFall extends Movement {
}
if (ctx.player().position().y - dest.getY() < ctx.playerController().getBlockReachDistance() && !ctx.player().onGround()) {
ctx.player().getInventory().setSelectedSlot(ctx.player().getInventory().findSlotMatchingItem(STACK_BUCKET_WATER));
ctx.player().getInventory().selected = ctx.player().getInventory().findSlotMatchingItem(STACK_BUCKET_WATER);
targetRotation = new Rotation(toDest.getYaw(), 90.0F);
@@ -119,7 +118,7 @@ public class MovementFall extends Movement {
if (playerFeet.equals(dest) && (ctx.player().position().y - playerFeet.getY() < 0.094 || isWater)) { // 0.094 because lilypads
if (isWater) { // only match water, not flowing water (which we cannot pick up with a bucket)
if (Inventory.isHotbarSlot(ctx.player().getInventory().findSlotMatchingItem(STACK_BUCKET_EMPTY))) {
ctx.player().getInventory().setSelectedSlot(ctx.player().getInventory().findSlotMatchingItem(STACK_BUCKET_EMPTY));
ctx.player().getInventory().selected = ctx.player().getInventory().findSlotMatchingItem(STACK_BUCKET_EMPTY);
if (ctx.player().getDeltaMovement().y >= 0) {
return state.setInput(Input.CLICK_RIGHT, true);
} else {
@@ -141,7 +140,7 @@ public class MovementFall extends Movement {
}
state.setInput(Input.MOVE_FORWARD, true);
}
Vec3i avoid = Optional.ofNullable(avoid()).map(Direction::getUnitVec3i).orElse(null);
Vec3i avoid = Optional.ofNullable(avoid()).map(Direction::getNormal).orElse(null);
if (avoid == null) {
avoid = src.subtract(dest);
} else {

View File

@@ -64,7 +64,7 @@ public class MovementParkour extends Movement {
if (!context.allowParkour) {
return;
}
if (!context.allowJumpAtBuildLimit && y >= context.world.getMaxY()) {
if (!context.allowJumpAtBuildLimit && y >= context.world.getMaxBuildHeight()) {
return;
}
int xDiff = dir.getStepX();

View File

@@ -25,10 +25,15 @@ import baritone.api.pathing.goals.GoalGetToBlock;
import baritone.api.process.IBuilderProcess;
import baritone.api.process.PathingCommand;
import baritone.api.process.PathingCommandType;
import baritone.api.schematic.*;
import baritone.api.schematic.FillSchematic;
import baritone.api.schematic.ISchematic;
import baritone.api.schematic.IStaticSchematic;
import baritone.api.schematic.MaskSchematic;
import baritone.api.schematic.SubstituteSchematic;
import baritone.api.schematic.RotatedSchematic;
import baritone.api.schematic.MirroredSchematic;
import baritone.api.schematic.format.ISchematicFormat;
import baritone.api.utils.*;
import baritone.api.utils.Rotation;
import baritone.api.utils.input.Input;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
@@ -37,10 +42,11 @@ import baritone.utils.BaritoneProcessHelper;
import baritone.utils.BlockStateInterface;
import baritone.utils.PathingCommandContext;
import baritone.utils.schematic.MapArtSchematic;
import baritone.utils.schematic.SchematicSystem;
import baritone.utils.schematic.SelectionSchematic;
import baritone.utils.schematic.SchematicSystem;
import baritone.utils.schematic.litematica.LitematicaHelper;
import baritone.utils.schematic.schematica.SchematicaHelper;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import net.minecraft.core.BlockPos;
@@ -52,7 +58,14 @@ import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.AirBlock;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.HorizontalDirectionalBlock;
import net.minecraft.world.level.block.LiquidBlock;
import net.minecraft.world.level.block.PipeBlock;
import net.minecraft.world.level.block.RotatedPillarBlock;
import net.minecraft.world.level.block.StairBlock;
import net.minecraft.world.level.block.TrapDoorBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.Property;
import net.minecraft.world.phys.AABB;
@@ -383,7 +396,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
private OptionalInt hasAnyItemThatWouldPlace(BlockState desired, HitResult result, Rotation rot) {
for (int i = 0; i < 9; i++) {
ItemStack stack = ctx.player().getInventory().getNonEquipmentItems().get(i);
ItemStack stack = ctx.player().getInventory().items.get(i);
if (stack.isEmpty() || !(stack.getItem() instanceof BlockItem)) {
continue;
}
@@ -555,7 +568,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
if (toPlace.isPresent() && isSafeToCancel && ctx.player().onGround() && ticks <= 0) {
Rotation rot = toPlace.get().rot;
baritone.getLookBehavior().updateTarget(rot, true);
ctx.player().getInventory().setSelectedSlot(toPlace.get().hotbarSelection);
ctx.player().getInventory().selected = toPlace.get().hotbarSelection;
baritone.getInputOverrideHandler().setInputForceState(Input.SNEAK, true);
if ((ctx.isLookingAt(toPlace.get().placeAgainst) && ((BlockHitResult) ctx.objectMouseOver()).getDirection().equals(toPlace.get().side)) || ctx.playerRotations().isReallyCloseTo(rot)) {
baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true);
@@ -1005,7 +1018,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
private List<BlockState> approxPlaceable(int size) {
List<BlockState> result = new ArrayList<>();
for (int i = 0; i < size; i++) {
ItemStack stack = ctx.player().getInventory().getNonEquipmentItems().get(i);
ItemStack stack = ctx.player().getInventory().items.get(i);
if (stack.isEmpty() || !(stack.getItem() instanceof BlockItem)) {
result.add(Blocks.AIR.defaultBlockState());
continue;
@@ -1037,8 +1050,8 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
if (!ignoreDirection && ignoredProps.isEmpty()) {
return first.equals(second); // early return if no properties are being ignored
}
Map<Property<?>, Comparable<?>> map1 = first.getValues();
Map<Property<?>, Comparable<?>> map2 = second.getValues();
ImmutableMap<Property<?>, Comparable<?>> map1 = first.getValues();
ImmutableMap<Property<?>, Comparable<?>> map2 = second.getValues();
for (Property<?> prop : map1.keySet()) {
if (map1.get(prop) != map2.get(prop)
&& !(ignoreDirection && ORIENTATION_PROPS.contains(prop))

View File

@@ -23,8 +23,6 @@ import baritone.api.process.ICustomGoalProcess;
import baritone.api.process.PathingCommand;
import baritone.api.process.PathingCommandType;
import baritone.utils.BaritoneProcessHelper;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.network.chat.Component;
/**
* As set by ExampleBaritoneControl or something idk
@@ -107,9 +105,7 @@ public final class CustomGoalProcess extends BaritoneProcessHelper implements IC
if (this.goal == null || (this.goal.isInGoal(ctx.playerFeet()) && this.goal.isInGoal(baritone.getPathingBehavior().pathStart()))) {
onLostControl(); // we're there xd
if (Baritone.settings().disconnectOnArrival.value) {
if (ctx.world() instanceof ClientLevel clientLevel) {
clientLevel.disconnect(Component.literal("[Baritone] Arrived at goal!"));
}
ctx.world().disconnect();
}
if (Baritone.settings().notificationOnPathComplete.value) {
logNotification("Pathing complete", false);

View File

@@ -44,10 +44,8 @@ import baritone.process.elytra.NullElytraProcess;
import baritone.utils.BaritoneProcessHelper;
import baritone.utils.PathingCommandContext;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.core.BlockPos;
import net.minecraft.core.NonNullList;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
@@ -159,9 +157,7 @@ public class ElytraProcess extends BaritoneProcessHelper implements IBaritonePro
if (Baritone.settings().disconnectOnArrival.value && !reachedGoal) {
// don't be active when the user logs back in
this.onLostControl();
if (ctx.world() instanceof ClientLevel clientLevel) {
clientLevel.disconnect(Component.literal("[Baritone] Arrived at goal!"));
}
ctx.world().disconnect();
return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL);
}
reachedGoal = true;
@@ -258,8 +254,7 @@ public class ElytraProcess extends BaritoneProcessHelper implements IBaritonePro
if (this.state == State.GET_TO_JUMP) {
final IPathExecutor executor = baritone.getPathingBehavior().getCurrent();
// TODO 1.21.5: replace `ctx.player().getDeltaMovement().y < -0.377` with `ctx.player().fallDistance > 1.0f`
final boolean canStartFlying = ctx.player().getDeltaMovement().y < -0.377
final boolean canStartFlying = ctx.player().fallDistance > 1.0f
&& !isSafeToCancel
&& executor != null
&& executor.getPath().movements().get(executor.getPosition()) instanceof MovementFall;
@@ -277,8 +272,7 @@ public class ElytraProcess extends BaritoneProcessHelper implements IBaritonePro
baritone.getPathingBehavior().secretInternalSegmentCancel();
}
baritone.getInputOverrideHandler().clearAllKeys();
// TODO 1.21.5: replace `ctx.player().getDeltaMovement().y < -0.377` with `ctx.player().fallDistance > 1.0f`
if (ctx.player().getDeltaMovement().y < -0.377) {
if (ctx.player().fallDistance > 1.0f) {
baritone.getInputOverrideHandler().setInputForceState(Input.JUMP, true);
}
}
@@ -366,12 +360,12 @@ public class ElytraProcess extends BaritoneProcessHelper implements IBaritonePro
private boolean shouldLandForSafety() {
ItemStack chest = ctx.player().getItemBySlot(EquipmentSlot.CHEST);
if (chest.getItem() != Items.ELYTRA || chest.getMaxDamage() - chest.getDamageValue() < Baritone.settings().elytraMinimumDurability.value) {
if (chest.getItem() != Items.ELYTRA || chest.getItem().getMaxDamage() - chest.getDamageValue() < Baritone.settings().elytraMinimumDurability.value) {
// elytrabehavior replaces when durability <= minimumDurability, so if durability < minimumDurability then we can reasonably assume that the elytra will soon be broken without replacement
return true;
}
NonNullList<ItemStack> inv = ctx.player().getInventory().getNonEquipmentItems();
NonNullList<ItemStack> inv = ctx.player().getInventory().items;
int qty = 0;
for (int i = 0; i < 36; i++) {
if (ElytraBehavior.isFireworks(inv.get(i))) {

View File

@@ -260,7 +260,7 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
}
if (state.getBlock() instanceof BonemealableBlock) {
BonemealableBlock ig = (BonemealableBlock) state.getBlock();
if (ig.isValidBonemealTarget(ctx.world(), pos, state) && ig.isBonemealSuccess(ctx.world(), ctx.world().random, pos, state)) {
if (ig.isValidBonemealTarget(ctx.world(), pos, state, true) && ig.isBonemealSuccess(ctx.world(), ctx.world().random, pos, state)) {
bonemealable.add(pos);
}
}
@@ -310,7 +310,7 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
if (!(ctx.world().getBlockState(pos.relative(dir)).getBlock() instanceof AirBlock)) {
continue;
}
Vec3 faceCenter = Vec3.atCenterOf(pos).add(Vec3.atLowerCornerOf(dir.getUnitVec3i()).scale(0.5));
Vec3 faceCenter = Vec3.atCenterOf(pos).add(Vec3.atLowerCornerOf(dir.getNormal()).scale(0.5));
Optional<Rotation> rot = RotationUtils.reachableOffset(ctx, pos, faceCenter, blockReachDistance, false);
if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, this::isCocoa)) {
HitResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot.get(), blockReachDistance);

View File

@@ -74,7 +74,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
@Override
public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
if (desiredQuantity > 0) {
int curr = ctx.player().getInventory().getNonEquipmentItems().stream()
int curr = ctx.player().getInventory().items.stream()
.filter(stack -> filter.has(stack))
.mapToInt(ItemStack::getCount).sum();
if (curr >= desiredQuantity) {

View File

@@ -31,12 +31,11 @@ import baritone.utils.BlockStateInterface;
import baritone.utils.IRenderer;
import baritone.utils.PathRenderer;
import baritone.utils.accessor.IFireworkRocketEntity;
import com.mojang.blaze3d.vertex.BufferBuilder;
import it.unimi.dsi.fastutil.floats.FloatArrayList;
import it.unimi.dsi.fastutil.floats.FloatIterator;
import net.minecraft.core.BlockPos;
import net.minecraft.core.NonNullList;
import net.minecraft.core.component.DataComponents;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket;
import net.minecraft.util.Mth;
import net.minecraft.world.InteractionHand;
@@ -45,7 +44,6 @@ import net.minecraft.world.entity.projectile.FireworkRocketEntity;
import net.minecraft.world.inventory.ClickType;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.component.Fireworks;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.block.AirBlock;
@@ -57,9 +55,9 @@ import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.Queue;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.UnaryOperator;
@@ -424,28 +422,28 @@ public final class ElytraBehavior implements Helper {
PathRenderer.drawGoal(event.getModelViewStack(), ctx, new GoalBlock(this.aimPos), event.getPartialTicks(), Color.GREEN);
}
if (!this.clearLines.isEmpty() && settings.elytraRenderRaytraces.value) {
BufferBuilder bufferBuilder = IRenderer.startLines(Color.GREEN, settings.pathRenderLineWidthPixels.value);
IRenderer.startLines(Color.GREEN, settings.pathRenderLineWidthPixels.value, settings.renderPathIgnoreDepth.value);
for (Pair<Vec3, Vec3> line : this.clearLines) {
IRenderer.emitLine(bufferBuilder, event.getModelViewStack(), line.first(), line.second());
IRenderer.emitLine(event.getModelViewStack(), line.first(), line.second());
}
IRenderer.endLines(bufferBuilder, settings.renderPathIgnoreDepth.value);
IRenderer.endLines(settings.renderPathIgnoreDepth.value);
}
if (!this.blockedLines.isEmpty() && Baritone.settings().elytraRenderRaytraces.value) {
BufferBuilder bufferBuilder = IRenderer.startLines(Color.BLUE, settings.pathRenderLineWidthPixels.value);
IRenderer.startLines(Color.BLUE, settings.pathRenderLineWidthPixels.value, settings.renderPathIgnoreDepth.value);
for (Pair<Vec3, Vec3> line : this.blockedLines) {
IRenderer.emitLine(bufferBuilder, event.getModelViewStack(), line.first(), line.second());
IRenderer.emitLine(event.getModelViewStack(), line.first(), line.second());
}
IRenderer.endLines(bufferBuilder, settings.renderPathIgnoreDepth.value);
IRenderer.endLines(settings.renderPathIgnoreDepth.value);
}
if (this.simulationLine != null && Baritone.settings().elytraRenderSimulation.value) {
BufferBuilder bufferBuilder = IRenderer.startLines(new Color(0x36CCDC), settings.pathRenderLineWidthPixels.value);
IRenderer.startLines(new Color(0x36CCDC), settings.pathRenderLineWidthPixels.value, settings.renderPathIgnoreDepth.value);
final Vec3 offset = ctx.player().getPosition(event.getPartialTicks());
for (int i = 0; i < this.simulationLine.size() - 1; i++) {
final Vec3 src = this.simulationLine.get(i).add(offset);
final Vec3 dst = this.simulationLine.get(i + 1).add(offset);
IRenderer.emitLine(bufferBuilder, event.getModelViewStack(), src, dst);
IRenderer.emitLine(event.getModelViewStack(), src, dst);
}
IRenderer.endLines(bufferBuilder, settings.renderPathIgnoreDepth.value);
IRenderer.endLines(settings.renderPathIgnoreDepth.value);
}
}
@@ -924,8 +922,9 @@ public final class ElytraBehavior implements Helper {
if (itemStack.getItem() != Items.FIREWORK_ROCKET) {
return false;
}
Fireworks fw = itemStack.get(DataComponents.FIREWORKS);
return fw != null && fw.explosions().isEmpty();
// If it has NBT data, make sure it won't cause us to explode.
final CompoundTag compound = itemStack.getTagElement("Fireworks");
return compound == null || !compound.getAllKeys().contains("Explosions");
}
private static boolean isBoostingFireworks(final ItemStack itemStack) {
@@ -933,9 +932,11 @@ public final class ElytraBehavior implements Helper {
}
private static OptionalInt getFireworkBoost(final ItemStack itemStack) {
Fireworks fw = itemStack.get(DataComponents.FIREWORKS);
if (fw != null && fw.explosions().isEmpty()) {
return OptionalInt.of(fw.flightDuration());
if (isFireworks(itemStack)) {
final CompoundTag compound = itemStack.getTagElement("Fireworks");
if (compound != null && compound.getAllKeys().contains("Flight")) {
return OptionalInt.of(compound.getByte("Flight"));
}
}
return OptionalInt.empty();
}
@@ -1288,10 +1289,10 @@ public final class ElytraBehavior implements Helper {
}
private int findGoodElytra() {
NonNullList<ItemStack> invy = ctx.player().getInventory().getNonEquipmentItems();
NonNullList<ItemStack> invy = ctx.player().getInventory().items;
for (int i = 0; i < invy.size(); i++) {
ItemStack slot = invy.get(i);
if (slot.getItem() == Items.ELYTRA && (slot.getMaxDamage() - slot.getDamageValue()) > Baritone.settings().elytraMinimumDurability.value) {
if (slot.getItem() == Items.ELYTRA && (slot.getItem().getMaxDamage() - slot.getDamageValue()) > Baritone.settings().elytraMinimumDurability.value) {
return i;
}
}
@@ -1305,7 +1306,7 @@ public final class ElytraBehavior implements Helper {
ItemStack chest = ctx.player().getItemBySlot(EquipmentSlot.CHEST);
if (chest.getItem() != Items.ELYTRA
|| chest.getMaxDamage() - chest.getDamageValue() > Baritone.settings().elytraMinimumDurability.value) {
|| chest.getItem().getMaxDamage() - chest.getDamageValue() > Baritone.settings().elytraMinimumDurability.value) {
return;
}

View File

@@ -30,7 +30,6 @@ import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.world.level.chunk.PaletteResize;
import net.minecraft.world.level.chunk.PalettedContainer;
import net.minecraft.world.phys.Vec3;
@@ -196,7 +195,7 @@ public final class NetherPathfinderContext {
continue;
}
final PalettedContainer<BlockState> bsc = extendedblockstorage.getStates();
final int airId = ((IPalettedContainer<BlockState>) bsc).getPalette().idFor(AIR_BLOCK_STATE, PaletteResize.noResizeExpected());
final int airId = ((IPalettedContainer<BlockState>) bsc).getPalette().idFor(AIR_BLOCK_STATE);
// pasted from FasterWorldScanner
final BitStorage array = ((IPalettedContainer<BlockState>) bsc).getStorage();
if (array == null) continue;

View File

@@ -37,7 +37,7 @@ public class Selection implements ISelection {
max.z - min.z + 1
);
this.aabb = new AABB(min.x, min.y, min.z, max.x + 1, max.y + 1, max.z + 1);
this.aabb = new AABB(this.min, this.max.offset(1, 1, 1));
}
@Override

View File

@@ -5,7 +5,6 @@ import baritone.api.event.events.RenderEvent;
import baritone.api.event.listener.AbstractGameEventListener;
import baritone.api.selection.ISelection;
import baritone.utils.IRenderer;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.world.phys.AABB;
@@ -29,27 +28,27 @@ public class SelectionRenderer implements IRenderer, AbstractGameEventListener {
return;
}
BufferBuilder bufferBuilder = IRenderer.startLines(settings.colorSelection.value, opacity, lineWidth);
IRenderer.startLines(settings.colorSelection.value, opacity, lineWidth, ignoreDepth);
for (ISelection selection : selections) {
IRenderer.emitAABB(bufferBuilder, stack, selection.aabb(), SELECTION_BOX_EXPANSION);
IRenderer.emitAABB(stack, selection.aabb(), SELECTION_BOX_EXPANSION);
}
if (settings.renderSelectionCorners.value) {
IRenderer.glColor(settings.colorSelectionPos1.value, opacity);
for (ISelection selection : selections) {
IRenderer.emitAABB(bufferBuilder, stack, new AABB(selection.pos1()));
IRenderer.emitAABB(stack, new AABB(selection.pos1(), selection.pos1().offset(1, 1, 1)));
}
IRenderer.glColor(settings.colorSelectionPos2.value, opacity);
for (ISelection selection : selections) {
IRenderer.emitAABB(bufferBuilder, stack, new AABB(selection.pos2()));
IRenderer.emitAABB(stack, new AABB(selection.pos2(), selection.pos2().offset(1, 1, 1)));
}
}
IRenderer.endLines(bufferBuilder, ignoreDepth);
IRenderer.endLines(ignoreDepth);
}
@Override

View File

@@ -1,134 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.utils;
import com.mojang.blaze3d.buffers.GpuBuffer;
import com.mojang.blaze3d.buffers.GpuBufferSlice;
import com.mojang.blaze3d.pipeline.RenderPipeline;
import com.mojang.blaze3d.pipeline.RenderTarget;
import com.mojang.blaze3d.systems.RenderPass;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.systems.ScissorState;
import com.mojang.blaze3d.textures.GpuTextureView;
import com.mojang.blaze3d.vertex.MeshData;
import com.mojang.blaze3d.vertex.VertexFormat;
import net.minecraft.client.renderer.RenderStateShard;
import net.minecraft.client.renderer.RenderType;
import org.joml.Vector3f;
import org.joml.Vector4f;
import java.util.OptionalDouble;
import java.util.OptionalInt;
public class BaritoneRenderType extends RenderType {
private final RenderPipeline renderPipeline;
public BaritoneRenderType(String name, int bufferSize, boolean affectsCrumbling, boolean sortOnUpload, RenderPipeline renderPipeline) {
super(name, bufferSize, affectsCrumbling, sortOnUpload, () -> {}, () -> {});
this.renderPipeline = renderPipeline;
}
public static BaritoneRenderType create(String name, int bufferSize, RenderPipeline renderPipeline) {
return new BaritoneRenderType(name, bufferSize, false, false, renderPipeline);
}
@Override
public VertexFormat format() {
return this.renderPipeline.getVertexFormat();
}
@Override
public VertexFormat.Mode mode() {
return this.renderPipeline.getVertexFormatMode();
}
@Override
public RenderPipeline pipeline() {
return this.renderPipeline;
}
@Override
public void draw(final MeshData meshData) {
this.setupRenderState();
try {
GpuBuffer vertexBuffer = this.renderPipeline.getVertexFormat().uploadImmediateVertexBuffer(meshData.vertexBuffer());
GpuBuffer indexBuffer;
VertexFormat.IndexType indexType;
if (meshData.indexBuffer() == null) {
RenderSystem.AutoStorageIndexBuffer autoStorageIndexBuffer = RenderSystem.getSequentialBuffer(meshData.drawState().mode());
indexBuffer = autoStorageIndexBuffer.getBuffer(meshData.drawState().indexCount());
indexType = autoStorageIndexBuffer.type();
} else {
indexBuffer = this.renderPipeline.getVertexFormat().uploadImmediateIndexBuffer(meshData.indexBuffer());
indexType = meshData.drawState().indexType();
}
RenderTarget renderTarget = RenderStateShard.MAIN_TARGET.getRenderTarget();
GpuTextureView colorTextureTarget = RenderSystem.outputColorTextureOverride != null
? RenderSystem.outputColorTextureOverride
: renderTarget.getColorTextureView();
GpuTextureView depthTextureTarget = renderTarget.useDepth
? (RenderSystem.outputDepthTextureOverride != null ? RenderSystem.outputDepthTextureOverride : renderTarget.getDepthTextureView())
: null;
GpuBufferSlice dynamicTransformsUbo = RenderSystem.getDynamicUniforms()
.writeTransform(
RenderSystem.getModelViewMatrix(),
new Vector4f(1.0F, 1.0F, 1.0F, 1.0F),
new Vector3f(),
RenderSystem.getTextureMatrix(),
RenderSystem.getShaderLineWidth()
);
try (RenderPass renderPass = RenderSystem.getDevice()
.createCommandEncoder()
.createRenderPass(() -> "Immediate draw for " + this.getName(), colorTextureTarget, OptionalInt.empty(), depthTextureTarget, OptionalDouble.empty())) {
renderPass.setPipeline(this.renderPipeline);
ScissorState scissorState = RenderSystem.getScissorStateForRenderTypeDraws();
if (scissorState.enabled()) {
renderPass.enableScissor(scissorState.x(), scissorState.y(), scissorState.width(), scissorState.height());
}
RenderSystem.bindDefaultUniforms(renderPass);
renderPass.setUniform("DynamicTransforms", dynamicTransformsUbo);
renderPass.setVertexBuffer(0, vertexBuffer);
for (int i = 0; i < 12; i++) {
GpuTextureView texture = RenderSystem.getShaderTexture(i);
if (texture != null) {
renderPass.bindSampler("Sampler" + i, texture);
}
}
renderPass.setIndexBuffer(indexBuffer, indexType);
renderPass.drawIndexed(0, 0, meshData.drawState().indexCount(), 1);
}
} catch (Throwable e) {
try {
meshData.close();
} catch (Throwable e2) {
e.addSuppressed(e2);
}
throw e;
}
meshData.close();
this.clearRenderState();
}
}

View File

@@ -30,9 +30,9 @@ import net.minecraft.world.level.Level;
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.chunk.ChunkStatus;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.world.level.chunk.status.ChunkStatus;
/**
* Wraps get for chuck caching capability

View File

@@ -60,8 +60,8 @@ public final class BlockStateInterfaceAccessWrapper implements BlockGetter {
}
@Override
public int getMinY() {
return bsi.world.getMinY();
public int getMinBuildHeight() {
return bsi.world.getMinBuildHeight();
}
}

View File

@@ -22,17 +22,16 @@ import baritone.api.BaritoneAPI;
import baritone.api.pathing.goals.GoalBlock;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.Helper;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.phys.AABB;
@@ -85,16 +84,17 @@ public class GuiClick extends Screen implements Helper {
}
@Override
public boolean mouseReleased(MouseButtonEvent event) {
public boolean mouseReleased(double mouseX, double mouseY, int mouseButton) {
if (currentMouseOver != null) { //Catch this, or else a click into void will result in a crash
if (event.button() == 0) {
if (mouseButton == 0) {
if (clickStart != null && !clickStart.equals(currentMouseOver)) {
BaritoneAPI.getProvider().getPrimaryBaritone().getSelectionManager().removeAllSelections();
BaritoneAPI.getProvider().getPrimaryBaritone().getSelectionManager().addSelection(BetterBlockPos.from(clickStart), BetterBlockPos.from(currentMouseOver));
MutableComponent component = Component.literal("Selection made! For usage: " + Baritone.settings().prefix.value + "help sel");
component.setStyle(component.getStyle()
.withColor(ChatFormatting.WHITE)
.withClickEvent(new ClickEvent.RunCommand(
.withClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
FORCE_COMMAND_PREFIX + "help sel"
)));
Helper.HELPER.logDirect(component);
@@ -102,18 +102,18 @@ public class GuiClick extends Screen implements Helper {
} else {
BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalBlock(currentMouseOver));
}
} else if (event.button() == 1) {
} else if (mouseButton == 1) {
BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalBlock(currentMouseOver.above()));
}
}
clickStart = null;
return super.mouseReleased(event);
return super.mouseReleased(mouseX, mouseY, mouseButton);
}
@Override
public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) {
clickStart = currentMouseOver;
return super.mouseClicked(event, doubleClick);
return super.mouseClicked(mouseX, mouseY, mouseButton);
}
public void onRender(PoseStack modelViewStack, Matrix4f projectionMatrix) {
@@ -126,11 +126,11 @@ public class GuiClick extends Screen implements Helper {
// drawSingleSelectionBox WHEN?
PathRenderer.drawManySelectionBoxes(modelViewStack, e, Collections.singletonList(currentMouseOver), Color.CYAN);
if (clickStart != null && !clickStart.equals(currentMouseOver)) {
BufferBuilder bufferBuilder = IRenderer.startLines(Color.RED, Baritone.settings().pathRenderLineWidthPixels.value);
IRenderer.startLines(Color.RED, Baritone.settings().pathRenderLineWidthPixels.value, true);
BetterBlockPos a = new BetterBlockPos(currentMouseOver);
BetterBlockPos b = new BetterBlockPos(clickStart);
IRenderer.emitAABB(bufferBuilder, modelViewStack, new AABB(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z), Math.max(a.x, b.x) + 1, Math.max(a.y, b.y) + 1, Math.max(a.z, b.z) + 1));
IRenderer.endLines(bufferBuilder, true);
IRenderer.emitAABB(modelViewStack, new AABB(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z), Math.max(a.x, b.x) + 1, Math.max(a.y, b.y) + 1, Math.max(a.z, b.z) + 1));
IRenderer.endLines(true);
}
}
}

View File

@@ -20,53 +20,26 @@ package baritone.utils;
import baritone.api.BaritoneAPI;
import baritone.api.Settings;
import baritone.utils.accessor.IEntityRenderManager;
import baritone.utils.accessor.IRenderPipelines;
import com.mojang.blaze3d.pipeline.BlendFunction;
import com.mojang.blaze3d.pipeline.RenderPipeline;
import com.mojang.blaze3d.platform.DepthTestFunction;
import com.mojang.blaze3d.platform.DestFactor;
import com.mojang.blaze3d.platform.SourceFactor;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderPipelines;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
import org.joml.Matrix3f;
import org.joml.Matrix4f;
import java.awt.*;
public interface IRenderer {
Tesselator tessellator = Tesselator.getInstance();
BufferBuilder buffer = tessellator.getBuilder();
IEntityRenderManager renderManager = (IEntityRenderManager) Minecraft.getInstance().getEntityRenderDispatcher();
TextureManager textureManager = Minecraft.getInstance().getTextureManager();
Settings settings = BaritoneAPI.getSettings();
RenderPipeline.Snippet BARITONE_LINES_SNIPPET = RenderPipeline.builder(((IRenderPipelines) new RenderPipelines()).getLinesSnippet())
.withBlend(new BlendFunction(
SourceFactor.SRC_ALPHA,
DestFactor.ONE_MINUS_SRC_ALPHA,
SourceFactor.ONE,
DestFactor.ZERO
))
.withDepthWrite(false)
.withCull(false)
.buildSnippet();
RenderType linesWithDepthRenderType = BaritoneRenderType.create(
"renderType/baritone_lines_with_depth",
256,
RenderPipeline.builder(BARITONE_LINES_SNIPPET)
.withLocation("pipelines/baritone_lines_with_depth")
.withDepthTestFunction(DepthTestFunction.LEQUAL_DEPTH_TEST)
.build()
);
RenderType linesNoDepthRenderType = BaritoneRenderType.create(
"renderType/baritone_lines_no_depth",
256,
RenderPipeline.builder(BARITONE_LINES_SNIPPET)
.withLocation("pipelines/baritone_lines_no_depth")
.withDepthTestFunction(DepthTestFunction.NO_DEPTH_TEST)
.build()
);
float[] color = new float[]{1.0F, 1.0F, 1.0F, 255.0F};
@@ -78,28 +51,43 @@ public interface IRenderer {
IRenderer.color[3] = alpha;
}
static BufferBuilder startLines(Color color, float alpha, float lineWidth) {
static void startLines(Color color, float alpha, float lineWidth, boolean ignoreDepth) {
RenderSystem.enableBlend();
RenderSystem.setShader(GameRenderer::getPositionColorShader);
RenderSystem.blendFuncSeparate(
GlStateManager.SourceFactor.SRC_ALPHA,
GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA,
GlStateManager.SourceFactor.ONE,
GlStateManager.DestFactor.ZERO
);
glColor(color, alpha);
RenderSystem.lineWidth(lineWidth);
return tessellator.begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL);
}
RenderSystem.depthMask(false);
RenderSystem.disableCull();
static BufferBuilder startLines(Color color, float lineWidth) {
return startLines(color, .4f, lineWidth);
}
static void endLines(BufferBuilder bufferBuilder, boolean ignoredDepth) {
MeshData meshData = bufferBuilder.build();
if (meshData != null) {
if (ignoredDepth) {
linesNoDepthRenderType.draw(meshData);
} else {
linesWithDepthRenderType.draw(meshData);
}
if (ignoreDepth) {
RenderSystem.disableDepthTest();
}
RenderSystem.setShader(GameRenderer::getRendertypeLinesShader);
buffer.begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL);
}
static void emitLine(BufferBuilder bufferBuilder, PoseStack stack, double x1, double y1, double z1, double x2, double y2, double z2) {
static void startLines(Color color, float lineWidth, boolean ignoreDepth) {
startLines(color, .4f, lineWidth, ignoreDepth);
}
static void endLines(boolean ignoredDepth) {
tessellator.end();
if (ignoredDepth) {
RenderSystem.enableDepthTest();
}
RenderSystem.enableCull();
RenderSystem.depthMask(true);
RenderSystem.disableBlend();
}
static void emitLine(PoseStack stack, double x1, double y1, double z1, double x2, double y2, double z2) {
final double dx = x2 - x1;
final double dy = y2 - y1;
final double dz = z2 - z1;
@@ -109,59 +97,60 @@ public interface IRenderer {
final float ny = (float) (dy * invMag);
final float nz = (float) (dz * invMag);
emitLine(bufferBuilder, stack, x1, y1, z1, x2, y2, z2, nx, ny, nz);
emitLine(stack, x1, y1, z1, x2, y2, z2, nx, ny, nz);
}
static void emitLine(BufferBuilder bufferBuilder, PoseStack stack,
static void emitLine(PoseStack stack,
double x1, double y1, double z1,
double x2, double y2, double z2,
double nx, double ny, double nz) {
emitLine(bufferBuilder, stack,
emitLine(stack,
(float) x1, (float) y1, (float) z1,
(float) x2, (float) y2, (float) z2,
(float) nx, (float) ny, (float) nz
);
}
static void emitLine(BufferBuilder bufferBuilder, PoseStack stack,
static void emitLine(PoseStack stack,
float x1, float y1, float z1,
float x2, float y2, float z2,
float nx, float ny, float nz) {
PoseStack.Pose pose = stack.last();
final Matrix4f matrix4f = stack.last().pose();
final Matrix3f normal = stack.last().normal();
bufferBuilder.addVertex(pose, x1, y1, z1).setColor(color[0], color[1], color[2], color[3]).setNormal(pose, nx, ny, nz);
bufferBuilder.addVertex(pose, x2, y2, z2).setColor(color[0], color[1], color[2], color[3]).setNormal(pose, nx, ny, nz);
buffer.vertex(matrix4f, x1, y1, z1).color(color[0], color[1], color[2], color[3]).normal(normal, nx, ny, nz).endVertex();
buffer.vertex(matrix4f, x2, y2, z2).color(color[0], color[1], color[2], color[3]).normal(normal, nx, ny, nz).endVertex();
}
static void emitAABB(BufferBuilder bufferBuilder, PoseStack stack, AABB aabb) {
static void emitAABB(PoseStack stack, AABB aabb) {
AABB toDraw = aabb.move(-renderManager.renderPosX(), -renderManager.renderPosY(), -renderManager.renderPosZ());
// bottom
emitLine(bufferBuilder, stack, toDraw.minX, toDraw.minY, toDraw.minZ, toDraw.maxX, toDraw.minY, toDraw.minZ, 1.0, 0.0, 0.0);
emitLine(bufferBuilder, stack, toDraw.maxX, toDraw.minY, toDraw.minZ, toDraw.maxX, toDraw.minY, toDraw.maxZ, 0.0, 0.0, 1.0);
emitLine(bufferBuilder, stack, toDraw.maxX, toDraw.minY, toDraw.maxZ, toDraw.minX, toDraw.minY, toDraw.maxZ, -1.0, 0.0, 0.0);
emitLine(bufferBuilder, stack, toDraw.minX, toDraw.minY, toDraw.maxZ, toDraw.minX, toDraw.minY, toDraw.minZ, 0.0, 0.0, -1.0);
emitLine(stack, toDraw.minX, toDraw.minY, toDraw.minZ, toDraw.maxX, toDraw.minY, toDraw.minZ, 1.0, 0.0, 0.0);
emitLine(stack, toDraw.maxX, toDraw.minY, toDraw.minZ, toDraw.maxX, toDraw.minY, toDraw.maxZ, 0.0, 0.0, 1.0);
emitLine(stack, toDraw.maxX, toDraw.minY, toDraw.maxZ, toDraw.minX, toDraw.minY, toDraw.maxZ, -1.0, 0.0, 0.0);
emitLine(stack, toDraw.minX, toDraw.minY, toDraw.maxZ, toDraw.minX, toDraw.minY, toDraw.minZ, 0.0, 0.0, -1.0);
// top
emitLine(bufferBuilder, stack, toDraw.minX, toDraw.maxY, toDraw.minZ, toDraw.maxX, toDraw.maxY, toDraw.minZ, 1.0, 0.0, 0.0);
emitLine(bufferBuilder, stack, toDraw.maxX, toDraw.maxY, toDraw.minZ, toDraw.maxX, toDraw.maxY, toDraw.maxZ, 0.0, 0.0, 1.0);
emitLine(bufferBuilder, stack, toDraw.maxX, toDraw.maxY, toDraw.maxZ, toDraw.minX, toDraw.maxY, toDraw.maxZ, -1.0, 0.0, 0.0);
emitLine(bufferBuilder, stack, toDraw.minX, toDraw.maxY, toDraw.maxZ, toDraw.minX, toDraw.maxY, toDraw.minZ, 0.0, 0.0, -1.0);
emitLine(stack, toDraw.minX, toDraw.maxY, toDraw.minZ, toDraw.maxX, toDraw.maxY, toDraw.minZ, 1.0, 0.0, 0.0);
emitLine(stack, toDraw.maxX, toDraw.maxY, toDraw.minZ, toDraw.maxX, toDraw.maxY, toDraw.maxZ, 0.0, 0.0, 1.0);
emitLine(stack, toDraw.maxX, toDraw.maxY, toDraw.maxZ, toDraw.minX, toDraw.maxY, toDraw.maxZ, -1.0, 0.0, 0.0);
emitLine(stack, toDraw.minX, toDraw.maxY, toDraw.maxZ, toDraw.minX, toDraw.maxY, toDraw.minZ, 0.0, 0.0, -1.0);
// corners
emitLine(bufferBuilder, stack, toDraw.minX, toDraw.minY, toDraw.minZ, toDraw.minX, toDraw.maxY, toDraw.minZ, 0.0, 1.0, 0.0);
emitLine(bufferBuilder, stack, toDraw.maxX, toDraw.minY, toDraw.minZ, toDraw.maxX, toDraw.maxY, toDraw.minZ, 0.0, 1.0, 0.0);
emitLine(bufferBuilder, stack, toDraw.maxX, toDraw.minY, toDraw.maxZ, toDraw.maxX, toDraw.maxY, toDraw.maxZ, 0.0, 1.0, 0.0);
emitLine(bufferBuilder, stack, toDraw.minX, toDraw.minY, toDraw.maxZ, toDraw.minX, toDraw.maxY, toDraw.maxZ, 0.0, 1.0, 0.0);
emitLine(stack, toDraw.minX, toDraw.minY, toDraw.minZ, toDraw.minX, toDraw.maxY, toDraw.minZ, 0.0, 1.0, 0.0);
emitLine(stack, toDraw.maxX, toDraw.minY, toDraw.minZ, toDraw.maxX, toDraw.maxY, toDraw.minZ, 0.0, 1.0, 0.0);
emitLine(stack, toDraw.maxX, toDraw.minY, toDraw.maxZ, toDraw.maxX, toDraw.maxY, toDraw.maxZ, 0.0, 1.0, 0.0);
emitLine(stack, toDraw.minX, toDraw.minY, toDraw.maxZ, toDraw.minX, toDraw.maxY, toDraw.maxZ, 0.0, 1.0, 0.0);
}
static void emitAABB(BufferBuilder bufferBuilder, PoseStack stack, AABB aabb, double expand) {
emitAABB(bufferBuilder, stack, aabb.inflate(expand, expand, expand));
static void emitAABB(PoseStack stack, AABB aabb, double expand) {
emitAABB(stack, aabb.inflate(expand, expand, expand));
}
static void emitLine(BufferBuilder bufferBuilder, PoseStack stack, Vec3 start, Vec3 end) {
static void emitLine(PoseStack stack, Vec3 start, Vec3 end) {
double vpX = renderManager.renderPosX();
double vpY = renderManager.renderPosY();
double vpZ = renderManager.renderPosZ();
emitLine(bufferBuilder, stack, start.x - vpX, start.y - vpY, start.z - vpZ, end.x - vpX, end.y - vpY, end.z - vpZ);
emitLine(stack, start.x - vpX, start.y - vpY, start.z - vpZ, end.x - vpX, end.y - vpY, end.z - vpZ);
}
}

View File

@@ -25,9 +25,11 @@ import baritone.api.utils.IPlayerContext;
import baritone.api.utils.interfaces.IGoalRenderPos;
import baritone.behavior.PathingBehavior;
import baritone.pathing.path.PathExecutor;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.renderer.blockentity.BeaconRenderer;
import net.minecraft.core.BlockPos;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.block.state.BlockState;
@@ -35,7 +37,6 @@ import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.util.Arrays;
@@ -49,6 +50,9 @@ import java.util.List;
*/
public final class PathRenderer implements IRenderer {
private static final ResourceLocation TEXTURE_BEACON_BEAM = new ResourceLocation("textures/entity/beacon_beam.png");
private PathRenderer() {}
public static double posX() {
@@ -129,7 +133,7 @@ public final class PathRenderer implements IRenderer {
}
public static void drawPath(PoseStack stack, List<BetterBlockPos> positions, int startIndex, Color color, boolean fadeOut, int fadeStart0, int fadeEnd0, double offset) {
BufferBuilder bufferBuilder = IRenderer.startLines(color, settings.pathRenderLineWidthPixels.value);
IRenderer.startLines(color, settings.pathRenderLineWidthPixels.value, settings.renderPathIgnoreDepth.value);
int fadeStart = fadeStart0 + startIndex;
int fadeEnd = fadeEnd0 + startIndex;
@@ -163,13 +167,13 @@ public final class PathRenderer implements IRenderer {
IRenderer.glColor(color, alpha);
}
emitPathLine(bufferBuilder, stack, start.x, start.y, start.z, end.x, end.y, end.z, offset);
emitPathLine(stack, start.x, start.y, start.z, end.x, end.y, end.z, offset);
}
IRenderer.endLines(bufferBuilder, settings.renderPathIgnoreDepth.value);
IRenderer.endLines(settings.renderPathIgnoreDepth.value);
}
private static void emitPathLine(BufferBuilder bufferBuilder, PoseStack stack, double x1, double y1, double z1, double x2, double y2, double z2, double offset) {
private static void emitPathLine(PoseStack stack, double x1, double y1, double z1, double x2, double y2, double z2, double offset) {
final double extraOffset = offset + 0.03D;
double vpX = posX();
@@ -177,20 +181,20 @@ public final class PathRenderer implements IRenderer {
double vpZ = posZ();
boolean renderPathAsFrickinThingy = !settings.renderPathAsLine.value;
IRenderer.emitLine(bufferBuilder, stack,
IRenderer.emitLine(stack,
x1 + offset - vpX, y1 + offset - vpY, z1 + offset - vpZ,
x2 + offset - vpX, y2 + offset - vpY, z2 + offset - vpZ
);
if (renderPathAsFrickinThingy) {
IRenderer.emitLine(bufferBuilder, stack,
IRenderer.emitLine(stack,
x2 + offset - vpX, y2 + offset - vpY, z2 + offset - vpZ,
x2 + offset - vpX, y2 + extraOffset - vpY, z2 + offset - vpZ
);
IRenderer.emitLine(bufferBuilder, stack,
IRenderer.emitLine(stack,
x2 + offset - vpX, y2 + extraOffset - vpY, z2 + offset - vpZ,
x1 + offset - vpX, y1 + extraOffset - vpY, z1 + offset - vpZ
);
IRenderer.emitLine(bufferBuilder, stack,
IRenderer.emitLine(stack,
x1 + offset - vpX, y1 + extraOffset - vpY, z1 + offset - vpZ,
x1 + offset - vpX, y1 + offset - vpY, z1 + offset - vpZ
);
@@ -198,7 +202,7 @@ public final class PathRenderer implements IRenderer {
}
public static void drawManySelectionBoxes(PoseStack stack, Entity player, Collection<BlockPos> positions, Color color) {
BufferBuilder bufferBuilder = IRenderer.startLines(color, settings.pathRenderLineWidthPixels.value);
IRenderer.startLines(color, settings.pathRenderLineWidthPixels.value, settings.renderSelectionBoxesIgnoreDepth.value);
//BlockPos blockpos = movingObjectPositionIn.getBlockPos();
BlockStateInterface bsi = new BlockStateInterface(BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext()); // TODO this assumes same dimension between primary baritone and render view? is this safe?
@@ -208,20 +212,17 @@ public final class PathRenderer implements IRenderer {
VoxelShape shape = state.getShape(player.level(), pos);
AABB toDraw = shape.isEmpty() ? Shapes.block().bounds() : shape.bounds();
toDraw = toDraw.move(pos);
IRenderer.emitAABB(bufferBuilder, stack, toDraw, .002D);
IRenderer.emitAABB(stack, toDraw, .002D);
});
IRenderer.endLines(bufferBuilder, settings.renderSelectionBoxesIgnoreDepth.value);
IRenderer.endLines(settings.renderSelectionBoxesIgnoreDepth.value);
}
public static void drawGoal(PoseStack stack, IPlayerContext ctx, Goal goal, float partialTicks, Color color) {
drawGoal(null, stack, ctx, goal, partialTicks, color, true);
drawGoal(stack, ctx, goal, partialTicks, color, true);
}
private static void drawGoal(@Nullable BufferBuilder bufferBuilder, PoseStack stack, IPlayerContext ctx, Goal goal, float partialTicks, Color color, boolean setupRender) {
if (!setupRender && bufferBuilder == null) {
throw new RuntimeException("BufferBuilder must not be null if setupRender is false");
}
private static void drawGoal(PoseStack stack, IPlayerContext ctx, Goal goal, float partialTicks, Color color, boolean setupRender) {
double renderPosX = posX();
double renderPosY = posY();
double renderPosZ = posZ();
@@ -253,20 +254,45 @@ public final class PathRenderer implements IRenderer {
y2 -= 0.5;
maxY--;
}
drawDankLitGoalBox(bufferBuilder, stack, color, minX, maxX, minZ, maxZ, minY, maxY, y1, y2, setupRender);
drawDankLitGoalBox(stack, color, minX, maxX, minZ, maxZ, minY, maxY, y1, y2, setupRender);
} else if (goal instanceof GoalXZ) {
GoalXZ goalPos = (GoalXZ) goal;
minY = ctx.world().getMinY();
maxY = ctx.world().getMaxY();
minY = ctx.world().getMinBuildHeight();
maxY = ctx.world().getMaxBuildHeight();
if (settings.renderGoalXZBeacon.value) {
// todo: fix beacon renderer (has been broken since at least 1.20.4)
// issue with outer beam rendering, probably related to matrix transforms state not matching vanilla
// possible solutions:
// inject hook into LevelRenderer#renderBlockEntities where the matrices have already been set up correctly
// copy out and modify the vanilla beacon render code
// also another issue on 1.21.5 is we don't have a simple method call for editing the beacon's depth test
// return;
//TODO: check
textureManager.bindForSetup(TEXTURE_BEACON_BEAM);
if (settings.renderGoalIgnoreDepth.value) {
RenderSystem.disableDepthTest();
}
stack.pushPose(); // push
stack.translate(goalPos.getX() - renderPosX, -renderPosY, goalPos.getZ() - renderPosZ); // translate
//TODO: check
BeaconRenderer.renderBeaconBeam(
stack,
ctx.minecraft().renderBuffers().bufferSource(),
TEXTURE_BEACON_BEAM,
settings.renderGoalAnimated.value ? partialTicks : 0,
1.0F,
settings.renderGoalAnimated.value ? ctx.world().getGameTime() : 0,
(int) minY,
(int) maxY,
color.getColorComponents(null),
// Arguments filled by the private method lol
0.2F,
0.25F
);
stack.popPose(); // pop
if (settings.renderGoalIgnoreDepth.value) {
RenderSystem.enableDepthTest();
}
return;
}
minX = goalPos.getX() + 0.002 - renderPosX;
@@ -278,19 +304,19 @@ public final class PathRenderer implements IRenderer {
y2 = 0;
minY -= renderPosY;
maxY -= renderPosY;
drawDankLitGoalBox(bufferBuilder, stack, color, minX, maxX, minZ, maxZ, minY, maxY, y1, y2, setupRender);
drawDankLitGoalBox(stack, color, minX, maxX, minZ, maxZ, minY, maxY, y1, y2, setupRender);
} else if (goal instanceof GoalComposite) {
// Simple way to determine if goals can be batched, without having some sort of GoalRenderer
boolean batch = Arrays.stream(((GoalComposite) goal).goals()).allMatch(IGoalRenderPos.class::isInstance);
BufferBuilder buf = bufferBuilder;
if (batch) {
buf = IRenderer.startLines(color, settings.goalRenderLineWidthPixels.value);
IRenderer.startLines(color, settings.goalRenderLineWidthPixels.value, settings.renderGoalIgnoreDepth.value);
}
for (Goal g : ((GoalComposite) goal).goals()) {
drawGoal(buf, stack, ctx, g, partialTicks, color, !batch);
drawGoal(stack, ctx, g, partialTicks, color, !batch);
}
if (batch) {
IRenderer.endLines(buf, settings.renderGoalIgnoreDepth.value);
IRenderer.endLines(settings.renderGoalIgnoreDepth.value);
}
} else if (goal instanceof GoalInverted) {
drawGoal(stack, ctx, ((GoalInverted) goal).origin, partialTicks, settings.colorInvertedGoalBox.value);
@@ -304,37 +330,37 @@ public final class PathRenderer implements IRenderer {
maxY = minY + 2;
y1 = 1 + y + goalpos.level - renderPosY;
y2 = 1 - y + goalpos.level - renderPosY;
drawDankLitGoalBox(bufferBuilder, stack, color, minX, maxX, minZ, maxZ, minY, maxY, y1, y2, setupRender);
drawDankLitGoalBox(stack, color, minX, maxX, minZ, maxZ, minY, maxY, y1, y2, setupRender);
}
}
private static void drawDankLitGoalBox(BufferBuilder bufferBuilder, PoseStack stack, Color colorIn, double minX, double maxX, double minZ, double maxZ, double minY, double maxY, double y1, double y2, boolean setupRender) {
private static void drawDankLitGoalBox(PoseStack stack, Color colorIn, double minX, double maxX, double minZ, double maxZ, double minY, double maxY, double y1, double y2, boolean setupRender) {
if (setupRender) {
bufferBuilder = IRenderer.startLines(colorIn, settings.goalRenderLineWidthPixels.value);
IRenderer.startLines(colorIn, settings.goalRenderLineWidthPixels.value, settings.renderGoalIgnoreDepth.value);
}
renderHorizontalQuad(bufferBuilder, stack, minX, maxX, minZ, maxZ, y1);
renderHorizontalQuad(bufferBuilder, stack, minX, maxX, minZ, maxZ, y2);
renderHorizontalQuad(stack, minX, maxX, minZ, maxZ, y1);
renderHorizontalQuad(stack, minX, maxX, minZ, maxZ, y2);
for (double y = minY; y < maxY; y += 16) {
double max = Math.min(maxY, y + 16);
IRenderer.emitLine(bufferBuilder, stack, minX, y, minZ, minX, max, minZ, 0.0, 1.0, 0.0);
IRenderer.emitLine(bufferBuilder, stack, maxX, y, minZ, maxX, max, minZ, 0.0, 1.0, 0.0);
IRenderer.emitLine(bufferBuilder, stack, maxX, y, maxZ, maxX, max, maxZ, 0.0, 1.0, 0.0);
IRenderer.emitLine(bufferBuilder, stack, minX, y, maxZ, minX, max, maxZ, 0.0, 1.0, 0.0);
IRenderer.emitLine(stack, minX, y, minZ, minX, max, minZ, 0.0, 1.0, 0.0);
IRenderer.emitLine(stack, maxX, y, minZ, maxX, max, minZ, 0.0, 1.0, 0.0);
IRenderer.emitLine(stack, maxX, y, maxZ, maxX, max, maxZ, 0.0, 1.0, 0.0);
IRenderer.emitLine(stack, minX, y, maxZ, minX, max, maxZ, 0.0, 1.0, 0.0);
}
if (setupRender) {
IRenderer.endLines(bufferBuilder, settings.renderGoalIgnoreDepth.value);
IRenderer.endLines(settings.renderGoalIgnoreDepth.value);
}
}
private static void renderHorizontalQuad(BufferBuilder bufferBuilder, PoseStack stack, double minX, double maxX, double minZ, double maxZ, double y) {
private static void renderHorizontalQuad(PoseStack stack, double minX, double maxX, double minZ, double maxZ, double y) {
if (y != 0) {
IRenderer.emitLine(bufferBuilder, stack, minX, y, minZ, maxX, y, minZ, 1.0, 0.0, 0.0);
IRenderer.emitLine(bufferBuilder, stack, maxX, y, minZ, maxX, y, maxZ, 0.0, 0.0, 1.0);
IRenderer.emitLine(bufferBuilder, stack, maxX, y, maxZ, minX, y, maxZ, -1.0, 0.0, 0.0);
IRenderer.emitLine(bufferBuilder, stack, minX, y, maxZ, minX, y, minZ, 0.0, 0.0, -1.0);
IRenderer.emitLine(stack, minX, y, minZ, maxX, y, minZ, 1.0, 0.0, 0.0);
IRenderer.emitLine(stack, maxX, y, minZ, maxX, y, maxZ, 0.0, 0.0, 1.0);
IRenderer.emitLine(stack, maxX, y, maxZ, minX, y, maxZ, -1.0, 0.0, 0.0);
IRenderer.emitLine(stack, minX, y, maxZ, minX, y, minZ, 0.0, 0.0, -1.0);
}
}
}

View File

@@ -18,10 +18,8 @@
package baritone.utils;
import baritone.api.utils.input.Input;
import net.minecraft.client.player.ClientInput;
import net.minecraft.world.phys.Vec2;
public class PlayerMovementInput extends ClientInput {
public class PlayerMovementInput extends net.minecraft.client.player.Input {
private final InputOverrideHandler handler;
@@ -30,40 +28,31 @@ public class PlayerMovementInput extends ClientInput {
}
@Override
public void tick() {
float leftImpulse = 0.0F;
float forwardImpulse = 0.0F;
boolean jumping = handler.isInputForcedDown(Input.JUMP); // oppa gangnam style
public void tick(boolean p_225607_1_, float f) {
this.leftImpulse = 0.0F;
this.forwardImpulse = 0.0F;
boolean up = handler.isInputForcedDown(Input.MOVE_FORWARD);
if (up) {
forwardImpulse++;
this.jumping = handler.isInputForcedDown(Input.JUMP); // oppa gangnam style
if (this.up = handler.isInputForcedDown(Input.MOVE_FORWARD)) {
this.forwardImpulse++;
}
boolean down = handler.isInputForcedDown(Input.MOVE_BACK);
if (down) {
forwardImpulse--;
if (this.down = handler.isInputForcedDown(Input.MOVE_BACK)) {
this.forwardImpulse--;
}
boolean left = handler.isInputForcedDown(Input.MOVE_LEFT);
if (left) {
leftImpulse++;
if (this.left = handler.isInputForcedDown(Input.MOVE_LEFT)) {
this.leftImpulse++;
}
boolean right = handler.isInputForcedDown(Input.MOVE_RIGHT);
if (right) {
leftImpulse--;
if (this.right = handler.isInputForcedDown(Input.MOVE_RIGHT)) {
this.leftImpulse--;
}
boolean sneaking = handler.isInputForcedDown(Input.SNEAK);
if (sneaking) {
leftImpulse *= 0.3D;
forwardImpulse *= 0.3D;
if (this.shiftKeyDown = handler.isInputForcedDown(Input.SNEAK)) {
this.leftImpulse *= 0.3D;
this.forwardImpulse *= 0.3D;
}
this.moveVector = new Vec2(leftImpulse, forwardImpulse);
boolean sprinting = handler.isInputForcedDown(Input.SPRINT);
this.keyPresses = new net.minecraft.world.entity.player.Input(up, down, left, right, jumping, sneaking, sprinting);
}
}

View File

@@ -19,24 +19,16 @@ package baritone.utils;
import baritone.Baritone;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.core.Holder;
import net.minecraft.core.component.DataComponents;
import net.minecraft.tags.ItemTags;
import net.minecraft.tags.TagKey;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.EnchantmentEffectComponents;
import net.minecraft.world.item.SwordItem;
import net.minecraft.world.item.TieredItem;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.item.enchantment.Enchantments;
import net.minecraft.world.item.enchantment.ItemEnchantments;
import net.minecraft.world.item.enchantment.effects.EnchantmentAttributeEffect;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
@@ -60,20 +52,6 @@ public class ToolSet {
private final LocalPlayer player;
/**
* Used for evaluating the material cost of a tool.
* see {@link #getMaterialCost(ItemStack)}
* Prefer tools with lower material cost (lower index in this list).
*/
private static final List<TagKey<Item>> materialTagsPriorityList = List.of(
ItemTags.WOODEN_TOOL_MATERIALS,
ItemTags.STONE_TOOL_MATERIALS,
ItemTags.IRON_TOOL_MATERIALS,
ItemTags.GOLD_TOOL_MATERIALS,
ItemTags.DIAMOND_TOOL_MATERIALS,
ItemTags.NETHERITE_TOOL_MATERIALS
);
public ToolSet(LocalPlayer player) {
breakStrengthCache = new HashMap<>();
this.player = player;
@@ -98,30 +76,24 @@ public class ToolSet {
}
/**
* Evaluate the material cost of a possible tool.
* If all else is equal, we want to prefer the tool with the lowest material cost.
* i.e. we want to prefer a wooden pickaxe over a stone pickaxe, if all else is equal.
* Evaluate the material cost of a possible tool. The priority matches the
* harvest level order; there is a chance for multiple at the same with modded tools
* but in that case we don't really care.
*
* @param itemStack a possibly empty ItemStack
* @return values from 0 up
*/
private int getMaterialCost(ItemStack itemStack) {
for (int i = 0; i < materialTagsPriorityList.size(); i++) {
final TagKey<Item> tag = materialTagsPriorityList.get(i);
if (itemStack.is(tag)) return i;
if (itemStack.getItem() instanceof TieredItem) {
TieredItem tool = (TieredItem) itemStack.getItem();
return tool.getTier().getLevel();
} else {
return -1;
}
return -1;
}
public boolean hasSilkTouch(ItemStack stack) {
ItemEnchantments enchantments = stack.getEnchantments();
for (Holder<Enchantment> enchant : enchantments.keySet()) {
// silk touch enchantment is still special cased as affecting block drops
// not possible to add custom attribute via datapack
if (enchant.is(Enchantments.SILK_TOUCH) && enchantments.getLevel(enchant) > 0) {
return true;
}
}
return false;
return EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, stack) > 0;
}
/**
@@ -143,7 +115,7 @@ public class ToolSet {
possible, this lets us make pathing depend on the actual tool to be used (if auto tool is disabled)
*/
if (!Baritone.settings().autoTool.value && pathingCalculation) {
return player.getInventory().getSelectedSlot();
return player.getInventory().selected;
}
int best = 0;
@@ -153,7 +125,7 @@ public class ToolSet {
BlockState blockState = b.defaultBlockState();
for (int i = 0; i < 9; i++) {
ItemStack itemStack = player.getInventory().getItem(i);
if (!Baritone.settings().useSwordToMine.value && itemStack.getItem().components().has(DataComponents.WEAPON)) {
if (!Baritone.settings().useSwordToMine.value && itemStack.getItem() instanceof SwordItem) {
continue;
}
@@ -218,15 +190,9 @@ public class ToolSet {
float speed = item.getDestroySpeed(state);
if (speed > 1) {
final ItemEnchantments itemEnchantments = item.getEnchantments();
OUTER: for (Holder<Enchantment> enchant : itemEnchantments.keySet()) {
List<EnchantmentAttributeEffect> effects = enchant.value().getEffects(EnchantmentEffectComponents.ATTRIBUTES);
for (EnchantmentAttributeEffect e : effects) {
if (e.attribute().is(Attributes.MINING_EFFICIENCY.unwrapKey().get())) {
speed += e.amount().calculate(itemEnchantments.getLevel(enchant));
break OUTER;
}
}
int effLevel = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.BLOCK_EFFICIENCY, item);
if (effLevel > 0 && !item.isEmpty()) {
speed += effLevel * effLevel + 1;
}
}
@@ -245,11 +211,11 @@ public class ToolSet {
*/
private double potionAmplifier() {
double speed = 1;
if (player.hasEffect(MobEffects.HASTE)) {
speed *= 1 + (player.getEffect(MobEffects.HASTE).getAmplifier() + 1) * 0.2;
if (player.hasEffect(MobEffects.DIG_SPEED)) {
speed *= 1 + (player.getEffect(MobEffects.DIG_SPEED).getAmplifier() + 1) * 0.2;
}
if (player.hasEffect(MobEffects.MINING_FATIGUE)) {
switch (player.getEffect(MobEffects.MINING_FATIGUE).getAmplifier()) {
if (player.hasEffect(MobEffects.DIG_SLOWDOWN)) {
switch (player.getEffect(MobEffects.DIG_SLOWDOWN).getAmplifier()) {
case 0:
speed *= 0.3;
break;

View File

@@ -1,24 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.utils.accessor;
import com.mojang.blaze3d.pipeline.RenderPipeline;
public interface IRenderPipelines {
RenderPipeline.Snippet getLinesSnippet();
}

View File

@@ -23,7 +23,6 @@ import baritone.utils.schematic.format.defaults.LitematicaSchematic;
import baritone.utils.schematic.format.defaults.MCEditSchematic;
import baritone.utils.schematic.format.defaults.SpongeSchematic;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtAccounter;
import net.minecraft.nbt.NbtIo;
import org.apache.commons.io.FilenameUtils;
@@ -47,7 +46,7 @@ public enum DefaultSchematicFormats implements ISchematicFormat {
MCEDIT("schematic") {
@Override
public IStaticSchematic parse(InputStream input) throws IOException {
return new MCEditSchematic(NbtIo.readCompressed(input, NbtAccounter.unlimitedHeap()));
return new MCEditSchematic(NbtIo.readCompressed(input));
}
},
@@ -59,8 +58,8 @@ public enum DefaultSchematicFormats implements ISchematicFormat {
SPONGE("schem") {
@Override
public IStaticSchematic parse(InputStream input) throws IOException {
CompoundTag nbt = NbtIo.readCompressed(input, NbtAccounter.unlimitedHeap());
int version = nbt.getInt("Version").orElse(-1);
CompoundTag nbt = NbtIo.readCompressed(input);
int version = nbt.getInt("Version");
switch (version) {
case 1:
case 2:
@@ -77,15 +76,13 @@ public enum DefaultSchematicFormats implements ISchematicFormat {
LITEMATICA("litematic") {
@Override
public IStaticSchematic parse(InputStream input) throws IOException {
CompoundTag nbt = NbtIo.readCompressed(input, NbtAccounter.unlimitedHeap());
int version = nbt.getInt("Version").orElse(-1);
CompoundTag nbt = NbtIo.readCompressed(input);
int version = nbt.getInt("Version");
switch (version) {
case 4: //1.12
case 5: //1.13-1.17
throw new UnsupportedOperationException("This litematic Version is too old.");
case 6: //1.18-1.20
throw new UnsupportedOperationException("This litematic Version is too old.");
case 7: //1.21+
case 6: //1.18+
return new LitematicaSchematic(nbt);
default:
throw new UnsupportedOperationException("Unsuported Version of a Litematica Schematic");

View File

@@ -20,14 +20,12 @@ package baritone.utils.schematic.format.defaults;
import baritone.api.schematic.CompositeSchematic;
import baritone.api.schematic.IStaticSchematic;
import baritone.utils.schematic.StaticSchematic;
import net.minecraft.core.Holder;
import net.minecraft.core.Vec3i;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.resources.ResourceLocation;
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.block.state.properties.Property;
import org.apache.commons.lang3.Validate;
@@ -58,13 +56,9 @@ public final class LitematicaSchematic extends CompositeSchematic implements ISt
* @return Array of subregion tags.
*/
private static CompoundTag[] getRegions(CompoundTag nbt) {
return nbt.getCompound("Regions")
.map(CompoundTag::values)
.map(r -> r.stream()
.filter(v -> v instanceof CompoundTag)
.map(CompoundTag.class::cast)
.toArray(CompoundTag[]::new)
).orElse(new CompoundTag[0]);
return nbt.getCompound("Regions").getAllKeys().stream()
.map(nbt.getCompound("Regions")::getCompound)
.toArray(CompoundTag[]::new);
}
/**
@@ -74,8 +68,8 @@ public final class LitematicaSchematic extends CompositeSchematic implements ISt
* @return the lower coord of the requested axis.
*/
private static int getMinOfSubregion(CompoundTag subReg, String s) {
int a = subReg.getCompound("Position").flatMap(position -> position.getInt(s)).orElse(0);
int b = subReg.getCompound("Size").flatMap(size -> size.getInt(s)).orElse(0);
int a = subReg.getCompound("Position").getInt(s);
int b = subReg.getCompound("Size").getInt(s);
return Math.min(a, a + b + 1);
}
@@ -87,14 +81,8 @@ public final class LitematicaSchematic extends CompositeSchematic implements ISt
BlockState[] blockList = new BlockState[blockStatePalette.size()];
for (int i = 0; i < blockStatePalette.size(); i++) {
CompoundTag tag = (CompoundTag) blockStatePalette.get(i);
ResourceLocation blockKey = ResourceLocation.tryParse(tag.getString("Name").orElse(""));
Block block = blockKey == null
? Blocks.AIR
: BuiltInRegistries.BLOCK.get(blockKey)
.map(Holder.Reference::value)
.orElse(Blocks.AIR);
CompoundTag properties = tag.getCompound("Properties").orElse(new CompoundTag());
Block block = BuiltInRegistries.BLOCK.get(new ResourceLocation((((CompoundTag) blockStatePalette.get(i)).getString("Name"))));
CompoundTag properties = ((CompoundTag) blockStatePalette.get(i)).getCompound("Properties");
blockList[i] = getBlockState(block, properties);
}
@@ -109,9 +97,9 @@ public final class LitematicaSchematic extends CompositeSchematic implements ISt
private static BlockState getBlockState(Block block, CompoundTag properties) {
BlockState blockState = block.defaultBlockState();
for (String key : properties.keySet()) {
Property<?> property = block.getStateDefinition().getProperty(key);
String propertyValue = properties.getString(key).orElse(null);
for (Object key : properties.getAllKeys()) {
Property<?> property = block.getStateDefinition().getProperty((String) key);
String propertyValue = properties.getString((String) key);
if (property != null) {
blockState = setPropertyValue(blockState, property, propertyValue);
}
@@ -146,8 +134,8 @@ public final class LitematicaSchematic extends CompositeSchematic implements ISt
* @return the volume of the subregion.
*/
private static long getVolume(CompoundTag subReg) {
CompoundTag size = subReg.getCompound("Size").orElse(new CompoundTag());
return Math.abs(size.getInt("x").orElse(0) * size.getInt("y").orElse(0) * size.getInt("z").orElse(0));
CompoundTag size = subReg.getCompound("Size");
return Math.abs(size.getInt("x") * size.getInt("y") * size.getInt("z"));
}
/**
@@ -168,12 +156,12 @@ public final class LitematicaSchematic extends CompositeSchematic implements ISt
private void fillInSchematic(CompoundTag nbt) {
Vec3i offsetMinCorner = new Vec3i(getMinOfSchematic(nbt, "x"), getMinOfSchematic(nbt, "y"), getMinOfSchematic(nbt, "z"));
for (CompoundTag subReg : getRegions(nbt)) {
ListTag usedBlockTypes = subReg.getListOrEmpty("BlockStatePalette");
ListTag usedBlockTypes = subReg.getList("BlockStatePalette", 10);
BlockState[] blockList = getBlockList(usedBlockTypes);
int bitsPerBlock = getBitsPerBlock(usedBlockTypes.size());
long regionVolume = getVolume(subReg);
long[] blockStateArray = subReg.getLongArray("BlockStates").orElse(new long[0]);
long[] blockStateArray = subReg.getLongArray("BlockStates");
LitematicaBitArray bitArray = new LitematicaBitArray(bitsPerBlock, regionVolume, blockStateArray);
writeSubregionIntoSchematic(subReg, offsetMinCorner, blockList, bitArray);
@@ -190,10 +178,10 @@ public final class LitematicaSchematic extends CompositeSchematic implements ISt
int offsetX = getMinOfSubregion(subReg, "x") - offsetMinCorner.getX();
int offsetY = getMinOfSubregion(subReg, "y") - offsetMinCorner.getY();
int offsetZ = getMinOfSubregion(subReg, "z") - offsetMinCorner.getZ();
CompoundTag size = subReg.getCompound("Size").orElse(new CompoundTag());
int sizeX = Math.abs(size.getInt("x").orElse(0));
int sizeY = Math.abs(size.getInt("y").orElse(0));
int sizeZ = Math.abs(size.getInt("z").orElse(0));
CompoundTag size = subReg.getCompound("Size");
int sizeX = Math.abs(size.getInt("x"));
int sizeY = Math.abs(size.getInt("y"));
int sizeZ = Math.abs(size.getInt("z"));
BlockState[][][] states = new BlockState[sizeX][sizeZ][sizeY];
int index = 0;
for (int y = 0; y < sizeY; y++) {
@@ -285,4 +273,4 @@ public final class LitematicaSchematic extends CompositeSchematic implements ISt
return this.arraySize;
}
}
}
}

View File

@@ -18,13 +18,12 @@
package baritone.utils.schematic.format.defaults;
import baritone.utils.schematic.StaticSchematic;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.datafix.fixes.ItemIdFix;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
/**
@@ -34,19 +33,19 @@ import net.minecraft.world.level.block.state.BlockState;
public final class MCEditSchematic extends StaticSchematic {
public MCEditSchematic(CompoundTag schematic) {
String type = schematic.getString("Materials").orElseThrow();
String type = schematic.getString("Materials");
if (!type.equals("Alpha")) {
throw new IllegalStateException("bad schematic " + type);
}
this.x = schematic.getInt("Width").orElse(0);
this.y = schematic.getInt("Height").orElse(0);
this.z = schematic.getInt("Length").orElse(0);
byte[] blocks = schematic.getByteArray("Blocks").orElseThrow();
this.x = schematic.getInt("Width");
this.y = schematic.getInt("Height");
this.z = schematic.getInt("Length");
byte[] blocks = schematic.getByteArray("Blocks");
// byte[] metadata = schematic.getByteArray("Data");
byte[] additional = null;
if (schematic.contains("AddBlocks")) {
byte[] addBlocks = schematic.getByteArray("AddBlocks").orElseThrow();
byte[] addBlocks = schematic.getByteArray("AddBlocks");
additional = new byte[addBlocks.length * 2];
for (int i = 0; i < addBlocks.length; i++) {
additional[i * 2 + 0] = (byte) ((addBlocks[i] >> 4) & 0xF); // lower nibble
@@ -64,13 +63,7 @@ public final class MCEditSchematic extends StaticSchematic {
// additional is 0 through 15 inclusive since it's & 0xF above
blockID |= additional[blockInd] << 8;
}
ResourceLocation blockKey = ResourceLocation.tryParse(ItemIdFix.getItem(blockID));
Block block = blockKey == null
? Blocks.AIR
: BuiltInRegistries.BLOCK.get(blockKey)
.map(Holder.Reference::value)
.orElse(Blocks.AIR);
Block block = BuiltInRegistries.BLOCK.get(ResourceLocation.tryParse(ItemIdFix.getItem(blockID)));
// int meta = metadata[blockInd] & 0xFF;
// this.states[x][z][y] = block.getStateFromMeta(meta);
this.states[x][z][y] = block.defaultBlockState();

View File

@@ -20,20 +20,18 @@ package baritone.utils.schematic.format.defaults;
import baritone.utils.schematic.StaticSchematic;
import baritone.utils.type.VarInt;
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
import net.minecraft.core.Holder;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
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.block.state.properties.Property;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.Property;
/**
* @author Brady
@@ -42,15 +40,15 @@ import java.util.regex.Pattern;
public final class SpongeSchematic extends StaticSchematic {
public SpongeSchematic(CompoundTag nbt) {
this.x = nbt.getInt("Width").orElse(0);
this.y = nbt.getInt("Height").orElse(0);
this.z = nbt.getInt("Length").orElse(0);
this.x = nbt.getInt("Width");
this.y = nbt.getInt("Height");
this.z = nbt.getInt("Length");
this.states = new BlockState[this.x][this.z][this.y];
Int2ObjectArrayMap<BlockState> palette = new Int2ObjectArrayMap<>();
CompoundTag paletteTag = nbt.getCompound("Palette").orElse(new CompoundTag());
for (String tag : paletteTag.keySet()) {
int index = paletteTag.getInt(tag).orElse(0);
CompoundTag paletteTag = nbt.getCompound("Palette");
for (String tag : paletteTag.getAllKeys()) {
int index = paletteTag.getInt(tag);
SerializedBlockState serializedState = SerializedBlockState.getFromString(tag);
if (serializedState == null) {
@@ -66,7 +64,7 @@ public final class SpongeSchematic extends StaticSchematic {
}
// BlockData is stored as an NBT byte[], however, the actual data that is represented is a varint[]
byte[] rawBlockData = nbt.getByteArray("BlockData").orElseThrow();
byte[] rawBlockData = nbt.getByteArray("BlockData");
int[] blockData = new int[this.x * this.y * this.z];
int offset = 0;
for (int i = 0; i < blockData.length; i++) {
@@ -109,9 +107,7 @@ public final class SpongeSchematic extends StaticSchematic {
private BlockState deserialize() {
if (this.blockState == null) {
Block block = BuiltInRegistries.BLOCK.get(this.resourceLocation)
.map(Holder.Reference::value)
.orElse(Blocks.AIR);
Block block = BuiltInRegistries.BLOCK.get(this.resourceLocation);
this.blockState = block.defaultBlockState();
this.properties.keySet().stream().sorted(String::compareTo).forEachOrdered(key -> {
@@ -134,7 +130,7 @@ public final class SpongeSchematic extends StaticSchematic {
String location = m.group("location");
String properties = m.group("properties");
ResourceLocation resourceLocation = ResourceLocation.parse(location);
ResourceLocation resourceLocation = new ResourceLocation(location);
Map<String, String> propertiesMap = new HashMap<>();
if (properties != null) {
for (String property : properties.split(",")) {

View File

@@ -21,7 +21,7 @@ import net.minecraft.world.level.Level;
public abstract class WorldSchematic extends Level {
private WorldSchematic() {
super(null, null, null, null, false, false, 0, 0);
super(null, null, null, null, null, false, false, 0, 0);
throw new LinkageError();
}
}

View File

@@ -95,7 +95,7 @@ jar {
}
task proguard(type: ProguardTask) {
proguardVersion "7.4.2"
proguardVersion "7.2.1"
}
task createDist(type: CreateDistTask, dependsOn: proguard)

View File

@@ -0,0 +1,105 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch;
import com.google.common.base.Strings;
import com.google.gson.GsonBuilder;
import com.mojang.authlib.Agent;
import com.mojang.authlib.exceptions.AuthenticationException;
import com.mojang.authlib.properties.PropertyMap;
import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService;
import com.mojang.authlib.yggdrasil.YggdrasilUserAuthentication;
import net.minecraft.launchwrapper.Launch;
import java.io.File;
import java.lang.reflect.Field;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Based on GradleStart from ForgeGradle 2.3
*
* @author Brady
* @since 3/11/2019
*/
public class LaunchTesting {
public static void main(String[] args) {
Map<String, String> arguments = new HashMap<>();
hackNatives();
arguments.put("version", "BaritownedDeveloperEnvironment");
arguments.put("assetIndex", System.getenv("assetIndex"));
arguments.put("assetsDir", System.getenv().getOrDefault("assetDirectory", "assets"));
arguments.put("accessToken", "FML");
arguments.put("userProperties", "{}");
arguments.put("tweakClass", System.getenv("tweakClass"));
String password = System.getenv("password");
if (password != null && !password.isEmpty()) {
attemptLogin(arguments, System.getenv("username"), System.getenv("password"));
}
List<String> argsArray = new ArrayList<>();
arguments.forEach((k, v) -> {
argsArray.add("--" + k);
argsArray.add(v);
});
Launch.main(argsArray.toArray(new String[0]));
}
private static void hackNatives() {
String paths = System.getProperty("java.library.path");
String nativesDir = System.getenv().get("nativesDirectory");
if (Strings.isNullOrEmpty(paths))
paths = nativesDir;
else
paths += File.pathSeparator + nativesDir;
System.setProperty("java.library.path", paths);
// hack the classloader now.
try {
final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
sysPathsField.setAccessible(true);
sysPathsField.set(null, null);
} catch (Throwable ignored) {}
}
private static void attemptLogin(Map<String, String> argMap, String username, String password) {
YggdrasilUserAuthentication auth = (YggdrasilUserAuthentication) (new YggdrasilAuthenticationService(Proxy.NO_PROXY, "1")).createUserAuthentication(Agent.MINECRAFT);
auth.setUsername(username);
auth.setPassword(password);
try {
auth.logIn();
} catch (AuthenticationException var4) {
throw new RuntimeException(var4);
}
argMap.put("accessToken", auth.getAuthenticatedToken());
argMap.put("uuid", auth.getSelectedProfile().getId().toString().replace("-", ""));
argMap.put("username", auth.getSelectedProfile().getName());
argMap.put("userType", auth.getUserType().getName());
argMap.put("userProperties", (new GsonBuilder()).registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create().toJson(auth.getUserProperties()));
}
}