warning cleanup

This commit is contained in:
gnembon committed 2023-02-08 21:13:15 +01:00
1 parent 5ab4a9e442
commit 277872b33c
106 files changed
+4495 -4345

No files matched your search

@@ -52,7 +52,7 @@ public class AppStoreManager
*/
private static String scarpetRepoLink = "https://api.github.com/repos/gnembon/scarpet/contents/programs/";
public static void setScarpetRepoLink(@Nullable final String link)
public static void setScarpetRepoLink(@Nullable String link)
{
APP_STORE_ROOT = AppStoreManager.StoreNode.folder(null, "");
scarpetRepoLink = link;
@@ -66,23 +66,24 @@ public class AppStoreManager
public static class StoreNode
{
public String name;
@Nullable
public StoreNode parent;
public Map<String, StoreNode> children;
public boolean sealed;
public String value;
public static StoreNode folder(final StoreNode parent, final String name)
public static StoreNode folder(@Nullable StoreNode parent, String name)
{
final StoreNode node = new StoreNode(parent, name);
StoreNode node = new StoreNode(parent, name);
node.children = new HashMap<>();
node.value = null;
node.sealed = false;
return node;
}
public static StoreNode scriptFile(final StoreNode parent, final String name, final String value)
public static StoreNode scriptFile(StoreNode parent, String name, String value)
{
final StoreNode node = new StoreNode(parent, name);
StoreNode node = new StoreNode(parent, name);
node.children = null;
node.value = value;
node.sealed = true;
@@ -109,7 +110,7 @@ public class AppStoreManager
return this == APP_STORE_ROOT ? new StringBuilder() : parent.createPrePath().append(pathElement());
}
private StoreNode(final StoreNode parent, final String name)
private StoreNode(@Nullable StoreNode parent, String name)
{
this.parent = parent;
this.name = name;
@@ -127,43 +128,40 @@ public class AppStoreManager
throw new IOException("Accessing scarpet app repo is disabled");
}
final String queryPath = scarpetRepoLink + getPath();
final String response;
String queryPath = scarpetRepoLink + getPath();
String response;
try
{
response = IOUtils.toString(new URL(queryPath), StandardCharsets.UTF_8);
}
catch (final IOException e)
catch (IOException e)
{
// Not sealing to allow retrying
throw new IOException("Problems fetching " + queryPath, e);
}
final JsonArray files = JsonParser.parseString(response).getAsJsonArray();
for (final JsonElement je : files)
JsonArray files = JsonParser.parseString(response).getAsJsonArray();
for (JsonElement je : files)
{
final JsonObject jo = je.getAsJsonObject();
final String name = jo.get("name").getAsString();
JsonObject jo = je.getAsJsonObject();
String elementName = jo.get("name").getAsString();
if (jo.get("type").getAsString().equals("dir"))
{
children.put(name, folder(this, name));
children.put(elementName, folder(this, elementName));
}
else// if (name.matches("(\\w+\\.scl?)"))
{
final String value = jo.get("download_url").getAsString();
children.put(name, scriptFile(this, name, value));
String url = jo.get("download_url").getAsString();
children.put(elementName, scriptFile(this, elementName, url));
}
}
sealed = true;
}
/**
* Returns true if doing down the directory structire cannot continue since the matching element is either a leaf or
* Returns true if doing down the directory structure cannot continue since the matching element is either a leaf or
* a string not matching of any node.
*
* @param pathElement
* @return
*/
public boolean cannotContinueFor(final String pathElement) throws IOException
public boolean cannotContinueFor(String pathElement) throws IOException
{
if (isLeaf())
{
@@ -180,14 +178,13 @@ public class AppStoreManager
return name.endsWith(".sc") ? Collections.singletonList(getPath()) : Collections.emptyList();
}
fillChildren();
final String prefix = getPath();
String prefix = getPath();
return children.values().stream().
filter(n -> (!n.isLeaf() || n.name.endsWith(".sc"))).
map(s -> prefix + s.pathElement().replaceAll("/$", "")).
collect(Collectors.toList());
map(s -> prefix + s.pathElement().replaceAll("/$", "")).toList();
}
public StoreNode drillDown(final String pathElement) throws IOException
public StoreNode drillDown(String pathElement) throws IOException
{
if (isLeaf())
{
@@ -201,9 +198,9 @@ public class AppStoreManager
return children.get(pathElement);
}
public String getValue(final String file) throws IOException
public String getValue(String file) throws IOException
{
final StoreNode leaf = drillDown(file);
StoreNode leaf = drillDown(file);
if (!leaf.isLeaf())
{
throw new IOException(file + " is not a file");
@@ -220,11 +217,11 @@ public class AppStoreManager
* @param currentPath The path down which we want to search for files
* @return A pair of the current valid path, as well as the set of all the file/directory names at the end of that path
*/
public static List<String> suggestionsFromPath(final String currentPath) throws IOException
public static List<String> suggestionsFromPath(String currentPath) throws IOException
{
final String[] path = currentPath.split("/");
String[] path = currentPath.split("/");
StoreNode appKiosk = APP_STORE_ROOT;
for (final String pathElement : path)
for (String pathElement : path)
{
if (appKiosk.cannotContinueFor(pathElement))
{
@@ -232,13 +229,10 @@ public class AppStoreManager
}
appKiosk = appKiosk.children.get(pathElement);
}
final List<String> filteredSuggestions = appKiosk.createPathSuggestions().stream().filter(s -> s.startsWith(currentPath)).collect(Collectors.toList());
if (filteredSuggestions.size() == 1)
List<String> filteredSuggestions = appKiosk.createPathSuggestions().stream().filter(s -> s.startsWith(currentPath)).toList();
if (filteredSuggestions.size() == 1 && !appKiosk.isLeaf())
{
if (!appKiosk.isLeaf())
{
return suggestionsFromPath(filteredSuggestions.get(0)); // Start suggesting directory contents
}
return suggestionsFromPath(filteredSuggestions.get(0)); // Start suggesting directory contents
}
return filteredSuggestions;
}
@@ -251,20 +245,20 @@ public class AppStoreManager
* @return {@code 1} if we succesfully saved the script, {@code 0} otherwise
*/
public static int downloadScript(final CommandSourceStack source, final String path)
public static int downloadScript(CommandSourceStack source, String path)
{
final AppInfo nodeInfo = getFileNode(path);
AppInfo nodeInfo = getFileNode(path);
return downloadScript(source, path, nodeInfo, false);
}
private static int downloadScript(final CommandSourceStack source, final String path, final AppInfo nodeInfo, final boolean useTrash)
private static int downloadScript(CommandSourceStack source, String path, AppInfo nodeInfo, boolean useTrash)
{
final String code;
String code;
try
{
code = IOUtils.toString(new URL(nodeInfo.url()), StandardCharsets.UTF_8);
}
catch (final IOException e)
catch (IOException e)
{
throw new CommandRuntimeException(Carpet.Messenger_compose("rb Failed to obtain app file content: " + e.getMessage()));
}
@@ -272,7 +266,7 @@ public class AppStoreManager
{
return 0;
}
final boolean success = Vanilla.MinecraftServer_getScriptServer(source.getServer()).addScriptHost(source, nodeInfo.name().replaceFirst("\\.sc$", ""), null, true, false, false, nodeInfo.source());
boolean success = Vanilla.MinecraftServer_getScriptServer(source.getServer()).addScriptHost(source, nodeInfo.name().replaceFirst("\\.sc$", ""), null, true, false, false, nodeInfo.source());
return success ? 1 : 0;
}
@@ -282,35 +276,35 @@ public class AppStoreManager
* @param appPath The user inputted path to the scarpet script
* @return Pair of app file name and content
*/
public static AppInfo getFileNode(final String appPath)
public static AppInfo getFileNode(String appPath)
{
return getFileNodeFrom(APP_STORE_ROOT, appPath);
}
public static AppInfo getFileNodeFrom(final StoreNode start, final String appPath)
public static AppInfo getFileNodeFrom(StoreNode start, String appPath)
{
final String[] path = appPath.split("/");
String[] path = appPath.split("/");
StoreNode appKiosk = start;
try
{
for (final String pathElement : Arrays.copyOfRange(path, 0, path.length - 1))
for (String pathElement : Arrays.copyOfRange(path, 0, path.length - 1))
{
appKiosk = appKiosk.drillDown(pathElement);
}
final String appName = path[path.length - 1];
String appName = path[path.length - 1];
appKiosk.getValue(appName);
return new AppInfo(appName, appKiosk.getValue(appName), appKiosk);
}
catch (final IOException e)
catch (IOException e)
{
throw new CommandRuntimeException(Carpet.Messenger_compose("rb '" + appPath + "' is not a valid path to a scarpet app: " + e.getMessage()));
}
}
public static boolean saveScriptToFile(final CommandSourceStack source, final String path, final String appFileName, final String code, final boolean globalSavePath, final boolean useTrash)
public static boolean saveScriptToFile(CommandSourceStack source, String path, String appFileName, String code, boolean globalSavePath, boolean useTrash)
{
final Path scriptLocation;
Path scriptLocation;
if (globalSavePath && !source.getServer().isDedicatedServer()) // never happens, this is always called with globalSavePath being false
{ //cos config folder only is in clients
scriptLocation = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts/appstore").toAbsolutePath().resolve(path);
@@ -331,8 +325,8 @@ public class AppStoreManager
int i = 0;
while (Files.exists(trashPath))
{
final String[] nameAndExtension = appFileName.split("\\.");
final String newFileName = String.format(nameAndExtension[0] + "%02d." + nameAndExtension[1], i);
String[] nameAndExtension = appFileName.split("\\.");
String newFileName = String.format(nameAndExtension[0] + "%02d." + nameAndExtension[1], i);
trashPath = trashPath.getParent().resolve(newFileName);
i++;
}
@@ -340,11 +334,11 @@ public class AppStoreManager
}
Carpet.Messenger_message(source, String.format("gi Note: replaced existing app '%s'" + (useTrash ? " (old moved to /trash folder)" : ""), appFileName));
}
final BufferedWriter writer = Files.newBufferedWriter(scriptLocation);
BufferedWriter writer = Files.newBufferedWriter(scriptLocation);
writer.write(code);
writer.close();
}
catch (final IOException e)
catch (IOException e)
{
Carpet.Messenger_message(source, "r Error while downloading app: " + e);
CarpetScriptServer.LOG.warn("Error while downloading app", e);
@@ -353,15 +347,15 @@ public class AppStoreManager
return true;
}
public static void writeUrlToFile(final String url, final Path destination) throws IOException
public static void writeUrlToFile(String url, Path destination) throws IOException
{
try (final InputStream in = new URL(url).openStream())
try (InputStream in = new URL(url).openStream())
{
Files.copy(in, destination, StandardCopyOption.REPLACE_EXISTING);
}
}
private static String getFullContentUrl(final String original, final StoreNode storeSource)
private static String getFullContentUrl(String original, StoreNode storeSource)
{
if (original.matches("^https?://.*$")) // We've got a full url here: Just use it
{
@@ -374,28 +368,28 @@ public class AppStoreManager
return getFileNodeFrom(storeSource, original).url(); // Relative path: Use download location
}
public static void addResource(final CarpetScriptHost carpetScriptHost, final StoreNode storeSource, final Value resource)
public static void addResource(CarpetScriptHost carpetScriptHost, StoreNode storeSource, Value resource)
{
if (!(resource instanceof final MapValue map))
{
throw new InternalExpressionException("This is not a valid resource map: " + resource.getString());
}
final Map<String, Value> resourceMap = map.getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), Map.Entry::getValue));
Map<String, Value> resourceMap = map.getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), Map.Entry::getValue));
if (!resourceMap.containsKey("source"))
{
throw new InternalExpressionException("Missing 'source' field in resource descriptor: " + resource.getString());
}
final String source = resourceMap.get("source").getString();
final String contentUrl = getFullContentUrl(source, storeSource);
final String target = resourceMap.computeIfAbsent("target", k -> new StringValue(contentUrl.substring(contentUrl.lastIndexOf('/') + 1))).getString();
final boolean shared = resourceMap.getOrDefault("shared", Value.FALSE).getBoolean();
String source = resourceMap.get("source").getString();
String contentUrl = getFullContentUrl(source, storeSource);
String target = resourceMap.computeIfAbsent("target", k -> new StringValue(contentUrl.substring(contentUrl.lastIndexOf('/') + 1))).getString();
boolean shared = resourceMap.getOrDefault("shared", Value.FALSE).getBoolean();
if (!carpetScriptHost.applyActionForResource(target, shared, p -> {
try
{
writeUrlToFile(contentUrl, p);
}
catch (final IOException e)
catch (IOException e)
{
throw new InternalExpressionException("Unable to write resource " + target + ": " + e);
}
@@ -414,7 +408,8 @@ public class AppStoreManager
* @param contentUrl The full content URL, from {@link #getFullContentUrl(String, StoreNode)}
* @return A {@link StoreNode} that can be used in an app that came from the provided source
*/
private static StoreNode getNewStoreNode(final StoreNode originalSource, String sourceString, final String contentUrl)
@Nullable
private static StoreNode getNewStoreNode(StoreNode originalSource, String sourceString, String contentUrl)
{
StoreNode next = originalSource;
if (sourceString == contentUrl) // External URL (check getFullUrlContent)
@@ -426,7 +421,7 @@ public class AppStoreManager
next = APP_STORE_ROOT;
sourceString = sourceString.substring(1);
}
final String[] dirs = sourceString.split("/");
String[] dirs = sourceString.split("/");
try
{
for (int i = 0; i < dirs.length - 1; i++)
@@ -434,23 +429,23 @@ public class AppStoreManager
next = next.drillDown(dirs[i]);
}
}
catch (final IOException e)
catch (IOException e)
{
return null; // Should never happen, but let's not give a potentially incorrect node just in case
}
return next;
}
public static void addLibrary(final CarpetScriptHost carpetScriptHost, final StoreNode storeSource, final Value library)
public static void addLibrary(CarpetScriptHost carpetScriptHost, StoreNode storeSource, Value library)
{
if (!(library instanceof final MapValue map))
{
throw new InternalExpressionException("This is not a valid library map: " + library.getString());
}
final Map<String, String> libraryMap = map.getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), e -> e.getValue().getString()));
final String source = libraryMap.get("source");
final String contentUrl = getFullContentUrl(source, storeSource);
final String target = libraryMap.computeIfAbsent("target", k -> contentUrl.substring(contentUrl.lastIndexOf('/') + 1));
Map<String, String> libraryMap = map.getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), e -> e.getValue().getString()));
String source = libraryMap.get("source");
String contentUrl = getFullContentUrl(source, storeSource);
String target = libraryMap.computeIfAbsent("target", k -> contentUrl.substring(contentUrl.lastIndexOf('/') + 1));
if (!(contentUrl.endsWith(".sc") || contentUrl.endsWith(".scl")))
{
throw new InternalExpressionException("App resource type must download a scarpet app or library.");
@@ -463,7 +458,7 @@ public class AppStoreManager
{
downloadScript(carpetScriptHost.responsibleSource, target, new AppInfo(target, contentUrl, getNewStoreNode(storeSource, source, contentUrl)), true);
}
catch (final CommandRuntimeException e)
catch (CommandRuntimeException e)
{
throw new InternalExpressionException("Error when installing app dependencies: " + e);
}
@@ -33,7 +33,7 @@ public class BiomeInfo
put("humidity", (w, b) -> NumericValue.of(Vanilla.Biome_getClimateSettings(b).downfall()));
put("precipitation", (w, b) -> StringValue.of(b.getPrecipitationAt(new BlockPos(0, w.getSeaLevel(), 0)).name().toLowerCase(Locale.ROOT)));
put("features", (w, b) -> {
final Registry<ConfiguredFeature<?, ?>> registry = w.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE);
Registry<ConfiguredFeature<?, ?>> registry = w.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE);
return ListValue.wrap(
b.getGenerationSettings().features().stream().map(step ->
ListValue.wrap(step.stream().map(cfp ->
@@ -9,24 +9,22 @@ public class EntityTools
{
/**
* Not a replacement for living entity jump() - this barely is to allow other entities that can't jump in vanilla to 'jump'
*
* @param e
*/
public static void genericJump(final Entity e)
public static void genericJump(Entity e)
{
if (!e.isOnGround() && !e.isInWaterOrBubble() && !e.isInLava())
{
return;
}
final float m = e.level.getBlockState(e.blockPosition()).getBlock().getJumpFactor();
final float g = e.level.getBlockState(new BlockPos(e.getX(), e.getBoundingBox().minY - 0.5000001D, e.getZ())).getBlock().getJumpFactor();
final float jumpVelocityMultiplier = m == 1.0D ? g : m;
final float jumpStrength = (0.42F * jumpVelocityMultiplier);
final Vec3 vec3d = e.getDeltaMovement();
float m = e.level.getBlockState(e.blockPosition()).getBlock().getJumpFactor();
float g = e.level.getBlockState(new BlockPos(e.getX(), e.getBoundingBox().minY - 0.5000001D, e.getZ())).getBlock().getJumpFactor();
float jumpVelocityMultiplier = m == 1.0D ? g : m;
float jumpStrength = (0.42F * jumpVelocityMultiplier);
Vec3 vec3d = e.getDeltaMovement();
e.setDeltaMovement(vec3d.x, jumpStrength, vec3d.z);
if (e.isSprinting())
{
final float u = e.getYRot() * 0.017453292F; // yaw
float u = e.getYRot() * 0.017453292F; // yaw
e.setDeltaMovement(e.getDeltaMovement().add((-Mth.sin(g) * 0.2F), 0.0D, (Mth.cos(u) * 0.2F)));
}
e.hasImpulse = true;
@@ -19,7 +19,7 @@ public class EquipmentInventory implements Container
LivingEntity mob;
public EquipmentInventory(final LivingEntity mob)
public EquipmentInventory(LivingEntity mob)
{
this.mob = mob;
}
@@ -33,7 +33,7 @@ public class EquipmentInventory implements Container
@Override
public boolean isEmpty()
{
for (final EquipmentSlot slot : slotToSlot)
for (EquipmentSlot slot : slotToSlot)
{
if (!mob.getItemBySlot(slot).isEmpty())
{
@@ -44,14 +44,14 @@ public class EquipmentInventory implements Container
}
@Override
public ItemStack getItem(final int slot)
public ItemStack getItem(int slot)
{
final EquipmentSlot slotSlot;
EquipmentSlot slotSlot;
try
{
slotSlot = slotToSlot.get(slot);
}
catch (final IndexOutOfBoundsException ignored)
catch (IndexOutOfBoundsException ignored)
{
//going out of the index should be really exceptional
return ItemStack.EMPTY;
@@ -60,14 +60,14 @@ public class EquipmentInventory implements Container
}
@Override
public ItemStack removeItem(final int slot, final int amount)
public ItemStack removeItem(int slot, int amount)
{
final EquipmentSlot slotSlot;
EquipmentSlot slotSlot;
try
{
slotSlot = slotToSlot.get(slot);
}
catch (final IndexOutOfBoundsException ignored)
catch (IndexOutOfBoundsException ignored)
{
//going out of the index should be really exceptional
return ItemStack.EMPTY;
@@ -76,32 +76,32 @@ public class EquipmentInventory implements Container
}
@Override
public ItemStack removeItemNoUpdate(final int slot)
public ItemStack removeItemNoUpdate(int slot)
{
final EquipmentSlot slotSlot;
EquipmentSlot slotSlot;
try
{
slotSlot = slotToSlot.get(slot);
}
catch (final IndexOutOfBoundsException ignored)
catch (IndexOutOfBoundsException ignored)
{
//going out of the index should be really exceptional
return ItemStack.EMPTY;
}
final ItemStack previous = mob.getItemBySlot(slotSlot);
ItemStack previous = mob.getItemBySlot(slotSlot);
mob.setItemSlot(slotSlot, ItemStack.EMPTY);
return previous;
}
@Override
public void setItem(final int slot, final ItemStack stack)
public void setItem(int slot, ItemStack stack)
{
final EquipmentSlot slotSlot;
EquipmentSlot slotSlot;
try
{
slotSlot = slotToSlot.get(slot);
}
catch (final IndexOutOfBoundsException ignored)
catch (IndexOutOfBoundsException ignored)
{
//going out of the index should be really exceptional
return;
@@ -116,7 +116,7 @@ public class EquipmentInventory implements Container
}
@Override
public boolean stillValid(final Player player)
public boolean stillValid(Player player)
{
return false;
}
@@ -124,7 +124,7 @@ public class EquipmentInventory implements Container
@Override
public void clearContent()
{
for (final EquipmentSlot slot : slotToSlot)
for (EquipmentSlot slot : slotToSlot)
{
mob.setItemSlot(slot, ItemStack.EMPTY);
}
@@ -68,24 +68,24 @@ import javax.annotation.Nullable;
public class FeatureGenerator
{
@Nullable
public static synchronized Boolean plop(final String featureName, final ServerLevel world, final BlockPos pos)
public static synchronized Boolean plop(String featureName, ServerLevel world, BlockPos pos)
{
final Function<ServerLevel, Thing> custom = featureMap.get(featureName);
Function<ServerLevel, Thing> custom = featureMap.get(featureName);
if (custom != null)
{
return custom.apply(world).plop(world, pos);
}
final ResourceLocation id = new ResourceLocation(featureName);
final Structure structure = world.registryAccess().registryOrThrow(Registries.STRUCTURE).get(id);
ResourceLocation id = new ResourceLocation(featureName);
Structure structure = world.registryAccess().registryOrThrow(Registries.STRUCTURE).get(id);
if (structure != null)
{
return plopAnywhere(structure, world, pos, world.getChunkSource().getGenerator(), false);
}
final ConfiguredFeature<?, ?> configuredFeature = world.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE).get(id);
ConfiguredFeature<?, ?> configuredFeature = world.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE).get(id);
if (configuredFeature != null)
{
final ThreadLocal<Boolean> checks = Vanilla.skipGenerationChecks(world);
ThreadLocal<Boolean> checks = Vanilla.skipGenerationChecks(world);
checks.set(true);
try
{
@@ -96,22 +96,22 @@ public class FeatureGenerator
checks.set(false);
}
}
final Optional<StructureType<?>> structureType = world.registryAccess().registryOrThrow(Registries.STRUCTURE_TYPE).getOptional(id);
Optional<StructureType<?>> structureType = world.registryAccess().registryOrThrow(Registries.STRUCTURE_TYPE).getOptional(id);
if (structureType.isPresent())
{
final Structure configuredStandard = getDefaultFeature(structureType.get(), world, pos);
Structure configuredStandard = getDefaultFeature(structureType.get(), world, pos);
if (configuredStandard != null)
{
return plopAnywhere(configuredStandard, world, pos, world.getChunkSource().getGenerator(), false);
}
}
final Feature<?> feature = world.registryAccess().registryOrThrow(Registries.FEATURE).get(id);
Feature<?> feature = world.registryAccess().registryOrThrow(Registries.FEATURE).get(id);
if (feature != null)
{
final ConfiguredFeature<?, ?> configuredStandard = getDefaultFeature(feature, world, pos, true);
ConfiguredFeature<?, ?> configuredStandard = getDefaultFeature(feature, world, pos, true);
if (configuredStandard != null)
{
final ThreadLocal<Boolean> checks = Vanilla.skipGenerationChecks(world);
ThreadLocal<Boolean> checks = Vanilla.skipGenerationChecks(world);
checks.set(true);
try
{
@@ -126,15 +126,16 @@ public class FeatureGenerator
return null;
}
public static Structure resolveConfiguredStructure(final String name, final ServerLevel world, final BlockPos pos)
@Nullable
public static Structure resolveConfiguredStructure(String name, ServerLevel world, BlockPos pos)
{
final ResourceLocation id = new ResourceLocation(name);
final Structure configuredStructureFeature = world.registryAccess().registryOrThrow(Registries.STRUCTURE).get(id);
ResourceLocation id = new ResourceLocation(name);
Structure configuredStructureFeature = world.registryAccess().registryOrThrow(Registries.STRUCTURE).get(id);
if (configuredStructureFeature != null)
{
return configuredStructureFeature;
}
final StructureType<?> structureFeature = world.registryAccess().registryOrThrow(Registries.STRUCTURE_TYPE).get(id);
StructureType<?> structureFeature = world.registryAccess().registryOrThrow(Registries.STRUCTURE_TYPE).get(id);
if (structureFeature == null)
{
return null;
@@ -142,7 +143,7 @@ public class FeatureGenerator
return getDefaultFeature(structureFeature, world, pos);
}
public static synchronized Boolean plopGrid(final Structure structureFeature, final ServerLevel world, final BlockPos pos)
public static synchronized boolean plopGrid(Structure structureFeature, ServerLevel world, BlockPos pos)
{
return plopAnywhere(structureFeature, world, pos, world.getChunkSource().getGenerator(), true);
}
@@ -153,10 +154,10 @@ public class FeatureGenerator
Boolean plop(ServerLevel world, BlockPos pos);
}
private static Thing simplePlop(final ConfiguredFeature<?, ?> feature)
private static Thing simplePlop(ConfiguredFeature<?, ?> feature)
{
return (w, p) -> {
final ThreadLocal<Boolean> checks = Vanilla.skipGenerationChecks(w);
ThreadLocal<Boolean> checks = Vanilla.skipGenerationChecks(w);
checks.set(true);
try
{
@@ -169,34 +170,34 @@ public class FeatureGenerator
};
}
private static <FC extends FeatureConfiguration, F extends Feature<FC>> Thing simplePlop(final F feature, final FC config)
private static <FC extends FeatureConfiguration, F extends Feature<FC>> Thing simplePlop(F feature, FC config)
{
return simplePlop(new ConfiguredFeature<>(feature, config));
}
private static Thing simpleTree(final TreeConfiguration config)
private static Thing simpleTree(TreeConfiguration config)
{
//config.ignoreFluidCheck();
return simplePlop(new ConfiguredFeature<>(Feature.TREE, config));
}
private static Thing spawnCustomStructure(final Structure structure)
private static Thing spawnCustomStructure(Structure structure)
{
return setupCustomStructure(structure, false);
}
private static Thing setupCustomStructure(final Structure structure, final boolean wireOnly)
private static Thing setupCustomStructure(Structure structure, boolean wireOnly)
{
return (w, p) -> plopAnywhere(structure, w, p, w.getChunkSource().getGenerator(), wireOnly);
}
private static Structure getDefaultFeature(final StructureType<?> structure, final ServerLevel world, final BlockPos pos)
private static Structure getDefaultFeature(StructureType<?> structure, ServerLevel world, BlockPos pos)
{
// would be nice to have a way to grab structures of this type for position
// TODO allow old types, like vaillage, or bastion
final Holder<Biome> existingBiome = world.getBiome(pos);
Holder<Biome> existingBiome = world.getBiome(pos);
Structure result = null;
for (final Structure confstr : world.registryAccess().registryOrThrow(Registries.STRUCTURE).entrySet().stream().
for (Structure confstr : world.registryAccess().registryOrThrow(Registries.STRUCTURE).entrySet().stream().
filter(cS -> cS.getValue().type() == structure).map(Map.Entry::getValue).toList())
{
result = confstr;
@@ -208,12 +209,12 @@ public class FeatureGenerator
return result;
}
private static ConfiguredFeature<?, ?> getDefaultFeature(final Feature<?> feature, final ServerLevel world, final BlockPos pos, final boolean tryHard)
private static ConfiguredFeature<?, ?> getDefaultFeature(Feature<?> feature, ServerLevel world, BlockPos pos, boolean tryHard)
{
final List<HolderSet<PlacedFeature>> configuredStepFeatures = world.getBiome(pos).value().getGenerationSettings().features();
for (final HolderSet<PlacedFeature> step : configuredStepFeatures)
List<HolderSet<PlacedFeature>> configuredStepFeatures = world.getBiome(pos).value().getGenerationSettings().features();
for (HolderSet<PlacedFeature> step : configuredStepFeatures)
{
for (final Holder<PlacedFeature> provider : step)
for (Holder<PlacedFeature> provider : step)
{
if (provider.value().feature().value().feature() == feature)
{
@@ -230,21 +231,22 @@ public class FeatureGenerator
findFirst().map(Map.Entry::getValue).orElse(null);
}
public static <T extends FeatureConfiguration> StructureStart shouldStructureStartAt(final ServerLevel world, final BlockPos pos, final Structure structure, final boolean computeBox)
public static <T extends FeatureConfiguration> StructureStart shouldStructureStartAt(ServerLevel world, BlockPos pos, Structure structure, boolean computeBox)
{
final ServerChunkCache chunkSource = world.getChunkSource();
final RandomState seed = chunkSource.randomState();
final ChunkGenerator generator = chunkSource.getGenerator();
final ChunkGeneratorStructureState structureState = chunkSource.getGeneratorState();
final List<StructurePlacement> structureConfig = structureState.getPlacementsForStructure(Holder.direct(structure));
final ChunkPos chunkPos = new ChunkPos(pos);
final boolean couldPlace = structureConfig.stream().anyMatch(p -> p.isStructureChunk(structureState, chunkPos.x, chunkPos.z));
ServerChunkCache chunkSource = world.getChunkSource();
RandomState seed = chunkSource.randomState();
ChunkGenerator generator = chunkSource.getGenerator();
ChunkGeneratorStructureState structureState = chunkSource.getGeneratorState();
List<StructurePlacement> structureConfig = structureState.getPlacementsForStructure(Holder.direct(structure));
ChunkPos chunkPos = new ChunkPos(pos);
boolean couldPlace = structureConfig.stream().anyMatch(p -> p.isStructureChunk(structureState, chunkPos.x, chunkPos.z));
if (!couldPlace)
{
return null;
}
final HolderSet<Biome> structureBiomes = structure.biomes();
HolderSet<Biome> structureBiomes = structure.biomes();
if (!computeBox)
{
@@ -259,7 +261,7 @@ public class FeatureGenerator
}
else
{
final StructureStart filledStructure = structure.generate(
StructureStart filledStructure = structure.generate(
world.registryAccess(), generator, generator.getBiomeSource(), seed, world.getStructureManager(),
world.getSeed(), chunkPos, 0, world, structureBiomes::contains);
if (filledStructure != null && filledStructure.isValid())
@@ -270,7 +272,7 @@ public class FeatureGenerator
return null;
}
private static TreeConfiguration.TreeConfigurationBuilder createTree(final Block block, final Block block2, final int i, final int j, final int k, final int l)
private static TreeConfiguration.TreeConfigurationBuilder createTree(Block block, Block block2, int i, int j, int k, int l)
{
return new TreeConfiguration.TreeConfigurationBuilder(BlockStateProvider.simple(block), new StraightTrunkPlacer(i, j, k), BlockStateProvider.simple(block2), new BlobFoliagePlacer(ConstantInt.of(l), ConstantInt.of(0), 3), new TwoLayersFeatureSize(1, 0, 1));
}
@@ -292,13 +294,13 @@ public class FeatureGenerator
PlacementUtils.inlinePlaced(Feature.CORAL_MUSHROOM, FeatureConfiguration.NONE)
))));
put("bastion_remnant_units", l -> {
final RegistryAccess regs = l.registryAccess();
RegistryAccess regs = l.registryAccess();
final HolderGetter<StructureProcessorList> processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST);
final Holder<StructureProcessorList> bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION);
HolderGetter<StructureProcessorList> processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST);
Holder<StructureProcessorList> bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION);
final HolderGetter<StructureTemplatePool> pools = regs.lookupOrThrow(Registries.TEMPLATE_POOL);
final Holder<StructureTemplatePool> empty = pools.getOrThrow(Pools.EMPTY);
HolderGetter<StructureTemplatePool> pools = regs.lookupOrThrow(Registries.TEMPLATE_POOL);
Holder<StructureTemplatePool> empty = pools.getOrThrow(Pools.EMPTY);
return spawnCustomStructure(
@@ -322,13 +324,13 @@ public class FeatureGenerator
);
});
put("bastion_remnant_hoglin_stable", l -> {
final RegistryAccess regs = l.registryAccess();
RegistryAccess regs = l.registryAccess();
final HolderGetter<StructureProcessorList> processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST);
final Holder<StructureProcessorList> bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION);
HolderGetter<StructureProcessorList> processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST);
Holder<StructureProcessorList> bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION);
final HolderGetter<StructureTemplatePool> pools = regs.lookupOrThrow(Registries.TEMPLATE_POOL);
final Holder<StructureTemplatePool> empty = pools.getOrThrow(Pools.EMPTY);
HolderGetter<StructureTemplatePool> pools = regs.lookupOrThrow(Registries.TEMPLATE_POOL);
Holder<StructureTemplatePool> empty = pools.getOrThrow(Pools.EMPTY);
return spawnCustomStructure(
new JigsawStructure(new Structure.StructureSettings(
@@ -351,13 +353,13 @@ public class FeatureGenerator
);
});
put("bastion_remnant_treasure", l -> {
final RegistryAccess regs = l.registryAccess();
RegistryAccess regs = l.registryAccess();
final HolderGetter<StructureProcessorList> processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST);
final Holder<StructureProcessorList> bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION);
HolderGetter<StructureProcessorList> processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST);
Holder<StructureProcessorList> bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION);
final HolderGetter<StructureTemplatePool> pools = regs.lookupOrThrow(Registries.TEMPLATE_POOL);
final Holder<StructureTemplatePool> empty = pools.getOrThrow(Pools.EMPTY);
HolderGetter<StructureTemplatePool> pools = regs.lookupOrThrow(Registries.TEMPLATE_POOL);
Holder<StructureTemplatePool> empty = pools.getOrThrow(Pools.EMPTY);
return spawnCustomStructure(
new JigsawStructure(new Structure.StructureSettings(
@@ -380,13 +382,13 @@ public class FeatureGenerator
);
});
put("bastion_remnant_bridge", l -> {
final RegistryAccess regs = l.registryAccess();
RegistryAccess regs = l.registryAccess();
final HolderGetter<StructureProcessorList> processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST);
final Holder<StructureProcessorList> bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION);
HolderGetter<StructureProcessorList> processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST);
Holder<StructureProcessorList> bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION);
final HolderGetter<StructureTemplatePool> pools = regs.lookupOrThrow(Registries.TEMPLATE_POOL);
final Holder<StructureTemplatePool> empty = pools.getOrThrow(Pools.EMPTY);
HolderGetter<StructureTemplatePool> pools = regs.lookupOrThrow(Registries.TEMPLATE_POOL);
Holder<StructureTemplatePool> empty = pools.getOrThrow(Pools.EMPTY);
return spawnCustomStructure(
new JigsawStructure(new Structure.StructureSettings(
@@ -411,29 +413,29 @@ public class FeatureGenerator
}};
public static boolean plopAnywhere(final Structure structure, final ServerLevel world, final BlockPos pos, final ChunkGenerator generator, final boolean wireOnly)
public static boolean plopAnywhere(Structure structure, ServerLevel world, BlockPos pos, ChunkGenerator generator, boolean wireOnly)
{
final ThreadLocal<Boolean> checks = Vanilla.skipGenerationChecks(world);
ThreadLocal<Boolean> checks = Vanilla.skipGenerationChecks(world);
checks.set(true);
try
{
final StructureStart start = structure.generate(world.registryAccess(), generator, generator.getBiomeSource(), world.getChunkSource().randomState(), world.getStructureManager(), world.getSeed(), new ChunkPos(pos), 0, world, b -> true);
StructureStart start = structure.generate(world.registryAccess(), generator, generator.getBiomeSource(), world.getChunkSource().randomState(), world.getStructureManager(), world.getSeed(), new ChunkPos(pos), 0, world, b -> true);
if (start == StructureStart.INVALID_START)
{
return false;
}
final RandomSource rand = RandomSource.create(world.getRandom().nextInt());
final int j = pos.getX() >> 4;
final int k = pos.getZ() >> 4;
final long chId = ChunkPos.asLong(j, k);
RandomSource rand = RandomSource.create(world.getRandom().nextInt());
int j = pos.getX() >> 4;
int k = pos.getZ() >> 4;
long chId = ChunkPos.asLong(j, k);
world.getChunk(j, k).setStartForStructure(structure, start);
world.getChunk(j, k).addReferenceForStructure(structure, chId);
final BoundingBox box = start.getBoundingBox();
BoundingBox box = start.getBoundingBox();
if (!wireOnly)
{
final Registry<Structure> registry3 = world.registryAccess().registryOrThrow(Registries.STRUCTURE);
Registry<Structure> registry3 = world.registryAccess().registryOrThrow(Registries.STRUCTURE);
world.setCurrentlyGenerating(() -> {
Objects.requireNonNull(structure);
return registry3.getResourceKey(structure).map(Object::toString).orElseGet(structure::toString);
@@ -441,7 +443,7 @@ public class FeatureGenerator
start.placeInChunk(world, world.structureManager(), generator, rand, box, new ChunkPos(j, k));
}
//structurestart.notifyPostProcessAt(new ChunkPos(j, k));
final int i = Math.max(box.getXSpan(), box.getZSpan()) / 16 + 1;
int i = Math.max(box.getXSpan(), box.getZSpan()) / 16 + 1;
//int i = getRadius();
for (int k1 = j - i; k1 <= j + i; ++k1)
@@ -459,7 +461,7 @@ public class FeatureGenerator
}
}
}
catch (final Exception booboo)
catch (Exception booboo)
{
CarpetScriptServer.LOG.error("Unknown Exception while plopping structure: " + booboo, booboo);
return false;
@@ -1,12 +1,13 @@
package carpet.script.utils;
import javax.annotation.Nullable;
import java.util.function.Supplier;
public class GlocalFlag extends ThreadLocal<Boolean>
{
private final boolean initial;
public GlocalFlag(final boolean initial)
public GlocalFlag(boolean initial)
{
this.initial = initial;
}
@@ -24,15 +25,15 @@ public class GlocalFlag extends ThreadLocal<Boolean>
* @param <T> - returned value of that action, whatever that might be
* @return result of the action
*/
public <T> T getWhileDisabled(final Supplier<T> action)
public <T> T getWhileDisabled(Supplier<T> action)
{
return whileValueReturn(!initial, action);
}
private <T> T whileValueReturn(final boolean what, final Supplier<T> action)
private <T> T whileValueReturn(boolean what, Supplier<T> action)
{
T result;
final boolean previous;
boolean previous;
synchronized (this)
{
previous = get();
@@ -49,7 +50,8 @@ public class GlocalFlag extends ThreadLocal<Boolean>
return result;
}
public <T> T runIfEnabled(final Supplier<T> action)
@Nullable
public <T> T runIfEnabled(Supplier<T> action)
{
synchronized (this)
{
@@ -9,9 +9,9 @@ import net.minecraft.resources.ResourceLocation;
public class InputValidator
{
public static String validateSimpleString(final String input, final boolean strict)
public static String validateSimpleString(String input, boolean strict)
{
final String simplified = input.toLowerCase(Locale.ROOT).replaceAll("[^A-Za-z0-9+_]", "");
String simplified = input.toLowerCase(Locale.ROOT).replaceAll("[^A-Za-z0-9+_]", "");
if (simplified.isEmpty() || (strict && !simplified.equals(input)))
{
throw new InternalExpressionException("simple name can only contain numbers, letter and _");
@@ -19,13 +19,13 @@ public class InputValidator
return simplified;
}
public static ResourceLocation identifierOf(final String string)
public static ResourceLocation identifierOf(String string)
{
try
{
return new ResourceLocation(string);
}
catch (final ResourceLocationException iie)
catch (ResourceLocationException iie)
{
throw new InternalExpressionException("Incorrect identifier format '" + string + "': " + iie.getMessage());
}
@@ -7,6 +7,7 @@ import net.minecraft.core.HolderLookup;
import net.minecraft.core.particles.ParticleOptions;
import net.minecraft.core.particles.ParticleType;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
@@ -14,19 +15,20 @@ public class ParticleParser
{
private static final Map<String, ParticleOptions> particleCache = new HashMap<>(); // we reset this on reloads, but probably need something better
private static ParticleOptions parseParticle(final String name, final HolderLookup<ParticleType<?>> lookup)
private static ParticleOptions parseParticle(String name, HolderLookup<ParticleType<?>> lookup)
{
try
{
return ParticleArgument.readParticle(new StringReader(name), lookup);
}
catch (final CommandSyntaxException e)
catch (CommandSyntaxException e)
{
throw new IllegalArgumentException("No such particle: " + name);
}
}
public static ParticleOptions getEffect(final String name, final HolderLookup<ParticleType<?>> lookup)
@Nullable
public static ParticleOptions getEffect(@Nullable String name, HolderLookup<ParticleType<?>> lookup)
{
if (name == null)
{
@@ -24,7 +24,7 @@ public class PerlinNoiseSampler
public static PerlinNoiseSampler instance = new PerlinNoiseSampler(new Random(0));
public static Map<Long, PerlinNoiseSampler> samplers = new Long2ObjectOpenHashMap<>();
public static PerlinNoiseSampler getPerlin(final long aLong)
public static PerlinNoiseSampler getPerlin(long aLong)
{
if (samplers.size() > 256)
{
@@ -33,7 +33,7 @@ public class PerlinNoiseSampler
return samplers.computeIfAbsent(aLong, seed -> new PerlinNoiseSampler(new Random(seed)));
}
public PerlinNoiseSampler(final Random random)
public PerlinNoiseSampler(Random random)
{
this.originX = random.nextDouble() * 256.0D;
this.originY = random.nextDouble() * 256.0D;
@@ -47,27 +47,27 @@ public class PerlinNoiseSampler
}
for (j = 0; j < 256; ++j)
{
final int k = random.nextInt(256 - j);
final byte b = this.permutations[j];
int k = random.nextInt(256 - j);
byte b = this.permutations[j];
this.permutations[j] = this.permutations[j + k];
this.permutations[j + k] = b;
}
}
//3D
public double sample3d(final double x, final double y, final double z)
public double sample3d(double x, double y, double z)
{//, double d, double e) {
final double f = x + this.originX;
final double g = y + this.originY;
final double h = z + this.originZ;
final int i = floor(f);
final int j = floor(g);
final int k = floor(h);
final double l = f - (double) i;
final double m = g - (double) j;
final double n = h - (double) k;
final double o = perlinFade(l);
final double p = perlinFade(m);
final double q = perlinFade(n);
double f = x + this.originX;
double g = y + this.originY;
double h = z + this.originZ;
int i = floor(f);
int j = floor(g);
int k = floor(h);
double l = f - (double) i;
double m = g - (double) j;
double n = h - (double) k;
double o = perlinFade(l);
double p = perlinFade(m);
double q = perlinFade(n);
//double t;
/*
if (d != 0.0D) {
@@ -80,124 +80,124 @@ public class PerlinNoiseSampler
return this.sample3d(i, j, k, l, m, n, o, p, q) / 2 + 0.5;
}
private double sample3d(final int sectionX, final int sectionY, final int sectionZ, final double localX, final double localY, final double localZ, final double fadeLocalX, final double fadeLocalY, final double fadeLocalZ)
private double sample3d(int sectionX, int sectionY, int sectionZ, double localX, double localY, double localZ, double fadeLocalX, double fadeLocalY, double fadeLocalZ)
{
final int i = this.getGradient(sectionX) + sectionY;
final int j = this.getGradient(i) + sectionZ;
final int k = this.getGradient(i + 1) + sectionZ;
final int l = this.getGradient(sectionX + 1) + sectionY;
final int m = this.getGradient(l) + sectionZ;
final int n = this.getGradient(l + 1) + sectionZ;
final double d = grad3d(this.getGradient(j), localX, localY, localZ);
final double e = grad3d(this.getGradient(m), localX - 1.0D, localY, localZ);
final double f = grad3d(this.getGradient(k), localX, localY - 1.0D, localZ);
final double g = grad3d(this.getGradient(n), localX - 1.0D, localY - 1.0D, localZ);
final double h = grad3d(this.getGradient(j + 1), localX, localY, localZ - 1.0D);
final double o = grad3d(this.getGradient(m + 1), localX - 1.0D, localY, localZ - 1.0D);
final double p = grad3d(this.getGradient(k + 1), localX, localY - 1.0D, localZ - 1.0D);
final double q = grad3d(this.getGradient(n + 1), localX - 1.0D, localY - 1.0D, localZ - 1.0D);
int i = this.getGradient(sectionX) + sectionY;
int j = this.getGradient(i) + sectionZ;
int k = this.getGradient(i + 1) + sectionZ;
int l = this.getGradient(sectionX + 1) + sectionY;
int m = this.getGradient(l) + sectionZ;
int n = this.getGradient(l + 1) + sectionZ;
double d = grad3d(this.getGradient(j), localX, localY, localZ);
double e = grad3d(this.getGradient(m), localX - 1.0D, localY, localZ);
double f = grad3d(this.getGradient(k), localX, localY - 1.0D, localZ);
double g = grad3d(this.getGradient(n), localX - 1.0D, localY - 1.0D, localZ);
double h = grad3d(this.getGradient(j + 1), localX, localY, localZ - 1.0D);
double o = grad3d(this.getGradient(m + 1), localX - 1.0D, localY, localZ - 1.0D);
double p = grad3d(this.getGradient(k + 1), localX, localY - 1.0D, localZ - 1.0D);
double q = grad3d(this.getGradient(n + 1), localX - 1.0D, localY - 1.0D, localZ - 1.0D);
return lerp3(fadeLocalX, fadeLocalY, fadeLocalZ, d, e, f, g, h, o, p, q);
}
private static double grad3d(final int hash, final double x, final double y, final double z)
private static double grad3d(int hash, double x, double y, double z)
{
final int i = hash & 15;
int i = hash & 15;
return dot3d(gradients3d[i], x, y, z);
}
protected static double dot3d(final int[] gArr, final double x, final double y, final double z)
protected static double dot3d(int[] gArr, double x, double y, double z)
{
return gArr[0] * x + gArr[1] * y + gArr[2] * z;
}
public static double lerp3(final double deltaX, final double deltaY, final double deltaZ, final double d, final double e, final double f, final double g, final double h, final double i, final double j, final double k)
public static double lerp3(double deltaX, double deltaY, double deltaZ, double d, double e, double f, double g, double h, double i, double j, double k)
{
return lerp(deltaZ, lerp2(deltaX, deltaY, d, e, f, g), lerp2(deltaX, deltaY, h, i, j, k));
}
//2D
public double sample2d(final double x, final double y)
public double sample2d(double x, double y)
{
final double f = x + this.originX;
final double g = y + this.originY;
final int i = floor(f);
final int j = floor(g);
final double l = f - (double) i;
final double m = g - (double) j;
final double o = perlinFade(l);
final double p = perlinFade(m);
double f = x + this.originX;
double g = y + this.originY;
int i = floor(f);
int j = floor(g);
double l = f - (double) i;
double m = g - (double) j;
double o = perlinFade(l);
double p = perlinFade(m);
return this.sample2d(i, j, l, m, o, p) / 2 + 0.5;
}
private double sample2d(final int sectionX, final int sectionY, final double localX, final double localY, final double fadeLocalX, final double fadeLocalY)
private double sample2d(int sectionX, int sectionY, double localX, double localY, double fadeLocalX, double fadeLocalY)
{
final int j = this.getGradient(sectionX) + sectionY;
final int m = this.getGradient(sectionX + 1) + sectionY;
final double d = grad2d(this.getGradient(j), localX, localY);
final double e = grad2d(this.getGradient(m), localX - 1.0D, localY);
final double f = grad2d(this.getGradient(j + 1), localX, localY - 1.0D);
final double g = grad2d(this.getGradient(m + 1), localX - 1.0D, localY - 1.0D);
int j = this.getGradient(sectionX) + sectionY;
int m = this.getGradient(sectionX + 1) + sectionY;
double d = grad2d(this.getGradient(j), localX, localY);
double e = grad2d(this.getGradient(m), localX - 1.0D, localY);
double f = grad2d(this.getGradient(j + 1), localX, localY - 1.0D);
double g = grad2d(this.getGradient(m + 1), localX - 1.0D, localY - 1.0D);
return lerp2(fadeLocalX, fadeLocalY, d, e, f, g);
}
private static double grad2d(final int hash, final double x, final double y)
private static double grad2d(int hash, double x, double y)
{
final int i = hash & 3;
int i = hash & 3;
return dot2d(gradients2d[i], x, y);
}
protected static double dot2d(final int[] gArr, final double x, final double y)
protected static double dot2d(int[] gArr, double x, double y)
{
return gArr[0] * x + gArr[1] * y;
}
public static double lerp2(final double deltaX, final double deltaY, final double d, final double e, final double f, final double g)
public static double lerp2(double deltaX, double deltaY, double d, double e, double f, double g)
{
return lerp(deltaY, lerp(deltaX, d, e), lerp(deltaX, f, g));
}
// 1D
public double sample1d(final double x)
public double sample1d(double x)
{
final double f = x + this.originX;
final int i = floor(f);
final double l = f - i;
final double o = perlinFade(l);
double f = x + this.originX;
int i = floor(f);
double l = f - i;
double o = perlinFade(l);
return this.sample1d(i, l, o) + 0.5;
}
private double sample1d(final int sectionX, final double localX, final double fadeLocalX)
private double sample1d(int sectionX, double localX, double fadeLocalX)
{
final double d = grad1d(this.getGradient(sectionX), localX);
final double e = grad1d(this.getGradient(sectionX + 1), localX - 1.0D);
double d = grad1d(this.getGradient(sectionX), localX);
double e = grad1d(this.getGradient(sectionX + 1), localX - 1.0D);
return lerp(fadeLocalX, d, e);
}
private static double grad1d(final int hash, final double x)
private static double grad1d(int hash, double x)
{
return ((hash & 1) == 0) ? x : -x;
}
public static double lerp(final double delta, final double first, final double second)
public static double lerp(double delta, double first, double second)
{
return first + delta * (second - first);
}
// shared
public int getGradient(final int hash)
public int getGradient(int hash)
{
return this.permutations[hash & 255] & 255;
}
public static double perlinFade(final double d)
public static double perlinFade(double d)
{
return d * d * d * (d * (d * 6.0D - 15.0D) + 10.0D);
}
public static int floor(final double d)
public static int floor(double d)
{
final int i = (int) d;
int i = (int) d;
return d < i ? i - 1 : i;
}
}
@@ -24,12 +24,12 @@ public class ScarpetJsonDeserializer implements JsonDeserializer<Value>
{
@Override
public Value deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException
public Value deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
return parseElement(json);
}
private Value parseElement(final JsonElement element) throws JsonParseException
private Value parseElement(JsonElement element) throws JsonParseException
{
if (element.isJsonObject())
{
@@ -46,21 +46,21 @@ public class ScarpetJsonDeserializer implements JsonDeserializer<Value>
return Value.NULL;
}
private Value parseMap(final JsonObject jsonMap) throws JsonParseException
private Value parseMap(JsonObject jsonMap) throws JsonParseException
{
final Map<Value, Value> map = new HashMap<>();
Map<Value, Value> map = new HashMap<>();
jsonMap.entrySet().forEach(entry -> map.put(new StringValue(entry.getKey()), parseElement(entry.getValue())));
return MapValue.wrap(map);
}
private Value parseList(final JsonArray jsonList) throws JsonParseException
private Value parseList(JsonArray jsonList) throws JsonParseException
{
final List<Value> list = new ArrayList<>();
List<Value> list = new ArrayList<>();
jsonList.forEach(elem -> list.add(parseElement(elem)));
return new ListValue(list);
}
private Value parsePrimitive(final JsonPrimitive primitive) throws JsonParseException
private Value parsePrimitive(JsonPrimitive primitive) throws JsonParseException
{
if (primitive.isString())
{
File diff suppressed because it is too large. Load diff
@@ -73,25 +73,25 @@ public class ShapesRenderer
put("item", (c, s) -> new RenderedSprite(c, s, true));
}};
public ShapesRenderer(final Minecraft minecraftClient)
public ShapesRenderer(Minecraft minecraftClient)
{
this.client = minecraftClient;
shapes = new HashMap<>();
labels = new HashMap<>();
}
public void render(final PoseStack matrices, final Camera camera, final float partialTick)
public void render(PoseStack matrices, Camera camera, float partialTick)
{
final Runnable token = Carpet.startProfilerSection("Scarpet client");
Runnable token = Carpet.startProfilerSection("Scarpet client");
//Camera camera = this.client.gameRenderer.getCamera();
final ClientLevel iWorld = this.client.level;
final ResourceKey<Level> dimensionType = iWorld.dimension();
ClientLevel iWorld = this.client.level;
ResourceKey<Level> dimensionType = iWorld.dimension();
if ((shapes.get(dimensionType) == null || shapes.get(dimensionType).isEmpty()) &&
(labels.get(dimensionType) == null || labels.get(dimensionType).isEmpty()))
{
return;
}
final long currentTime = client.level.getGameTime();
long currentTime = client.level.getGameTime();
RenderSystem.enableDepthTest();
RenderSystem.setShader(GameRenderer::getPositionColorShader);
RenderSystem.depthFunc(515);
@@ -107,21 +107,21 @@ public class ShapesRenderer
//RenderSystem.polygonOffset(-3f, -3f);
//RenderSystem.enablePolygonOffset();
final Tesselator tessellator = Tesselator.getInstance();
final BufferBuilder bufferBuilder = tessellator.getBuilder();
Tesselator tessellator = Tesselator.getInstance();
BufferBuilder bufferBuilder = tessellator.getBuilder();
// render
final double cameraX = camera.getPosition().x;
final double cameraY = camera.getPosition().y;
final double cameraZ = camera.getPosition().z;
final boolean entityBoxes = client.getEntityRenderDispatcher().shouldRenderHitBoxes();
double cameraX = camera.getPosition().x;
double cameraY = camera.getPosition().y;
double cameraZ = camera.getPosition().z;
boolean entityBoxes = client.getEntityRenderDispatcher().shouldRenderHitBoxes();
if (shapes.size() != 0)
if (!shapes.isEmpty())
{
shapes.get(dimensionType).long2ObjectEntrySet().removeIf(
entry -> entry.getValue().isExpired(currentTime)
);
final PoseStack matrixStack = RenderSystem.getModelViewStack();
PoseStack matrixStack = RenderSystem.getModelViewStack();
matrixStack.pushPose();
matrixStack.mulPoseMatrix(matrices.last().pose());
RenderSystem.applyModelViewMatrix();
@@ -147,7 +147,7 @@ public class ShapesRenderer
RenderSystem.applyModelViewMatrix();
}
if (labels.size() != 0)
if (!labels.isEmpty())
{
labels.get(dimensionType).long2ObjectEntrySet().removeIf(
entry -> entry.getValue().isExpired(currentTime)
@@ -166,9 +166,9 @@ public class ShapesRenderer
token.run();
}
public void addShapes(final ListTag tag)
public void addShapes(ListTag tag)
{
final Runnable token = Carpet.startProfilerSection("Scarpet client");
Runnable token = Carpet.startProfilerSection("Scarpet client");
for (int i = 0, count = tag.size(); i < count; i++)
{
addShape(tag.getCompound(i));
@@ -176,14 +176,14 @@ public class ShapesRenderer
token.run();
}
public void addShape(final CompoundTag tag)
public void addShape(CompoundTag tag)
{
final ShapeDispatcher.ExpiringShape shape = ShapeDispatcher.fromTag(tag, client.level);
ShapeDispatcher.ExpiringShape shape = ShapeDispatcher.fromTag(tag, client.level);
if (shape == null)
{
return;
}
final BiFunction<Minecraft, ShapeDispatcher.ExpiringShape, RenderedShape<? extends ShapeDispatcher.ExpiringShape>> shapeFactory;
BiFunction<Minecraft, ShapeDispatcher.ExpiringShape, RenderedShape<? extends ShapeDispatcher.ExpiringShape>> shapeFactory;
shapeFactory = renderedShapes.get(tag.getString("shape"));
if (shapeFactory == null)
{
@@ -191,12 +191,12 @@ public class ShapesRenderer
}
else
{
final RenderedShape<?> rshape = shapeFactory.apply(client, shape);
final ResourceKey<Level> dim = shape.shapeDimension;
final long key = rshape.key();
final Map<ResourceKey<Level>, Long2ObjectOpenHashMap<RenderedShape<? extends ShapeDispatcher.ExpiringShape>>> container =
RenderedShape<?> rshape = shapeFactory.apply(client, shape);
ResourceKey<Level> dim = shape.shapeDimension;
long key = rshape.key();
Map<ResourceKey<Level>, Long2ObjectOpenHashMap<RenderedShape<? extends ShapeDispatcher.ExpiringShape>>> container =
rshape.stageDeux() ? labels : shapes;
final RenderedShape<?> existing = container.computeIfAbsent(dim, d -> new Long2ObjectOpenHashMap<>()).get(key);
RenderedShape<?> existing = container.computeIfAbsent(dim, d -> new Long2ObjectOpenHashMap<>()).get(key);
if (existing != null)
{ // promoting previous shape
existing.promoteWith(rshape);
@@ -217,7 +217,7 @@ public class ShapesRenderer
public void renewShapes()
{
final Runnable token = Carpet.startProfilerSection("Scarpet client");
Runnable token = Carpet.startProfilerSection("Scarpet client");
shapes.values().forEach(el -> el.values().forEach(shape -> shape.expiryTick++));
labels.values().forEach(el -> el.values().forEach(shape -> shape.expiryTick++));
@@ -229,15 +229,15 @@ public class ShapesRenderer
protected T shape;
protected Minecraft client;
long expiryTick;
double renderEpsilon = 0;
double renderEpsilon;
public abstract void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder builder, double cx, double cy, double cz, float partialTick);
public void renderFaces(final Tesselator tessellator, final BufferBuilder builder, final double cx, final double cy, final double cz, final float partialTick)
public void renderFaces(Tesselator tessellator, BufferBuilder builder, double cx, double cy, double cz, float partialTick)
{
}
protected RenderedShape(final Minecraft client, final T shape)
protected RenderedShape(Minecraft client, T shape)
{
this.shape = shape;
this.client = client;
@@ -245,7 +245,7 @@ public class ShapesRenderer
renderEpsilon = (3 + ((double) key()) / Long.MAX_VALUE) / 1000;
}
public boolean isExpired(final long currentTick)
public boolean isExpired(long currentTick)
{
return expiryTick < currentTick;
}
@@ -255,7 +255,7 @@ public class ShapesRenderer
return shape.key(client.level.registryAccess());
}
public boolean shouldRender(final ResourceKey<Level> dim)
public boolean shouldRender(ResourceKey<Level> dim)
{
if (shape.followEntity <= 0)
{
@@ -277,7 +277,7 @@ public class ShapesRenderer
return false;
}
public void promoteWith(final RenderedShape<?> rshape)
public void promoteWith(RenderedShape<?> rshape)
{
expiryTick = rshape.expiryTick;
}
@@ -293,7 +293,7 @@ public class ShapesRenderer
private BlockState blockState;
private BlockEntity BlockEntity = null;
protected RenderedSprite(final Minecraft client, final ShapeDispatcher.ExpiringShape shape, final boolean isitem)
protected RenderedSprite(Minecraft client, ShapeDispatcher.ExpiringShape shape, boolean isitem)
{
super(client, (ShapeDispatcher.DisplayedSprite) shape);
this.isitem = isitem;
@@ -304,16 +304,16 @@ public class ShapesRenderer
}
@Override
public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder builder, final double cx, final double cy,
final double cz, final float partialTick)
public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder builder, double cx, double cy,
double cz, float partialTick)
{
if (shape.a == 0.0)
{
return;
}
final Vec3 v1 = shape.relativiseRender(client.level, shape.pos, partialTick);
final Camera camera1 = client.gameRenderer.getMainCamera();
Vec3 v1 = shape.relativiseRender(client.level, shape.pos, partialTick);
Camera camera1 = client.gameRenderer.getMainCamera();
matrices.pushPose();
if (!isitem)// blocks should use its center as the origin
@@ -364,20 +364,20 @@ public class ShapesRenderer
blockState = shape.blockState;
final MultiBufferSource.BufferSource immediate = client.renderBuffers().bufferSource();
MultiBufferSource.BufferSource immediate = client.renderBuffers().bufferSource();
if (!isitem)
{
// draw the block itself
if (blockState.getRenderShape() == RenderShape.MODEL)
{
final var bakedModel = client.getBlockRenderer().getBlockModel(blockState);
final int color = client.getBlockColors().getColor(blockState, client.level, blockPos, 0);
var bakedModel = client.getBlockRenderer().getBlockModel(blockState);
int color = client.getBlockColors().getColor(blockState, client.level, blockPos, 0);
//dont know why there is a 0.
//see https://github.com/senseiwells/EssentialClient/blob/4db1f291936f502304791ee323f369c206b3021d/src/main/java/me/senseiwells/essentialclient/utils/render/RenderHelper.java#L464
final float red = (color >> 16 & 0xFF) / 255.0F;
final float green = (color >> 8 & 0xFF) / 255.0F;
final float blue = (color & 0xFF) / 255.0F;
float red = (color >> 16 & 0xFF) / 255.0F;
float green = (color >> 8 & 0xFF) / 255.0F;
float blue = (color & 0xFF) / 255.0F;
client.getBlockRenderer().getModelRenderer().renderModel(matrices.last(), immediate.getBuffer(ItemBlockRenderTypes.getRenderType(blockState, false)), blockState, bakedModel, red, green, blue, light, OverlayTexture.NO_OVERLAY);
}
@@ -406,7 +406,7 @@ public class ShapesRenderer
{
if (BlockEntity != null)
{
final BlockEntityRenderer<BlockEntity> blockEntityRenderer = client.getBlockEntityRenderDispatcher().getRenderer(BlockEntity);
BlockEntityRenderer<BlockEntity> blockEntityRenderer = client.getBlockEntityRenderDispatcher().getRenderer(BlockEntity);
if (blockEntityRenderer != null)
{
blockEntityRenderer.render(BlockEntity, partialTick,
@@ -440,19 +440,19 @@ public class ShapesRenderer
}
// copy and modifiy a bit from net.minecraft.client.renderer.blockentity.ShulkerBoxRenderer.render
public void sbrender(final ShulkerBoxBlockEntity shulkerBoxBlockEntity, final float f, final PoseStack poseStack, final MultiBufferSource multiBufferSource, final int i, final int j)
public void sbrender(ShulkerBoxBlockEntity shulkerBoxBlockEntity, float f, PoseStack poseStack, MultiBufferSource multiBufferSource, int i, int j)
{
Direction direction = Direction.UP;
if (shulkerBoxBlockEntity.hasLevel())
{
final BlockState blockState = shulkerBoxBlockEntity.getBlockState();
BlockState blockState = shulkerBoxBlockEntity.getBlockState();
if (blockState.getBlock() instanceof ShulkerBoxBlock)
{
direction = blockState.getValue(ShulkerBoxBlock.FACING);
}
}
final DyeColor dyeColor = shulkerBoxBlockEntity.getColor();
final Material material;
DyeColor dyeColor = shulkerBoxBlockEntity.getColor();
Material material;
if (dyeColor == null)
{
material = Sheets.DEFAULT_SHULKER_TEXTURE_LOCATION;
@@ -468,11 +468,11 @@ public class ShapesRenderer
poseStack.mulPose(direction.getRotation());
poseStack.scale(1.0F, -1.0F, -1.0F);
poseStack.translate(0.0, -1.0, 0.0);
final ShulkerModel<?> model = VanillaClient.ShulkerBoxRenderer_model(client.getBlockEntityRenderDispatcher().getRenderer(shulkerBoxBlockEntity));
final ModelPart modelPart = model.getLid();
ShulkerModel<?> model = VanillaClient.ShulkerBoxRenderer_model(client.getBlockEntityRenderDispatcher().getRenderer(shulkerBoxBlockEntity));
ModelPart modelPart = model.getLid();
modelPart.setPos(0.0F, 24.0F - shulkerBoxBlockEntity.getProgress(f) * 0.5F * 16.0F, 0.0F);
modelPart.yRot = 270.0F * shulkerBoxBlockEntity.getProgress(f) * (float) (Math.PI / 180.0);
final VertexConsumer vertexConsumer = material.buffer(multiBufferSource, RenderType::entityCutoutNoCull);
VertexConsumer vertexConsumer = material.buffer(multiBufferSource, RenderType::entityCutoutNoCull);
model.renderToBuffer(poseStack, vertexConsumer, i, j, 1.0F, 1.0F, 1.0F, 1.0F);
poseStack.popPose();
}
@@ -482,21 +482,21 @@ public class ShapesRenderer
public static class RenderedText extends RenderedShape<ShapeDispatcher.DisplayedText>
{
protected RenderedText(final Minecraft client, final ShapeDispatcher.ExpiringShape shape)
protected RenderedText(Minecraft client, ShapeDispatcher.ExpiringShape shape)
{
super(client, (ShapeDispatcher.DisplayedText) shape);
}
@Override
public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder builder, final double cx, final double cy, final double cz, final float partialTick)
public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder builder, double cx, double cy, double cz, float partialTick)
{
if (shape.a == 0.0)
{
return;
}
final Vec3 v1 = shape.relativiseRender(client.level, shape.pos, partialTick);
final Camera camera1 = client.gameRenderer.getMainCamera();
final Font textRenderer = client.font;
Vec3 v1 = shape.relativiseRender(client.level, shape.pos, partialTick);
Camera camera1 = client.gameRenderer.getMainCamera();
Font textRenderer = client.font;
if (shape.doublesided)
{
RenderSystem.disableCull();
@@ -538,7 +538,7 @@ public class ShapesRenderer
{
text_x = (float) (-textRenderer.width(shape.value.getString()));
}
final MultiBufferSource.BufferSource immediate = MultiBufferSource.immediate(builder);
MultiBufferSource.BufferSource immediate = MultiBufferSource.immediate(builder);
textRenderer.drawInBatch(shape.value, text_x, 0.0F, shape.textcolor, false, matrices.last().pose(), immediate, false, shape.textbck, 15728880);
immediate.endBatch();
matrices.popPose();
@@ -552,14 +552,14 @@ public class ShapesRenderer
}
@Override
public void promoteWith(final RenderedShape<?> rshape)
public void promoteWith(RenderedShape<?> rshape)
{
super.promoteWith(rshape);
try
{
this.shape.value = ((ShapeDispatcher.DisplayedText) rshape.shape).value;
}
catch (final ClassCastException ignored)
catch (ClassCastException ignored)
{
CarpetScriptServer.LOG.error("shape " + rshape.shape.getClass() + " cannot cast to a Label");
}
@@ -569,20 +569,20 @@ public class ShapesRenderer
public static class RenderedBox extends RenderedShape<ShapeDispatcher.Box>
{
private RenderedBox(final Minecraft client, final ShapeDispatcher.ExpiringShape shape)
private RenderedBox(Minecraft client, ShapeDispatcher.ExpiringShape shape)
{
super(client, (ShapeDispatcher.Box) shape);
}
@Override
public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick)
public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick)
{
if (shape.a == 0.0)
{
return;
}
final Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick);
final Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick);
Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick);
Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick);
drawBoxWireGLLines(tessellator, bufferBuilder,
(float) (v1.x - cx - renderEpsilon), (float) (v1.y - cy - renderEpsilon), (float) (v1.z - cz - renderEpsilon),
(float) (v2.x - cx + renderEpsilon), (float) (v2.y - cy + renderEpsilon), (float) (v2.z - cz + renderEpsilon),
@@ -592,14 +592,14 @@ public class ShapesRenderer
}
@Override
public void renderFaces(final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick)
public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick)
{
if (shape.fa == 0.0)
{
return;
}
final Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick);
final Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick);
Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick);
Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick);
// consider using built-ins
//DebugRenderer.drawBox(new Box(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z), 0.5f, 0.5f, 0.5f, 0.5f);//shape.r, shape.g, shape.b, shape.a);
drawBoxFaces(tessellator, bufferBuilder,
@@ -613,16 +613,16 @@ public class ShapesRenderer
public static class RenderedLine extends RenderedShape<ShapeDispatcher.Line>
{
public RenderedLine(final Minecraft client, final ShapeDispatcher.ExpiringShape shape)
public RenderedLine(Minecraft client, ShapeDispatcher.ExpiringShape shape)
{
super(client, (ShapeDispatcher.Line) shape);
}
@Override
public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick)
public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick)
{
final Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick);
final Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick);
Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick);
Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick);
drawLine(tessellator, bufferBuilder,
(float) (v1.x - cx - renderEpsilon), (float) (v1.y - cy - renderEpsilon), (float) (v1.z - cz - renderEpsilon),
(float) (v2.x - cx + renderEpsilon), (float) (v2.y - cy + renderEpsilon), (float) (v2.z - cz + renderEpsilon),
@@ -636,13 +636,13 @@ public class ShapesRenderer
private static final VertexFormat.Mode[] faceIndices = new VertexFormat.Mode[]{
Mode.LINES, Mode.LINE_STRIP, Mode.DEBUG_LINES, Mode.DEBUG_LINE_STRIP, Mode.TRIANGLES, Mode.TRIANGLE_STRIP, Mode.TRIANGLE_FAN, Mode.QUADS};
public RenderedPolyface(final Minecraft client, final ShapeDispatcher.ExpiringShape shape)
public RenderedPolyface(Minecraft client, ShapeDispatcher.ExpiringShape shape)
{
super(client, (ShapeDispatcher.Polyface) shape);
}
@Override
public void renderFaces(final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick)
public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick)
{
if (shape.fa == 0)
{
@@ -659,9 +659,9 @@ public class ShapesRenderer
}
bufferBuilder.begin(faceIndices[shape.mode], DefaultVertexFormat.POSITION_COLOR);
for (int i = 0; i < shape.vertex_list.size(); i++)
for (int i = 0; i < shape.vertexList.size(); i++)
{
Vec3 vec = shape.vertex_list.get(i);
Vec3 vec = shape.vertexList.get(i);
if (shape.relative.get(i))
{
vec = shape.relativiseRender(client.level, vec, partialTick);
@@ -678,8 +678,8 @@ public class ShapesRenderer
}
@Override
public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder builder, final double cx, final double cy,
final double cz, final float partialTick)
public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder builder, double cx, double cy,
double cz, float partialTick)
{
if (shape.a == 0)
{
@@ -690,9 +690,9 @@ public class ShapesRenderer
{
builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR);
Vec3 vec0 = null;
for (int i = 0; i < shape.vertex_list.size(); i++)
for (int i = 0; i < shape.vertexList.size(); i++)
{
Vec3 vec = shape.vertex_list.get(i);
Vec3 vec = shape.vertexList.get(i);
if (shape.relative.get(i))
{
vec = shape.relativiseRender(client.level, vec, partialTick);
@@ -708,9 +708,9 @@ public class ShapesRenderer
if (shape.inneredges)
{
builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR);
for (int i = 1; i < shape.vertex_list.size() - 1; i++)
for (int i = 1; i < shape.vertexList.size() - 1; i++)
{
Vec3 vec = shape.vertex_list.get(i);
Vec3 vec = shape.vertexList.get(i);
if (shape.relative.get(i))
{
vec = shape.relativiseRender(client.level, vec, partialTick);
@@ -726,26 +726,26 @@ public class ShapesRenderer
if (shape.mode == 5)
{
builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR);
Vec3 vec = shape.vertex_list.get(1);
Vec3 vec = shape.vertexList.get(1);
if (shape.relative.get(1))
{
vec = shape.relativiseRender(client.level, vec, partialTick);
}
builder.vertex(vec.x() - cx, vec.y() - cy, vec.z() - cz).color(shape.r, shape.g, shape.b, shape.a).endVertex();
int i;
for (i = 0; i < shape.vertex_list.size(); i += 2)
for (i = 0; i < shape.vertexList.size(); i += 2)
{
vec = shape.vertex_list.get(i);
vec = shape.vertexList.get(i);
if (shape.relative.get(i))
{
vec = shape.relativiseRender(client.level, vec, partialTick);
}
builder.vertex(vec.x() - cx, vec.y() - cy, vec.z() - cz).color(shape.r, shape.g, shape.b, shape.a).endVertex();
}
i = shape.vertex_list.size() - 1;
i = shape.vertexList.size() - 1;
for (i -= 1 - i % 2; i > 0; i -= 2)
{
vec = shape.vertex_list.get(i);
vec = shape.vertexList.get(i);
if (shape.relative.get(i))
{
vec = shape.relativiseRender(client.level, vec, partialTick);
@@ -754,9 +754,9 @@ public class ShapesRenderer
}
if (shape.inneredges)
{
for (i = 2; i < shape.vertex_list.size() - 1; i++)
for (i = 2; i < shape.vertexList.size() - 1; i++)
{
vec = shape.vertex_list.get(i);
vec = shape.vertexList.get(i);
if (shape.relative.get(i))
{
vec = shape.relativiseRender(client.level, vec, partialTick);
@@ -770,21 +770,21 @@ public class ShapesRenderer
if (shape.mode == 4)
{
builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR);
for (int i = 0; i < shape.vertex_list.size(); i++)
for (int i = 0; i < shape.vertexList.size(); i++)
{
Vec3 vecA = shape.vertex_list.get(i);
Vec3 vecA = shape.vertexList.get(i);
if (shape.relative.get(i))
{
vecA = shape.relativiseRender(client.level, vecA, partialTick);
}
i++;
Vec3 vecB = shape.vertex_list.get(i);
Vec3 vecB = shape.vertexList.get(i);
if (shape.relative.get(i))
{
vecB = shape.relativiseRender(client.level, vecB, partialTick);
}
i++;
Vec3 vecC = shape.vertex_list.get(i);
Vec3 vecC = shape.vertexList.get(i);
if (shape.relative.get(i))
{
vecC = shape.relativiseRender(client.level, vecC, partialTick);
@@ -805,19 +805,19 @@ public class ShapesRenderer
public static class RenderedSphere extends RenderedShape<ShapeDispatcher.Sphere>
{
public RenderedSphere(final Minecraft client, final ShapeDispatcher.ExpiringShape shape)
public RenderedSphere(Minecraft client, ShapeDispatcher.ExpiringShape shape)
{
super(client, (ShapeDispatcher.Sphere) shape);
}
@Override
public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick)
public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick)
{
if (shape.a == 0.0)
{
return;
}
final Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick);
Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick);
drawSphereWireframe(tessellator, bufferBuilder,
(float) (vc.x - cx), (float) (vc.y - cy), (float) (vc.z - cz),
(float) (shape.radius + renderEpsilon), shape.subdivisions,
@@ -825,13 +825,13 @@ public class ShapesRenderer
}
@Override
public void renderFaces(final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick)
public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick)
{
if (shape.fa == 0.0)
{
return;
}
final Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick);
Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick);
drawSphereFaces(tessellator, bufferBuilder,
(float) (vc.x - cx), (float) (vc.y - cy), (float) (vc.z - cz),
(float) (shape.radius + renderEpsilon), shape.subdivisions,
@@ -841,20 +841,20 @@ public class ShapesRenderer
public static class RenderedCylinder extends RenderedShape<ShapeDispatcher.Cylinder>
{
public RenderedCylinder(final Minecraft client, final ShapeDispatcher.ExpiringShape shape)
public RenderedCylinder(Minecraft client, ShapeDispatcher.ExpiringShape shape)
{
super(client, (ShapeDispatcher.Cylinder) shape);
}
@Override
public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick)
public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick)
{
if (shape.a == 0.0)
{
return;
}
final Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick);
final double dir = Mth.sign(shape.height);
Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick);
double dir = Mth.sign(shape.height);
drawCylinderWireframe(tessellator, bufferBuilder,
(float) (vc.x - cx - dir * renderEpsilon), (float) (vc.y - cy - dir * renderEpsilon), (float) (vc.z - cz - dir * renderEpsilon),
(float) (shape.radius + renderEpsilon), (float) (shape.height + 2 * dir * renderEpsilon), shape.axis,
@@ -864,14 +864,14 @@ public class ShapesRenderer
}
@Override
public void renderFaces(final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick)
public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick)
{
if (shape.fa == 0.0)
{
return;
}
final Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick);
final double dir = Mth.sign(shape.height);
Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick);
double dir = Mth.sign(shape.height);
drawCylinderFaces(tessellator, bufferBuilder,
(float) (vc.x - cx - dir * renderEpsilon), (float) (vc.y - cy - dir * renderEpsilon), (float) (vc.z - cz - dir * renderEpsilon),
(float) (shape.radius + renderEpsilon), (float) (shape.height + 2 * dir * renderEpsilon), shape.axis,
@@ -882,7 +882,7 @@ public class ShapesRenderer
// some raw shit
public static void drawLine(final Tesselator tessellator, final BufferBuilder builder, final float x1, final float y1, final float z1, final float x2, final float y2, final float z2, final float red1, final float grn1, final float blu1, final float alpha)
public static void drawLine(Tesselator tessellator, BufferBuilder builder, float x1, float y1, float z1, float x2, float y2, float z2, float red1, float grn1, float blu1, float alpha)
{
builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR);
builder.vertex(x1, y1, z1).color(red1, grn1, blu1, alpha).endVertex();
@@ -891,11 +891,11 @@ public class ShapesRenderer
}
public static void drawBoxWireGLLines(
final Tesselator tessellator, final BufferBuilder builder,
final float x1, final float y1, final float z1,
final float x2, final float y2, final float z2,
final boolean xthick, final boolean ythick, final boolean zthick,
final float red1, final float grn1, final float blu1, final float alpha, final float red2, final float grn2, final float blu2)
Tesselator tessellator, BufferBuilder builder,
float x1, float y1, float z1,
float x2, float y2, float z2,
boolean xthick, boolean ythick, boolean zthick,
float red1, float grn1, float blu1, float alpha, float red2, float grn2, float blu2)
{
builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR);
if (xthick)
@@ -944,11 +944,11 @@ public class ShapesRenderer
}
public static void drawBoxFaces(
final Tesselator tessellator, final BufferBuilder builder,
final float x1, final float y1, final float z1,
final float x2, final float y2, final float z2,
final boolean xthick, final boolean ythick, final boolean zthick,
final float red1, final float grn1, final float blu1, final float alpha)
Tesselator tessellator, BufferBuilder builder,
float x1, float y1, float z1,
float x2, float y2, float z2,
boolean xthick, boolean ythick, boolean zthick,
float red1, float grn1, float blu1, float alpha)
{
builder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);
@@ -1004,14 +1004,14 @@ public class ShapesRenderer
tessellator.end();
}
public static void drawCylinderWireframe(final Tesselator tessellator, final BufferBuilder builder,
final float cx, final float cy, final float cz,
final float r, final float h, final Direction.Axis axis, final int subd, final boolean isFlat,
final float red, final float grn, final float blu, final float alpha)
public static void drawCylinderWireframe(Tesselator tessellator, BufferBuilder builder,
float cx, float cy, float cz,
float r, float h, Direction.Axis axis, int subd, boolean isFlat,
float red, float grn, float blu, float alpha)
{
final float step = (float) Math.PI / (subd / 2);
final int num_steps180 = (int) (Math.PI / step) + 1;
final int num_steps360 = (int) (2 * Math.PI / step);
float step = (float) Math.PI / (subd / 2);
int num_steps180 = (int) (Math.PI / step) + 1;
int num_steps360 = (int) (2 * Math.PI / step);
int hsteps = 1;
float hstep = 1.0f;
if (!isFlat)
@@ -1024,14 +1024,14 @@ public class ShapesRenderer
{
for (int dh = 0; dh < hsteps; dh++)
{
final float hh = dh * hstep;
float hh = dh * hstep;
builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip
for (int i = 0; i <= num_steps360 + 1; i++)
{
final float theta = step * i;
final float x = r * Mth.cos(theta);
final float y = hh;
final float z = r * Mth.sin(theta);
float theta = step * i;
float x = r * Mth.cos(theta);
float y = hh;
float z = r * Mth.sin(theta);
builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex();
}
tessellator.end();
@@ -1042,10 +1042,10 @@ public class ShapesRenderer
for (int i = 0; i <= num_steps180; i++)
{
builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip
final float theta = step * i;
final float x = r * Mth.cos(theta);
float theta = step * i;
float x = r * Mth.cos(theta);
final float z = r * Mth.sin(theta);
float z = r * Mth.sin(theta);
builder.vertex(cx - x, cy + 0, cz + z).color(red, grn, blu, alpha).endVertex();
builder.vertex(cx + x, cy + 0, cz - z).color(red, grn, blu, alpha).endVertex();
@@ -1060,9 +1060,9 @@ public class ShapesRenderer
builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR);
for (int i = 0; i <= num_steps180; i++)
{
final float theta = step * i;
final float x = r * Mth.cos(theta);
final float z = r * Mth.sin(theta);
float theta = step * i;
float x = r * Mth.cos(theta);
float z = r * Mth.sin(theta);
builder.vertex(cx - x, cy, cz + z).color(red, grn, blu, alpha).endVertex();
builder.vertex(cx + x, cy, cz - z).color(red, grn, blu, alpha).endVertex();
}
@@ -1074,14 +1074,14 @@ public class ShapesRenderer
{
for (int dh = 0; dh < hsteps; dh++)
{
final float hh = dh * hstep;
float hh = dh * hstep;
builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip
for (int i = 0; i <= num_steps360; i++)
{
final float theta = step * i;
final float z = r * Mth.cos(theta);
final float x = hh;
final float y = r * Mth.sin(theta);
float theta = step * i;
float z = r * Mth.cos(theta);
float x = hh;
float y = r * Mth.sin(theta);
builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex();
}
tessellator.end();
@@ -1092,10 +1092,10 @@ public class ShapesRenderer
for (int i = 0; i <= num_steps180; i++)
{
builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip
final float theta = step * i;
final float y = r * Mth.cos(theta);
float theta = step * i;
float y = r * Mth.cos(theta);
final float z = r * Mth.sin(theta);
float z = r * Mth.sin(theta);
builder.vertex(cx + 0, cy - y, cz + z).color(red, grn, blu, alpha).endVertex();
builder.vertex(cx + 0, cy + y, cz - z).color(red, grn, blu, alpha).endVertex();
@@ -1109,9 +1109,9 @@ public class ShapesRenderer
builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR);
for (int i = 0; i <= num_steps180; i++)
{
final float theta = step * i;
final float y = r * Mth.cos(theta);
final float z = r * Mth.sin(theta);
float theta = step * i;
float y = r * Mth.cos(theta);
float z = r * Mth.sin(theta);
builder.vertex(cx, cy - y, cz + z).color(red, grn, blu, alpha).endVertex();
builder.vertex(cx, cy + y, cz - z).color(red, grn, blu, alpha).endVertex();
}
@@ -1122,14 +1122,14 @@ public class ShapesRenderer
{
for (int dh = 0; dh < hsteps; dh++)
{
final float hh = dh * hstep;
float hh = dh * hstep;
builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip
for (int i = 0; i <= num_steps360; i++)
{
final float theta = step * i;
final float y = r * Mth.cos(theta);
final float z = hh;
final float x = r * Mth.sin(theta);
float theta = step * i;
float y = r * Mth.cos(theta);
float z = hh;
float x = r * Mth.sin(theta);
builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex();
}
tessellator.end();
@@ -1139,10 +1139,10 @@ public class ShapesRenderer
for (int i = 0; i <= num_steps180; i++)
{
builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip
final float theta = step * i;
final float x = r * Mth.cos(theta);
float theta = step * i;
float x = r * Mth.cos(theta);
final float y = r * Mth.sin(theta);
float y = r * Mth.sin(theta);
builder.vertex(cx + x, cy - y, cz + 0).color(red, grn, blu, alpha).endVertex();
builder.vertex(cx - x, cy + y, cz + 0).color(red, grn, blu, alpha).endVertex();
@@ -1156,9 +1156,9 @@ public class ShapesRenderer
builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR);
for (int i = 0; i <= num_steps180; i++)
{
final float theta = step * i;
final float x = r * Mth.cos(theta);
final float y = r * Mth.sin(theta);
float theta = step * i;
float x = r * Mth.cos(theta);
float y = r * Mth.sin(theta);
builder.vertex(cx + x, cy - y, cz).color(red, grn, blu, alpha).endVertex();
builder.vertex(cx - x, cy + y, cz).color(red, grn, blu, alpha).endVertex();
}
@@ -1168,14 +1168,14 @@ public class ShapesRenderer
}
}
public static void drawCylinderFaces(final Tesselator tessellator, final BufferBuilder builder,
final float cx, final float cy, final float cz,
final float r, final float h, final Direction.Axis axis, final int subd, final boolean isFlat,
final float red, final float grn, final float blu, final float alpha)
public static void drawCylinderFaces(Tesselator tessellator, BufferBuilder builder,
float cx, float cy, float cz,
float r, float h, Direction.Axis axis, int subd, boolean isFlat,
float red, float grn, float blu, float alpha)
{
final float step = (float) Math.PI / (subd / 2);
float step = (float) Math.PI / (subd / 2);
//final int num_steps180 = (int) (Math.PI / step) + 1;
final int num_steps360 = (int) (2 * Math.PI / step) + 1;
int num_steps360 = (int) (2 * Math.PI / step) + 1;
if (axis == Direction.Axis.Y)
{
@@ -1184,9 +1184,9 @@ public class ShapesRenderer
builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).endVertex();
for (int i = 0; i <= num_steps360; i++)
{
final float theta = step * i;
final float x = r * Mth.cos(theta);
final float z = r * Mth.sin(theta);
float theta = step * i;
float x = r * Mth.cos(theta);
float z = r * Mth.sin(theta);
builder.vertex(x + cx, cy, z + cz).color(red, grn, blu, alpha).endVertex();
}
tessellator.end();
@@ -1196,9 +1196,9 @@ public class ShapesRenderer
builder.vertex(cx, cy + h, cz).color(red, grn, blu, alpha).endVertex();
for (int i = 0; i <= num_steps360; i++)
{
final float theta = step * i;
final float x = r * Mth.cos(theta);
final float z = r * Mth.sin(theta);
float theta = step * i;
float x = r * Mth.cos(theta);
float z = r * Mth.sin(theta);
builder.vertex(x + cx, cy + h, z + cz).color(red, grn, blu, alpha).endVertex();
}
tessellator.end();
@@ -1208,9 +1208,9 @@ public class ShapesRenderer
float zp = r * 0;
for (int i = 1; i <= num_steps360; i++)
{
final float theta = step * i;
final float x = r * Mth.cos(theta);
final float z = r * Mth.sin(theta);
float theta = step * i;
float x = r * Mth.cos(theta);
float z = r * Mth.sin(theta);
builder.vertex(cx + xp, cy + 0, cz + zp).color(red, grn, blu, alpha).endVertex();
builder.vertex(cx + xp, cy + h, cz + zp).color(red, grn, blu, alpha).endVertex();
builder.vertex(cx + x, cy + h, cz + z).color(red, grn, blu, alpha).endVertex();
@@ -1228,9 +1228,9 @@ public class ShapesRenderer
builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).endVertex();
for (int i = 0; i <= num_steps360; i++)
{
final float theta = step * i;
final float y = r * Mth.cos(theta);
final float z = r * Mth.sin(theta);
float theta = step * i;
float y = r * Mth.cos(theta);
float z = r * Mth.sin(theta);
builder.vertex(cx, cy + y, z + cz).color(red, grn, blu, alpha).endVertex();
}
tessellator.end();
@@ -1240,9 +1240,9 @@ public class ShapesRenderer
builder.vertex(cx + h, cy, cz).color(red, grn, blu, alpha).endVertex();
for (int i = 0; i <= num_steps360; i++)
{
final float theta = step * i;
final float y = r * Mth.cos(theta);
final float z = r * Mth.sin(theta);
float theta = step * i;
float y = r * Mth.cos(theta);
float z = r * Mth.sin(theta);
builder.vertex(cx + h, cy + y, cz + z).color(red, grn, blu, alpha).endVertex();
}
tessellator.end();
@@ -1252,9 +1252,9 @@ public class ShapesRenderer
float zp = r * 0;
for (int i = 1; i <= num_steps360; i++)
{
final float theta = step * i;
final float y = r * Mth.cos(theta);
final float z = r * Mth.sin(theta);
float theta = step * i;
float y = r * Mth.cos(theta);
float z = r * Mth.sin(theta);
builder.vertex(cx + 0, cy + yp, cz + zp).color(red, grn, blu, alpha).endVertex();
builder.vertex(cx + h, cy + yp, cz + zp).color(red, grn, blu, alpha).endVertex();
builder.vertex(cx + h, cy + y, cz + z).color(red, grn, blu, alpha).endVertex();
@@ -1271,9 +1271,9 @@ public class ShapesRenderer
builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).endVertex();
for (int i = 0; i <= num_steps360; i++)
{
final float theta = step * i;
final float x = r * Mth.cos(theta);
final float y = r * Mth.sin(theta);
float theta = step * i;
float x = r * Mth.cos(theta);
float y = r * Mth.sin(theta);
builder.vertex(x + cx, cy + y, cz).color(red, grn, blu, alpha).endVertex();
}
tessellator.end();
@@ -1283,9 +1283,9 @@ public class ShapesRenderer
builder.vertex(cx, cy, cz + h).color(red, grn, blu, alpha).endVertex();
for (int i = 0; i <= num_steps360; i++)
{
final float theta = step * i;
final float x = r * Mth.cos(theta);
final float y = r * Mth.sin(theta);
float theta = step * i;
float x = r * Mth.cos(theta);
float y = r * Mth.sin(theta);
builder.vertex(x + cx, cy + y, cz + h).color(red, grn, blu, alpha).endVertex();
}
tessellator.end();
@@ -1295,9 +1295,9 @@ public class ShapesRenderer
float yp = 0;
for (int i = 1; i <= num_steps360; i++)
{
final float theta = step * i;
final float x = r * Mth.cos(theta);
final float y = r * Mth.sin(theta);
float theta = step * i;
float x = r * Mth.cos(theta);
float y = r * Mth.sin(theta);
builder.vertex(cx + xp, cy + yp, cz + 0).color(red, grn, blu, alpha).endVertex();
builder.vertex(cx + xp, cy + yp, cz + h).color(red, grn, blu, alpha).endVertex();
builder.vertex(cx + x, cy + y, cz + h).color(red, grn, blu, alpha).endVertex();
@@ -1310,24 +1310,24 @@ public class ShapesRenderer
}
}
public static void drawSphereWireframe(final Tesselator tessellator, final BufferBuilder builder,
final float cx, final float cy, final float cz,
final float r, final int subd,
final float red, final float grn, final float blu, final float alpha)
public static void drawSphereWireframe(Tesselator tessellator, BufferBuilder builder,
float cx, float cy, float cz,
float r, int subd,
float red, float grn, float blu, float alpha)
{
final float step = (float) Math.PI / (subd / 2);
final int num_steps180 = (int) (Math.PI / step) + 1;
final int num_steps360 = (int) (2 * Math.PI / step) + 1;
float step = (float) Math.PI / (subd / 2);
int num_steps180 = (int) (Math.PI / step) + 1;
int num_steps360 = (int) (2 * Math.PI / step) + 1;
for (int i = 0; i <= num_steps360; i++)
{
builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR);
final float theta = step * i;
float theta = step * i;
for (int j = 0; j <= num_steps180; j++)
{
final float phi = step * j;
final float x = r * Mth.sin(phi) * Mth.cos(theta);
final float z = r * Mth.sin(phi) * Mth.sin(theta);
final float y = r * Mth.cos(phi);
float phi = step * j;
float x = r * Mth.sin(phi) * Mth.cos(theta);
float z = r * Mth.sin(phi) * Mth.sin(theta);
float y = r * Mth.cos(phi);
builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex();
}
tessellator.end();
@@ -1335,14 +1335,14 @@ public class ShapesRenderer
for (int j = 0; j <= num_steps180; j++)
{
builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip
final float phi = step * j;
float phi = step * j;
for (int i = 0; i <= num_steps360; i++)
{
final float theta = step * i;
final float x = r * Mth.sin(phi) * Mth.cos(theta);
final float z = r * Mth.sin(phi) * Mth.sin(theta);
final float y = r * Mth.cos(phi);
float theta = step * i;
float x = r * Mth.sin(phi) * Mth.cos(theta);
float z = r * Mth.sin(phi) * Mth.sin(theta);
float y = r * Mth.cos(phi);
builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex();
}
tessellator.end();
@@ -1350,19 +1350,19 @@ public class ShapesRenderer
}
public static void drawSphereFaces(final Tesselator tessellator, final BufferBuilder builder,
final float cx, final float cy, final float cz,
final float r, final int subd,
final float red, final float grn, final float blu, final float alpha)
public static void drawSphereFaces(Tesselator tessellator, BufferBuilder builder,
float cx, float cy, float cz,
float r, int subd,
float red, float grn, float blu, float alpha)
{
final float step = (float) Math.PI / (subd / 2);
final int num_steps180 = (int) (Math.PI / step) + 1;
final int num_steps360 = (int) (2 * Math.PI / step);
float step = (float) Math.PI / (subd / 2);
int num_steps180 = (int) (Math.PI / step) + 1;
int num_steps360 = (int) (2 * Math.PI / step);
for (int i = 0; i <= num_steps360; i++)
{
final float theta = i * step;
final float thetaprime = theta + step;
float theta = i * step;
float thetaprime = theta + step;
builder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); // quad strip to quads
float xb = 0;
float zb = 0;
@@ -1371,12 +1371,12 @@ public class ShapesRenderer
float yp = r;
for (int j = 0; j <= num_steps180; j++)
{
final float phi = j * step;
final float x = r * Mth.sin(phi) * Mth.cos(theta);
final float z = r * Mth.sin(phi) * Mth.sin(theta);
final float y = r * Mth.cos(phi);
final float xp = r * Mth.sin(phi) * Mth.cos(thetaprime);
final float zp = r * Mth.sin(phi) * Mth.sin(thetaprime);
float phi = j * step;
float x = r * Mth.sin(phi) * Mth.cos(theta);
float z = r * Mth.sin(phi) * Mth.sin(theta);
float y = r * Mth.cos(phi);
float xp = r * Mth.sin(phi) * Mth.cos(thetaprime);
float zp = r * Mth.sin(phi) * Mth.sin(thetaprime);
builder.vertex(xb + cx, yp + cy, zb + cz).color(red, grn, blu, alpha).endVertex();
builder.vertex(xbp + cx, yp + cy, zbp + cz).color(red, grn, blu, alpha).endVertex();
builder.vertex(xp + cx, y + cy, zp + cz).color(red, grn, blu, alpha).endVertex();
@@ -15,7 +15,7 @@ public class SimplexNoiseSampler extends PerlinNoiseSampler
public static SimplexNoiseSampler instance = new SimplexNoiseSampler(new Random(0));
public static Map<Long, SimplexNoiseSampler> samplers = new Long2ObjectOpenHashMap<>();
public static SimplexNoiseSampler getSimplex(final long aLong)
public static SimplexNoiseSampler getSimplex(long aLong)
{
if (samplers.size() > 256)
{
@@ -24,15 +24,15 @@ public class SimplexNoiseSampler extends PerlinNoiseSampler
return samplers.computeIfAbsent(aLong, seed -> new SimplexNoiseSampler(new Random(seed)));
}
public SimplexNoiseSampler(final Random random)
public SimplexNoiseSampler(Random random)
{
super(random);
}
private double grad(final int hash, final double x, final double y, final double z, final double d)
private double grad(int hash, double x, double y, double z, double d)
{
double e = d - x * x - y * y - z * z;
final double g;
double g;
if (e < 0.0D)
{
g = 0.0D;
@@ -51,16 +51,16 @@ public class SimplexNoiseSampler extends PerlinNoiseSampler
{
x = x / 2;
y = y / 2;
final double d = (x + y) * SKEW_FACTOR_2D;
final int i = PerlinNoiseSampler.floor(x + d);
final int j = PerlinNoiseSampler.floor(y + d);
final double e = (i + j) * UNSKEW_FACTOR_2D;
final double f = i - e;
final double g = j - e;
final double h = x - f;
final double k = y - g;
final byte n;
final byte o;
double d = (x + y) * SKEW_FACTOR_2D;
int i = PerlinNoiseSampler.floor(x + d);
int j = PerlinNoiseSampler.floor(y + d);
double e = (i + j) * UNSKEW_FACTOR_2D;
double f = i - e;
double g = j - e;
double h = x - f;
double k = y - g;
byte n;
byte o;
if (h > k)
{
n = 1;
@@ -72,18 +72,18 @@ public class SimplexNoiseSampler extends PerlinNoiseSampler
o = 1;
}
final double p = h - n + UNSKEW_FACTOR_2D;
final double q = k - o + UNSKEW_FACTOR_2D;
final double r = h - 1.0D + 2.0D * UNSKEW_FACTOR_2D;
final double s = k - 1.0D + 2.0D * UNSKEW_FACTOR_2D;
final int t = i & 255;
final int u = j & 255;
final int v = this.getGradient(t + this.getGradient(u)) % 12;
final int w = this.getGradient(t + n + this.getGradient(u + o)) % 12;
final int z = this.getGradient(t + 1 + this.getGradient(u + 1)) % 12;
final double aa = this.grad(v, h, k, 0.0D, 0.5D);
final double ab = this.grad(w, p, q, 0.0D, 0.5D);
final double ac = this.grad(z, r, s, 0.0D, 0.5D);
double p = h - n + UNSKEW_FACTOR_2D;
double q = k - o + UNSKEW_FACTOR_2D;
double r = h - 1.0D + 2.0D * UNSKEW_FACTOR_2D;
double s = k - 1.0D + 2.0D * UNSKEW_FACTOR_2D;
int t = i & 255;
int u = j & 255;
int v = this.getGradient(t + this.getGradient(u)) % 12;
int w = this.getGradient(t + n + this.getGradient(u + o)) % 12;
int z = this.getGradient(t + 1 + this.getGradient(u + 1)) % 12;
double aa = this.grad(v, h, k, 0.0D, 0.5D);
double ab = this.grad(w, p, q, 0.0D, 0.5D);
double ac = this.grad(z, r, s, 0.0D, 0.5D);
//return 70.0D * (aa + ab + ac);
return 35.0D * (aa + ab + ac) + 0.5;
}
@@ -95,24 +95,24 @@ public class SimplexNoiseSampler extends PerlinNoiseSampler
e = e / 2;
f = f / 2;
//final double g = 0.3333333333333333D;
final double h = (d + e + f) * 0.3333333333333333D;
final int i = floor(d + h);
final int j = floor(e + h);
final int k = floor(f + h);
double h = (d + e + f) * 0.3333333333333333D;
int i = floor(d + h);
int j = floor(e + h);
int k = floor(f + h);
//final double l = 0.16666666666666666D;
final double m = (i + j + k) * 0.16666666666666666D;
final double n = i - m;
final double o = j - m;
final double p = k - m;
final double q = d - n;
final double r = e - o;
final double s = f - p;
final byte z;
final byte aa;
final byte ab;
final byte ac;
final byte ad;
final byte bc;
double m = (i + j + k) * 0.16666666666666666D;
double n = i - m;
double o = j - m;
double p = k - m;
double q = d - n;
double r = e - o;
double s = f - p;
byte z;
byte aa;
byte ab;
byte ac;
byte ad;
byte bc;
if (q >= r)
{
if (r >= s)
@@ -171,26 +171,26 @@ public class SimplexNoiseSampler extends PerlinNoiseSampler
bc = 0;
}
final double bd = q - z + 0.16666666666666666D;
final double be = r - aa + 0.16666666666666666D;
final double bf = s - ab + 0.16666666666666666D;
final double bg = q - ac + 0.3333333333333333D;
final double bh = r - ad + 0.3333333333333333D;
final double bi = s - bc + 0.3333333333333333D;
final double bj = q - 1.0D + 0.5D;
final double bk = r - 1.0D + 0.5D;
final double bl = s - 1.0D + 0.5D;
final int bm = i & 255;
final int bn = j & 255;
final int bo = k & 255;
final int bp = this.getGradient(bm + this.getGradient(bn + this.getGradient(bo))) % 12;
final int bq = this.getGradient(bm + z + this.getGradient(bn + aa + this.getGradient(bo + ab))) % 12;
final int br = this.getGradient(bm + ac + this.getGradient(bn + ad + this.getGradient(bo + bc))) % 12;
final int bs = this.getGradient(bm + 1 + this.getGradient(bn + 1 + this.getGradient(bo + 1))) % 12;
final double bt = this.grad(bp, q, r, s, 0.6D);
final double bu = this.grad(bq, bd, be, bf, 0.6D);
final double bv = this.grad(br, bg, bh, bi, 0.6D);
final double bw = this.grad(bs, bj, bk, bl, 0.6D);
double bd = q - z + 0.16666666666666666D;
double be = r - aa + 0.16666666666666666D;
double bf = s - ab + 0.16666666666666666D;
double bg = q - ac + 0.3333333333333333D;
double bh = r - ad + 0.3333333333333333D;
double bi = s - bc + 0.3333333333333333D;
double bj = q - 1.0D + 0.5D;
double bk = r - 1.0D + 0.5D;
double bl = s - 1.0D + 0.5D;
int bm = i & 255;
int bn = j & 255;
int bo = k & 255;
int bp = this.getGradient(bm + this.getGradient(bn + this.getGradient(bo))) % 12;
int bq = this.getGradient(bm + z + this.getGradient(bn + aa + this.getGradient(bo + ab))) % 12;
int br = this.getGradient(bm + ac + this.getGradient(bn + ad + this.getGradient(bo + bc))) % 12;
int bs = this.getGradient(bm + 1 + this.getGradient(bn + 1 + this.getGradient(bo + 1))) % 12;
double bt = this.grad(bp, q, r, s, 0.6D);
double bu = this.grad(bq, bd, be, bf, 0.6D);
double bv = this.grad(br, bg, bh, bi, 0.6D);
double bw = this.grad(bs, bj, bk, bl, 0.6D);
return 16.0D * (bt + bu + bv + bw) + 0.5;
}
@@ -40,7 +40,7 @@ public class SnoopyCommandSource extends CommandSourceStack
private final List<Component> chatOutput;
private final CommandSigningContext signingContext;
public SnoopyCommandSource(final CommandSourceStack original, final Component[] error, final List<Component> chatOutput)
public SnoopyCommandSource(CommandSourceStack original, Component[] error, List<Component> chatOutput)
{
super(CommandSource.NULL, original.getPosition(), original.getRotation(), original.getLevel(), Vanilla.MinecraftServer_getRunPermissionLevel(original.getServer()),
original.getTextName(), original.getDisplayName(), original.getServer(), original.getEntity(), false,
@@ -63,7 +63,7 @@ public class SnoopyCommandSource extends CommandSourceStack
this.signingContext = original.getSigningContext();
}
public SnoopyCommandSource(final ServerPlayer player, final Component[] error, final List<Component> output)
public SnoopyCommandSource(ServerPlayer player, Component[] error, List<Component> output)
{
super(player, player.position(), player.getRotationVector(),
player.level instanceof final ServerLevel serverLevel ? serverLevel : null,
@@ -86,8 +86,8 @@ public class SnoopyCommandSource extends CommandSourceStack
this.signingContext = CommandSigningContext.ANONYMOUS;
}
private SnoopyCommandSource(final CommandSource output, final Vec3 pos, final Vec2 rot, final ServerLevel world, final int level, final String simpleName, final Component name, final MinecraftServer server, @Nullable final Entity entity, final ResultConsumer<CommandSourceStack> consumer, final EntityAnchorArgument.Anchor entityAnchor, final CommandSigningContext context,
final Component[] error, final List<Component> chatOutput
private SnoopyCommandSource(CommandSource output, Vec3 pos, Vec2 rot, ServerLevel world, int level, String simpleName, Component name, MinecraftServer server, @Nullable Entity entity, ResultConsumer<CommandSourceStack> consumer, EntityAnchorArgument.Anchor entityAnchor, CommandSigningContext context,
Component[] error, List<Component> chatOutput
)
{
super(output, pos, rot, world, level,
@@ -110,33 +110,33 @@ public class SnoopyCommandSource extends CommandSourceStack
}
@Override
public CommandSourceStack withEntity(final Entity entity)
public CommandSourceStack withEntity(Entity entity)
{
return new SnoopyCommandSource(output, position, rotation, world, level, entity.getName().getString(), entity.getDisplayName(), server, entity, resultConsumer, entityAnchor, signingContext, error, chatOutput);
}
@Override
public CommandSourceStack withPosition(final Vec3 position)
public CommandSourceStack withPosition(Vec3 position)
{
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, signingContext, error, chatOutput);
}
@Override
public CommandSourceStack withRotation(final Vec2 rotation)
public CommandSourceStack withRotation(Vec2 rotation)
{
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, signingContext, error, chatOutput);
}
@Override
public CommandSourceStack withCallback(final ResultConsumer<CommandSourceStack> consumer)
public CommandSourceStack withCallback(ResultConsumer<CommandSourceStack> consumer)
{
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, consumer, entityAnchor, signingContext, error, chatOutput);
}
@Override
public CommandSourceStack withCallback(final ResultConsumer<CommandSourceStack> consumer, final BinaryOperator<ResultConsumer<CommandSourceStack>> binaryOperator)
public CommandSourceStack withCallback(ResultConsumer<CommandSourceStack> consumer, BinaryOperator<ResultConsumer<CommandSourceStack>> binaryOperator)
{
final ResultConsumer<CommandSourceStack> resultConsumer = binaryOperator.apply(this.resultConsumer, consumer);
ResultConsumer<CommandSourceStack> resultConsumer = binaryOperator.apply(this.resultConsumer, consumer);
return this.withCallback(resultConsumer);
}
@@ -145,58 +145,58 @@ public class SnoopyCommandSource extends CommandSourceStack
//public ServerCommandSource withSilent() { return this; }
@Override
public CommandSourceStack withPermission(final int level)
public CommandSourceStack withPermission(int level)
{
return this;
}
@Override
public CommandSourceStack withMaximumPermission(final int level)
public CommandSourceStack withMaximumPermission(int level)
{
return this;
}
@Override
public CommandSourceStack withAnchor(final EntityAnchorArgument.Anchor anchor)
public CommandSourceStack withAnchor(EntityAnchorArgument.Anchor anchor)
{
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, anchor, signingContext, error, chatOutput);
}
@Override
public CommandSourceStack withSigningContext(final CommandSigningContext commandSigningContext)
public CommandSourceStack withSigningContext(CommandSigningContext commandSigningContext)
{
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, commandSigningContext, error, chatOutput);
}
@Override
public CommandSourceStack withLevel(final ServerLevel world)
public CommandSourceStack withLevel(ServerLevel world)
{
final double d = DimensionType.getTeleportationScale(this.world.dimensionType(), world.dimensionType());
final Vec3 position = new Vec3(this.position.x * d, this.position.y, this.position.z * d);
double d = DimensionType.getTeleportationScale(this.world.dimensionType(), world.dimensionType());
Vec3 position = new Vec3(this.position.x * d, this.position.y, this.position.z * d);
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, signingContext, error, chatOutput);
}
@Override
public CommandSourceStack facing(final Vec3 position)
public CommandSourceStack facing(Vec3 position)
{
final Vec3 vec3d = this.entityAnchor.apply(this);
final double d = position.x - vec3d.x;
final double e = position.y - vec3d.y;
final double f = position.z - vec3d.z;
final double g = Math.sqrt(d * d + f * f);
final float h = Mth.wrapDegrees((float) (-(Mth.atan2(e, g) * 57.2957763671875D)));
final float i = Mth.wrapDegrees((float) (Mth.atan2(f, d) * 57.2957763671875D) - 90.0F);
Vec3 vec3d = this.entityAnchor.apply(this);
double d = position.x - vec3d.x;
double e = position.y - vec3d.y;
double f = position.z - vec3d.z;
double g = Math.sqrt(d * d + f * f);
float h = Mth.wrapDegrees((float) (-(Mth.atan2(e, g) * 57.2957763671875D)));
float i = Mth.wrapDegrees((float) (Mth.atan2(f, d) * 57.2957763671875D) - 90.0F);
return this.withRotation(new Vec2(h, i));
}
@Override
public void sendFailure(final Component message)
public void sendFailure(Component message)
{
error[0] = message;
}
@Override
public void sendSuccess(final Component message, final boolean broadcastToOps)
public void sendSuccess(Component message, boolean broadcastToOps)
{
chatOutput.add(message);
}
@@ -37,7 +37,7 @@ public class SystemInfo
{{
put("app_name", c ->
{
final String name = c.host.getName();
String name = c.host.getName();
return name == null ? Value.NULL : new StringValue(name);
});
put("app_list", c -> ListValue.wrap(((CarpetScriptHost) c.host).scriptServer().modules.keySet().stream().filter(Objects::nonNull).map(StringValue::new)));
@@ -49,18 +49,18 @@ public class SystemInfo
put("server_motd", c -> StringValue.of(c.server().getMotd()));
put("world_path", c -> StringValue.of(c.server().getWorldPath(LevelResource.ROOT).toString()));
put("world_folder", c -> {
final Path serverPath = c.server().getWorldPath(LevelResource.ROOT);
final int nodeCount = serverPath.getNameCount();
Path serverPath = c.server().getWorldPath(LevelResource.ROOT);
int nodeCount = serverPath.getNameCount();
if (nodeCount < 2)
{
return Value.NULL;
}
final String tlf = serverPath.getName(nodeCount - 2).toString();
String tlf = serverPath.getName(nodeCount - 2).toString();
return StringValue.of(tlf);
});
put("world_dimensions", c -> ListValue.wrap(c.server().levelKeys().stream().map(k -> ValueConversions.of(k.location()))));
put("world_spawn_point", c -> {
final LevelData prop = c.server().overworld().getLevelData();
LevelData prop = c.server().overworld().getLevelData();
return ListValue.of(NumericValue.of(prop.getXSpawn()), NumericValue.of(prop.getYSpawn()), NumericValue.of(prop.getZSpawn()));
});
@@ -69,7 +69,7 @@ public class SystemInfo
put("world_top", c -> new NumericValue(c.level().getMaxBuildHeight()));
put("world_center", c -> {
final WorldBorder worldBorder = c.level().getWorldBorder();
WorldBorder worldBorder = c.level().getWorldBorder();
return ListValue.fromTriple(worldBorder.getCenterX(), 0, worldBorder.getCenterZ());
});
@@ -90,11 +90,11 @@ public class SystemInfo
put("game_target", c -> StringValue.of(Vanilla.MinecraftServer_getReleaseTarget(c.server())));
put("game_protocol", c -> NumericValue.of(SharedConstants.getProtocolVersion()));
put("game_major_target", c -> {
final String[] vers = Vanilla.MinecraftServer_getReleaseTarget(c.server()).split("\\.");
String[] vers = Vanilla.MinecraftServer_getReleaseTarget(c.server()).split("\\.");
return NumericValue.of((vers.length > 1) ? Integer.parseInt(vers[1]) : 0);
});
put("game_minor_target", c -> {
final String[] vers = Vanilla.MinecraftServer_getReleaseTarget(c.server()).split("\\.");
String[] vers = Vanilla.MinecraftServer_getReleaseTarget(c.server()).split("\\.");
return NumericValue.of((vers.length > 2) ? Integer.parseInt(vers[2]) : 0);
});
put("game_stable", c -> BooleanValue.of(SharedConstants.getCurrentVersion().isStable()));
@@ -104,24 +104,24 @@ public class SystemInfo
put("server_ip", c -> StringValue.of(c.server().getLocalIp()));
put("server_whitelisted", c -> BooleanValue.of(c.server().isEnforceWhitelist()));
put("server_whitelist", c -> {
final MapValue whitelist = new MapValue(Collections.emptyList());
for (final String s : c.server().getPlayerList().getWhiteListNames())
MapValue whitelist = new MapValue(Collections.emptyList());
for (String s : c.server().getPlayerList().getWhiteListNames())
{
whitelist.append(StringValue.of(s));
}
return whitelist;
});
put("server_banned_players", c -> {
final MapValue whitelist = new MapValue(Collections.emptyList());
for (final String s : c.server().getPlayerList().getBans().getUserList())
MapValue whitelist = new MapValue(Collections.emptyList());
for (String s : c.server().getPlayerList().getBans().getUserList())
{
whitelist.append(StringValue.of(s));
}
return whitelist;
});
put("server_banned_ips", c -> {
final MapValue whitelist = new MapValue(Collections.emptyList());
for (final String s : c.server().getPlayerList().getIpBans().getUserList())
MapValue whitelist = new MapValue(Collections.emptyList());
for (String s : c.server().getPlayerList().getIpBans().getUserList())
{
whitelist.append(StringValue.of(s));
}
@@ -132,9 +132,9 @@ public class SystemInfo
put("server_last_tick_times", c -> {
//assuming we are in the tick world section
// might be off one tick when run in the off tasks or asynchronously.
final int currentReportedTick = c.server().getTickCount() - 1;
final List<Value> ticks = new ArrayList<>(100);
final long[] tickArray = c.server().tickTimes;
int currentReportedTick = c.server().getTickCount() - 1;
List<Value> ticks = new ArrayList<>(100);
long[] tickArray = c.server().tickTimes;
for (int i = currentReportedTick + 100; i > currentReportedTick; i--)
{
ticks.add(new NumericValue((tickArray[i % 100]) / 1000000.0));
@@ -148,9 +148,9 @@ public class SystemInfo
put("java_cpu_count", c -> new NumericValue(Runtime.getRuntime().availableProcessors()));
put("java_version", c -> StringValue.of(System.getProperty("java.version")));
put("java_bits", c -> {
for (final String property : new String[]{"sun.arch.data.model", "com.ibm.vm.bitmode", "os.arch"})
for (String property : new String[]{"sun.arch.data.model", "com.ibm.vm.bitmode", "os.arch"})
{
final String value = System.getProperty(property);
String value = System.getProperty(property);
if (value != null && value.contains("64"))
{
return new NumericValue(64);
@@ -159,23 +159,23 @@ public class SystemInfo
return new NumericValue(32);
});
put("java_system_cpu_load", c -> {
final OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(
OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(
OperatingSystemMXBean.class);
return new NumericValue(osBean.getCpuLoad());
});
put("java_process_cpu_load", c -> {
final OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(
OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(
OperatingSystemMXBean.class);
return new NumericValue(osBean.getProcessCpuLoad());
});
put("world_carpet_rules", c -> Carpet.getAllCarpetRules());
put("world_gamerules", c -> {
final Map<Value, Value> rules = new HashMap<>();
final GameRules gameRules = c.level().getGameRules();
Map<Value, Value> rules = new HashMap<>();
GameRules gameRules = c.level().getGameRules();
GameRules.visitGameRuleTypes(new GameRules.GameRuleTypeVisitor()
{
@Override
public <T extends GameRules.Value<T>> void visit(final GameRules.Key<T> key, final GameRules.Type<T> type)
public <T extends GameRules.Value<T>> void visit(GameRules.Key<T> key, GameRules.Type<T> type)
{
rules.put(StringValue.of(key.getId()), StringValue.of(gameRules.getRule(key).toString()));
}
@@ -188,13 +188,13 @@ public class SystemInfo
put("source_position", c -> ValueConversions.of(c.source().getPosition()));
put("source_dimension", c -> ValueConversions.of(c.level()));
put("source_rotation", c -> {
final Vec2 rotation = c.source().getRotation();
Vec2 rotation = c.source().getRotation();
return ListValue.of(new NumericValue(rotation.x), new NumericValue(rotation.y));
});
put("scarpet_version", c -> StringValue.of(Carpet.getCarpetVersion()));
}};
public static Value get(final String what, final CarpetContext cc)
public static Value get(String what, CarpetContext cc)
{
return options.getOrDefault(what, c -> null).apply(cc);
}
+18 -18
View File
@@ -14,45 +14,45 @@ import net.minecraft.world.phys.Vec3;
public class Tracer
{
public static HitResult rayTrace(final Entity source, final float partialTicks, final double reach, final boolean fluids)
public static HitResult rayTrace(Entity source, float partialTicks, double reach, boolean fluids)
{
final BlockHitResult blockHit = rayTraceBlocks(source, partialTicks, reach, fluids);
BlockHitResult blockHit = rayTraceBlocks(source, partialTicks, reach, fluids);
double maxSqDist = reach * reach;
if (blockHit != null)
{
maxSqDist = blockHit.getLocation().distanceToSqr(source.getEyePosition(partialTicks));
}
final EntityHitResult entityHit = rayTraceEntities(source, partialTicks, reach, maxSqDist);
EntityHitResult entityHit = rayTraceEntities(source, partialTicks, reach, maxSqDist);
return entityHit == null ? blockHit : entityHit;
}
public static BlockHitResult rayTraceBlocks(final Entity source, final float partialTicks, final double reach, final boolean fluids)
public static BlockHitResult rayTraceBlocks(Entity source, float partialTicks, double reach, boolean fluids)
{
final Vec3 pos = source.getEyePosition(partialTicks);
final Vec3 rotation = source.getViewVector(partialTicks);
final Vec3 reachEnd = pos.add(rotation.x * reach, rotation.y * reach, rotation.z * reach);
Vec3 pos = source.getEyePosition(partialTicks);
Vec3 rotation = source.getViewVector(partialTicks);
Vec3 reachEnd = pos.add(rotation.x * reach, rotation.y * reach, rotation.z * reach);
return source.level.clip(new ClipContext(pos, reachEnd, ClipContext.Block.OUTLINE, fluids ?
ClipContext.Fluid.ANY : ClipContext.Fluid.NONE, source));
}
public static EntityHitResult rayTraceEntities(final Entity source, final float partialTicks, final double reach, final double maxSqDist)
public static EntityHitResult rayTraceEntities(Entity source, float partialTicks, double reach, double maxSqDist)
{
final Vec3 pos = source.getEyePosition(partialTicks);
final Vec3 reachVec = source.getViewVector(partialTicks).scale(reach);
final AABB box = source.getBoundingBox().expandTowards(reachVec).inflate(1);
Vec3 pos = source.getEyePosition(partialTicks);
Vec3 reachVec = source.getViewVector(partialTicks).scale(reach);
AABB box = source.getBoundingBox().expandTowards(reachVec).inflate(1);
return rayTraceEntities(source, pos, pos.add(reachVec), box, e -> !e.isSpectator() && e.isPickable(), maxSqDist);
}
public static EntityHitResult rayTraceEntities(final Entity source, final Vec3 start, final Vec3 end, final AABB box, final Predicate<Entity> predicate, final double maxSqDistance)
public static EntityHitResult rayTraceEntities(Entity source, Vec3 start, Vec3 end, AABB box, Predicate<Entity> predicate, double maxSqDistance)
{
final Level world = source.level;
Level world = source.level;
double targetDistance = maxSqDistance;
Entity target = null;
Vec3 targetHitPos = null;
for (final Entity current : world.getEntities(source, box, predicate))
for (Entity current : world.getEntities(source, box, predicate))
{
final AABB currentBox = current.getBoundingBox().inflate(current.getPickRadius());
final Optional<Vec3> currentHit = currentBox.clip(start, end);
AABB currentBox = current.getBoundingBox().inflate(current.getPickRadius());
Optional<Vec3> currentHit = currentBox.clip(start, end);
if (currentBox.contains(start))
{
if (targetDistance >= 0)
@@ -64,8 +64,8 @@ public class Tracer
}
else if (currentHit.isPresent())
{
final Vec3 currentHitPos = currentHit.get();
final double currentDistance = start.distanceToSqr(currentHitPos);
Vec3 currentHitPos = currentHit.get();
double currentDistance = start.distanceToSqr(currentHitPos);
if (currentDistance < targetDistance || targetDistance == 0)
{
if (current.getRootVehicle() == source.getRootVehicle())
@@ -34,6 +34,7 @@ import net.minecraft.world.level.levelgen.WorldGenSettings;
import net.minecraft.world.level.storage.DerivedLevelData;
import net.minecraft.world.level.storage.ServerLevelData;
import javax.annotation.Nullable;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
@@ -44,24 +45,24 @@ import java.util.Set;
public class WorldTools
{
public static boolean canHasChunk(final ServerLevel world, final ChunkPos chpos, final Map<String, RegionFile> regionCache, final boolean deepcheck)
public static boolean canHasChunk(ServerLevel world, ChunkPos chpos, @Nullable Map<String, RegionFile> regionCache, boolean deepcheck)
{
if (world.getChunk(chpos.x, chpos.z, ChunkStatus.STRUCTURE_STARTS, false) != null)
{
return true;
}
final String currentRegionName = "r." + chpos.getRegionX() + "." + chpos.getRegionZ() + ".mca";
String currentRegionName = "r." + chpos.getRegionX() + "." + chpos.getRegionZ() + ".mca";
if (regionCache != null && regionCache.containsKey(currentRegionName))
{
final RegionFile region = regionCache.get(currentRegionName);
RegionFile region = regionCache.get(currentRegionName);
if (region == null)
{
return false;
}
return region.hasChunk(chpos);
}
final Path regionsFolder = Vanilla.MinecraftServer_storageSource(world.getServer()).getDimensionPath(world.dimension()).resolve("region");
final Path regionPath = regionsFolder.resolve(currentRegionName);
Path regionsFolder = Vanilla.MinecraftServer_storageSource(world.getServer()).getDimensionPath(world.dimension()).resolve("region");
Path regionPath = regionsFolder.resolve(currentRegionName);
if (!regionPath.toFile().exists())
{
if (regionCache != null)
@@ -76,14 +77,14 @@ public class WorldTools
}
try
{
final RegionFile region = new RegionFile(regionPath, regionsFolder, true);
RegionFile region = new RegionFile(regionPath, regionsFolder, true);
if (regionCache != null)
{
regionCache.put(currentRegionName, region);
}
return region.hasChunk(chpos);
}
catch (final IOException ignored)
catch (IOException ignored)
{
}
return true;
@@ -155,16 +156,16 @@ public class WorldTools
return true;
}*/
public static void forceChunkUpdate(final BlockPos pos, final ServerLevel world)
public static void forceChunkUpdate(BlockPos pos, ServerLevel world)
{
final ChunkPos chunkPos = new ChunkPos(pos);
final LevelChunk worldChunk = world.getChunkSource().getChunk(chunkPos.x, chunkPos.z, false);
ChunkPos chunkPos = new ChunkPos(pos);
LevelChunk worldChunk = world.getChunkSource().getChunk(chunkPos.x, chunkPos.z, false);
if (worldChunk != null)
{
final List<ServerPlayer> players = world.getChunkSource().chunkMap.getPlayers(chunkPos, false);
List<ServerPlayer> players = world.getChunkSource().chunkMap.getPlayers(chunkPos, false);
if (!players.isEmpty())
{
final ClientboundLevelChunkWithLightPacket packet = new ClientboundLevelChunkWithLightPacket(worldChunk, world.getLightEngine(), null, null, false); // false seems to update neighbours as well.
ClientboundLevelChunkWithLightPacket packet = new ClientboundLevelChunkWithLightPacket(worldChunk, world.getLightEngine(), null, null, false); // false seems to update neighbours as well.
players.forEach(p -> p.connection.send(packet));
}
}
@@ -5,6 +5,7 @@ import com.mojang.math.Axis;
import net.minecraft.client.Camera;
import net.minecraft.world.phys.Vec3;
import javax.annotation.Nullable;
import java.util.Locale;
public enum ShapeDirection
@@ -18,7 +19,8 @@ public enum ShapeDirection
CAMERA,
PLAYER;
public static ShapeDirection fromString(final String direction)
@Nullable
public static ShapeDirection fromString(String direction)
{
return switch (direction.toLowerCase(Locale.ROOT))
{
@@ -34,7 +36,7 @@ public enum ShapeDirection
};
}
public static void rotatePoseStackByShapeDirection(final PoseStack poseStack, final ShapeDirection shapeDirection, final Camera camera, final Vec3 objectPos)
public static void rotatePoseStackByShapeDirection(PoseStack poseStack, ShapeDirection shapeDirection, Camera camera, Vec3 objectPos)
{
switch (shapeDirection)
{
@@ -46,13 +48,13 @@ public enum ShapeDirection
case DOWN -> poseStack.mulPose(Axis.XP.rotationDegrees(-90));
case CAMERA -> poseStack.mulPose(camera.rotation());
case PLAYER -> {
final Vec3 vector = objectPos.subtract(camera.getPosition());
final double x = vector.x;
final double y = vector.y;
final double z = vector.z;
final double d = Math.sqrt(x * x + z * z);
final float rotX = (float) (Math.atan2(x, z));
final float rotY = (float) (Math.atan2(y, d));
Vec3 vector = objectPos.subtract(camera.getPosition());
double x = vector.x;
double y = vector.y;
double z = vector.z;
double d = Math.sqrt(x * x + z * z);
float rotX = (float) (Math.atan2(x, z));
float rotY = (float) (Math.atan2(y, d));
// that should work somehow but it doesn't for some reason
//matrices.mulPose(new Quaternion( -rotY, rotX, 0, false));