Merge upstream port lane c

This commit is contained in:
piexel committed 2026-11-10 01:31:37 +01:00
commit 55786d6297
50 files changed
+2014 -256

No files matched your search

@@ -200,7 +200,6 @@ public class IrisSettings {
public double targetSpawnEntitiesPerChunk = 0.95;
public boolean markerEntitySpawningSystem = true;
public boolean effectSystem = true;
public boolean worldEditWandCUI = true;
public boolean globalPregenCache = false;
}
@@ -103,6 +103,7 @@ public final class DatapackIngestService {
private static final String TRANSACTION_JOURNAL = "journal.json";
private static final String TRANSACTION_JOURNAL_NEXT = "journal.next.json";
private static final String STARTUP_VALIDATION_CACHE = "startup-validation.json";
private static final String LOCAL_IMPORT_DIRECTORY = "imports";
private static final int OWNERSHIP_SCHEMA = 1;
private static final int TRANSACTION_SCHEMA = 2;
private static final int STARTUP_VALIDATION_SCHEMA = 1;
@@ -159,7 +160,7 @@ public final class DatapackIngestService {
StartupValidationCache cached = readStartupValidationCache(cacheFile);
if (startupValidationContextMatches(
cached, mcVersion, irisVersion, autoIngest, stripOverrides, urls)) {
String localFingerprint = startupValidationFingerprint(root, worldFolders);
String localFingerprint = startupValidationFingerprint(root, worldFolders, urls);
if (startupValidationCacheMatches(
cached,
mcVersion,
@@ -244,7 +245,7 @@ public final class DatapackIngestService {
autoIngest,
stripOverrides,
urls,
startupValidationFingerprint(root, worldFolders));
startupValidationFingerprint(root, worldFolders, urls));
writeStartupValidationCache(cacheFile, cache);
return cache;
} catch (IOException | RuntimeException exception) {
@@ -302,7 +303,7 @@ public final class DatapackIngestService {
validated.autoIngest,
validated.stripOverrides,
validated.urls,
startupValidationFingerprint(root, worldFolders));
startupValidationFingerprint(root, worldFolders, validated.urls));
}
private static StartupValidationCache createStartupValidationCache(
@@ -412,6 +413,14 @@ public final class DatapackIngestService {
}
static String startupValidationFingerprint(File root, KList<File> worldFolders) throws IOException {
return startupValidationFingerprint(root, worldFolders, List.of());
}
static String startupValidationFingerprint(
File root,
KList<File> worldFolders,
Iterable<String> sources
) throws IOException {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
Path manifestPath = new File(root, "manifest.json").toPath();
@@ -457,12 +466,61 @@ public final class DatapackIngestService {
new File(worldFolder, entry.id));
}
}
updateLocalSourceFingerprint(digest, sources);
return hex(digest.digest());
} catch (NoSuchAlgorithmException exception) {
throw new IOException("SHA-256 algorithm unavailable", exception);
}
}
private static void updateLocalSourceFingerprint(
MessageDigest digest,
Iterable<String> sources
) throws IOException {
if (sources == null) {
return;
}
List<String> localSources = new ArrayList<>();
for (String source : sources) {
URI uri = parseSourceUri(source);
if (uri != null && "file".equalsIgnoreCase(uri.getScheme())) {
localSources.add(uri.normalize().toASCIIString());
}
}
localSources.sort(String::compareTo);
byte[] buffer = new byte[HASH_BUFFER_BYTES];
for (String source : localSources) {
Path path = requireLocalDatapackPath(parseSourceUri(source));
updateFingerprintValue(digest, "local-source:" + source);
try (InputStream input = Files.newInputStream(
path,
StandardOpenOption.READ,
LinkOption.NOFOLLOW_LINKS)) {
long bytes = 0;
int length;
while ((length = input.read(buffer)) > 0) {
bytes += length;
if (bytes > MAX_DOWNLOAD_BYTES) {
throw new IOException("Local datapack exceeds " + MAX_DOWNLOAD_BYTES + " bytes: " + path);
}
digest.update(buffer, 0, length);
}
updateDigestLong(digest, bytes);
}
}
}
private static URI parseSourceUri(String source) throws IOException {
if (source == null || source.isBlank()) {
return null;
}
try {
return new URI(source.trim());
} catch (URISyntaxException exception) {
throw new IOException("Invalid datapack URL " + source, exception);
}
}
private static void updateDirectoryFingerprint(
MessageDigest digest,
String identity,
@@ -575,7 +633,7 @@ public final class DatapackIngestService {
private static Report ingestLocked(VolmitSender sender, KList<String> urls, boolean restart) {
Report report = new Report();
if (urls == null || urls.isEmpty()) {
message(sender, C.YELLOW + "No datapackImports configured in any loaded pack. Add Modrinth URLs to a dimension's 'datapackImports' list, then run /iris datapack ingest.");
message(sender, C.YELLOW + "No external datapacks found. Add a Modrinth, HTTP(S) or file URL to a dimension's 'datapackImports', or place a ZIP in Iris/datapacks/imports, then run /iris datapack ingest.");
return report;
}
@@ -677,7 +735,7 @@ public final class DatapackIngestService {
if (report.changed()) {
message(sender, C.YELLOW + "New datapack structures were installed. A server restart is required for them to register and generate.");
message(sender, C.GRAY + "After the restart they generate natively only in Iris dimensions that declare their source URL - no import needed. To get editable Iris copies (jigsaw pools, pieces & objects written into the pack) run /iris structure import <dimension>, or set general.autoImportDatapackStructures=true to do it on every ingest. Place any registered key directly with a 'structures' placement using nativeStructures.");
message(sender, C.GRAY + "After the restart they generate natively in Iris dimensions that declare their source URL; ZIPs from Iris/datapacks/imports are enabled for every Iris dimension. To get editable Iris copies (jigsaw pools, pieces & objects written into the pack) run /iris structure import <dimension>, or set general.autoImportDatapackStructures=true to do it on every ingest. Place any registered key directly with a 'structures' placement using nativeStructures.");
message(sender, C.GRAY + "Datapacks replace matching vanilla structure keys by default. Set 'importedStructures.datapackOverrides' to false to keep minecraft-namespaced structure definitions untouched; deny non-minecraft datapack and mod structure families with importedStructures.disabled or complete keys with importedStructures.disabledExact.");
if (!restart) {
message(sender, C.GRAY + "Run with restart=true to restart now, or restart manually. After restart, run /iris module structure list to see the new keys.");
@@ -1435,15 +1493,74 @@ public final class DatapackIngestService {
}
public static KList<String> collectConfiguredImports() {
LinkedHashSet<String> urls = new LinkedHashSet<>();
LinkedHashSet<String> sources = new LinkedHashSet<>();
try (Stream<IrisData> stream = ServerConfigurator.allPacks()) {
stream.forEach(data -> collectImports(data, urls));
stream.forEach(data -> collectImports(data, sources));
}
sources.addAll(localDatapackImports());
KList<String> result = new KList<>();
result.addAll(urls);
result.addAll(sources);
return result;
}
public static Set<String> configuredImports(IrisDimension dimension) {
Iterable<String> explicit = dimension == null ? List.of() : dimension.getDatapackImports();
return mergeConfiguredImports(explicit, localDatapackImports());
}
static Set<String> mergeConfiguredImports(
Iterable<String> explicit,
Iterable<String> discovered
) {
LinkedHashSet<String> sources = new LinkedHashSet<>();
if (explicit != null) {
addImports(explicit, sources);
}
if (discovered != null) {
addImports(discovered, sources);
}
return sources.isEmpty() ? Set.of() : Set.copyOf(sources);
}
static List<String> discoverLocalDatapackImports(File directory) throws IOException {
Path root = directory.toPath().toAbsolutePath().normalize();
if (Files.notExists(root, LinkOption.NOFOLLOW_LINKS)) {
Files.createDirectories(root);
}
if (Files.isSymbolicLink(root)
|| !Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Local datapack import path is not a safe directory: " + root);
}
try (Stream<Path> stream = Files.list(root)) {
return stream
.filter(path -> !Files.isSymbolicLink(path))
.filter(path -> Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS))
.filter(DatapackIngestService::isLocalDatapackArchive)
.sorted(Comparator.comparing(
(Path path) -> path.getFileName().toString(),
String.CASE_INSENSITIVE_ORDER)
.thenComparing((Path path) -> path.getFileName().toString()))
.map(path -> path.toAbsolutePath().normalize().toUri().toASCIIString())
.toList();
}
}
private static boolean isLocalDatapackArchive(Path path) {
String name = path.getFileName().toString();
return !name.startsWith(".") && name.toLowerCase(Locale.ROOT).endsWith(".zip");
}
private static List<String> localDatapackImports() {
File directory = IrisPlatforms.get().dataFolder("datapacks", LOCAL_IMPORT_DIRECTORY);
try {
return discoverLocalDatapackImports(directory);
} catch (IOException exception) {
IrisLogging.reportError("Could not discover local datapack imports under "
+ directory.getPath() + ".", exception);
return List.of();
}
}
public static List<Entry> installed() {
TRANSACTION_LOCK.lock();
try {
@@ -1884,34 +2001,39 @@ public final class DatapackIngestService {
if (imports == null) {
continue;
}
for (String url : imports) {
if (url != null && !url.isBlank()) {
urls.add(url.trim());
}
addImports(imports, urls);
}
}
private static void addImports(Iterable<String> imports, LinkedHashSet<String> sources) {
for (String source : imports) {
if (source != null && !source.isBlank()) {
sources.add(normalizeConfiguredSource(source));
}
}
}
static String normalizeConfiguredSource(String source) {
String normalized = source.trim();
try {
URI uri = new URI(normalized);
if ("file".equalsIgnoreCase(uri.getScheme())) {
return Path.of(uri).toAbsolutePath().normalize().toUri().toASCIIString();
}
} catch (IllegalArgumentException | URISyntaxException ignored) {
}
return normalized;
}
private static Set<String> configuredImports(IrisData data) {
LinkedHashSet<String> urls = new LinkedHashSet<>();
collectImports(data, urls);
urls.addAll(localDatapackImports());
return urls;
}
private static boolean hasImports(IrisData data) {
if (data.getDimensionLoader() == null) {
return false;
}
for (IrisDimension dimension : data.getDimensionLoader().loadAll(data.getDimensionLoader().getPossibleKeys())) {
if (dimension == null) {
continue;
}
KList<String> imports = dimension.getDatapackImports();
if (imports != null && !imports.isEmpty()) {
return true;
}
}
return false;
return !configuredImports(data).isEmpty();
}
static InstallResult install(File stagedDir, KList<File> worldFolders, Entry entry, boolean stripOverrides) throws IOException {
@@ -3542,11 +3664,12 @@ public final class DatapackIngestService {
}
static DownloadResult download(String url, File dest, String etag, String lastModified) throws IOException {
URI current;
try {
current = new URI(url);
} catch (URISyntaxException e) {
throw new IOException("Invalid datapack URL " + url, e);
URI current = parseSourceUri(url);
if (current == null) {
throw new IOException("Empty datapack URL");
}
if ("file".equalsIgnoreCase(current.getScheme())) {
return copyLocalDatapack(current, dest);
}
for (int attempt = 0; attempt < MAX_REDIRECTS; attempt++) {
if (!"http".equalsIgnoreCase(current.getScheme()) && !"https".equalsIgnoreCase(current.getScheme())) {
@@ -3624,6 +3747,84 @@ public final class DatapackIngestService {
throw new IOException("Too many redirects downloading " + url);
}
private static DownloadResult copyLocalDatapack(URI source, File destination) throws IOException {
Path sourcePath = requireLocalDatapackPath(source);
Path destinationPath = destination.toPath().toAbsolutePath().normalize();
if (Files.exists(destinationPath, LinkOption.NOFOLLOW_LINKS)
&& Files.isSameFile(sourcePath, destinationPath)) {
throw new IOException("Local datapack source and cache destination are the same file: " + sourcePath);
}
Path parent = destinationPath.getParent();
if (parent == null) {
throw new IOException("Local datapack cache destination has no parent: " + destinationPath);
}
ensureScratchDirectory(parent.toFile(), "datapack download cache");
BasicFileAttributes before = Files.readAttributes(
sourcePath,
BasicFileAttributes.class,
LinkOption.NOFOLLOW_LINKS);
Path temporary = Files.createTempFile(parent, destination.getName() + "-", ".part");
try {
long copied = 0;
try (InputStream input = Files.newInputStream(
sourcePath,
StandardOpenOption.READ,
LinkOption.NOFOLLOW_LINKS);
OutputStream output = Files.newOutputStream(temporary)) {
byte[] buffer = new byte[HASH_BUFFER_BYTES];
int length;
while ((length = input.read(buffer)) > 0) {
copied += length;
if (copied > MAX_DOWNLOAD_BYTES) {
throw new IOException("Local datapack exceeds " + MAX_DOWNLOAD_BYTES + " bytes: " + sourcePath);
}
output.write(buffer, 0, length);
}
}
BasicFileAttributes after = Files.readAttributes(
sourcePath,
BasicFileAttributes.class,
LinkOption.NOFOLLOW_LINKS);
if (!after.isRegularFile()
|| before.size() != after.size()
|| !before.lastModifiedTime().equals(after.lastModifiedTime())
|| !Objects.equals(before.fileKey(), after.fileKey())
|| copied != after.size()) {
throw new IOException("Local datapack changed while Iris was copying it: " + sourcePath);
}
move(temporary, destinationPath);
return new DownloadResult(false, null, null);
} finally {
Files.deleteIfExists(temporary);
}
}
private static Path requireLocalDatapackPath(URI source) throws IOException {
if (source == null
|| !"file".equalsIgnoreCase(source.getScheme())
|| source.isOpaque()
|| source.getRawAuthority() != null
|| source.getRawQuery() != null
|| source.getRawFragment() != null) {
throw new IOException("Datapack file URL must be an absolute local file URI without authority, query, or fragment: " + source);
}
Path path;
try {
path = Path.of(source).toAbsolutePath().normalize();
} catch (IllegalArgumentException exception) {
throw new IOException("Invalid local datapack file URL: " + source, exception);
}
if (Files.isSymbolicLink(path)
|| !Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Local datapack is not a regular non-symbolic-link file: " + path);
}
long size = Files.size(path);
if (size > MAX_DOWNLOAD_BYTES) {
throw new IOException("Local datapack exceeds " + MAX_DOWNLOAD_BYTES + " bytes: " + path);
}
return path;
}
private static String headerOrFallback(HttpURLConnection connection, String name, String fallback) {
String value = connection.getHeaderField(name);
return value == null || value.isBlank() ? fallback : value;
@@ -32,6 +32,7 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
@@ -42,6 +43,7 @@ public final class ModrinthResolver {
private static final String API = "https://api.modrinth.com/v2";
private static final String USER_AGENT = "VolmitSoftware/Iris (datapack-ingest)";
private static final String DATAPACK_LOADER = "datapack";
private static final String DEFAULT_DIRECT_FILENAME = "datapack.zip";
private static final int MAX_API_RESPONSE_CHARS = 8 * 1024 * 1024;
private ModrinthResolver() {
@@ -228,22 +230,33 @@ public final class ModrinthResolver {
}
private static ResolvedDatapack directResolve(String url) {
String filename = url;
int slash = filename.lastIndexOf('/');
if (slash >= 0) {
filename = filename.substring(slash + 1);
}
int query = filename.indexOf('?');
if (query >= 0) {
filename = filename.substring(0, query);
}
if (filename.isBlank()) {
filename = "datapack.zip";
}
String filename = directFilename(url);
String identity = directIdentity(url);
return new ResolvedDatapack(url, filename, null, "direct-" + identity, "direct", null, true);
}
private static String directFilename(String url) {
try {
URI uri = new URI(url);
if ("file".equalsIgnoreCase(uri.getScheme())) {
Path fileName = Path.of(uri).getFileName();
return fileName == null || fileName.toString().isBlank()
? DEFAULT_DIRECT_FILENAME
: fileName.toString();
}
String path = uri.getPath();
if (path != null && !path.isBlank()) {
int slash = path.lastIndexOf('/');
String fileName = slash >= 0 ? path.substring(slash + 1) : path;
if (!fileName.isBlank()) {
return fileName;
}
}
} catch (IllegalArgumentException | URISyntaxException ignored) {
}
return DEFAULT_DIRECT_FILENAME;
}
static String directIdentity(String url) {
String normalized = url;
try {
@@ -44,7 +44,8 @@ public final class ModuleObjectPlacement {
}
/**
* @param requestedY the height to place at, or a negative value for the placement to sample it
* Places the object at {@code requestedY}, which may be below zero in a dimension that reaches down there.
*
* @param listener hears each of the object's own blocks once the placement is written; null for none
* @param cave the cave the object is placed in, or null outside caves
*/
@@ -52,21 +53,42 @@ public final class ModuleObjectPlacement {
ObjectPlacement config, RNG rng,
BiConsumer<art.arcane.volmlib.util.math.BlockPosition, PlatformBlockState> listener,
CarveResult cave, IrisData data) {
ObjectRun run = cave == null
? ObjectRun.of(object, config, x, requestedY, z)
: ObjectRun.inCave(object, config, x, requestedY, z, caveOf(cave));
return place(run, placer, config, rng, listener, data);
}
/** As {@link #place}, at the height the placement samples from the terrain, or from {@code cave}. */
public static ObjectPlacementResult placeAutomatic(IrisObject object, int x, int z, IObjectPlacer placer,
ObjectPlacement config, RNG rng,
BiConsumer<art.arcane.volmlib.util.math.BlockPosition, PlatformBlockState> listener,
CarveResult cave, IrisData data) {
ObjectRun run = cave == null
? ObjectRun.automatic(object, config, x, z)
: ObjectRun.automaticInCave(object, config, x, z, caveOf(cave));
return place(run, placer, config, rng, listener, data);
}
private static ObjectRun.Cave caveOf(CarveResult cave) {
return new ObjectRun.Cave(cave.getSurface(), cave.getHeight());
}
private static ObjectPlacementResult place(ObjectRun run, IObjectPlacer placer, ObjectPlacement config, RNG rng,
BiConsumer<art.arcane.volmlib.util.math.BlockPosition, PlatformBlockState> listener,
IrisData data) {
Objects.requireNonNull(placer, "Object placer is required.");
Objects.requireNonNull(config, "Object placement config is required.");
Objects.requireNonNull(rng, "Object placement RNG is required.");
Objects.requireNonNull(data, "Object placement data is required.");
PlacerTerrain terrain = listener == null ? PlacerTerrain.of(placer, data) : PlacerTerrain.rememberingWrites(placer, data);
ObjectRun run = cave == null
? ObjectRun.of(object, config, x, requestedY, z)
: ObjectRun.inCave(object, config, x, requestedY, z, new ObjectRun.Cave(cave.getSurface(), cave.getHeight()));
PlacementOutcome outcome = placeIn(run, terrain, placer.getEngine(), rng, data);
if (!outcome.isPlaced()) {
return ObjectPlacementResult.rejected(outcome.rejection().orElseThrow());
}
reportObjectBlocks(run, terrain, listener);
int anchorY = run.anchorY().orElseThrow(() -> new IllegalStateException(
"The placement graph placed " + object.name() + " without anchoring it"));
"The placement graph placed " + run.object().name() + " without anchoring it"));
return ObjectPlacementResult.placed(anchorY);
}
@@ -0,0 +1,114 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle;
import art.arcane.iris.core.link.Identifier;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.util.project.matter.TileWrapper;
import art.arcane.volmlib.util.mantle.runtime.Mantle;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
/**
* Drops the deferred custom-block and tile records that a native structure write has overwritten, so the
* chunk's later materialization pass does not replay them onto the structure's blocks.
*/
public final class DeferredPlacementRecords {
private DeferredPlacementRecords() {
}
public static void clearWritten(Engine engine, WrittenBlocks written) {
if (written.isEmpty()) {
return;
}
Mantle<Matter> mantle = engine.getMantle().getMantle();
int minHeight = engine.getMinHeight();
Long2ObjectOpenHashMap<MantleChunk<Matter>> acquired = new Long2ObjectOpenHashMap<>();
try {
for (int index = 0; index < written.size(); index++) {
int x = written.x(index);
int z = written.z(index);
MantleChunk<Matter> chunk = acquired.computeIfAbsent(chunkKey(x >> 4, z >> 4),
key -> mantle.getChunk(x >> 4, z >> 4).use());
synchronized (chunk) {
clearRecords(chunk, x & 15, written.y(index) - minHeight, z & 15);
}
}
} finally {
acquired.values().forEach(MantleChunk::release);
}
}
private static long chunkKey(int chunkX, int chunkZ) {
return ((long) chunkX << 32) | (chunkZ & 0xFFFFFFFFL);
}
private static void clearRecords(MantleChunk<Matter> chunk, int x, int y, int z) {
if (y < 0 || (y >> 4) >= chunk.sectionCount() || !chunk.exists(y >> 4)) {
return;
}
Matter section = chunk.get(y >> 4);
if (section == null) {
return;
}
clearRecord(section, Identifier.class, x, y & 15, z);
clearRecord(section, TileWrapper.class, x, y & 15, z);
}
private static void clearRecord(Matter section, Class<?> type, int x, int y, int z) {
if (section.hasSlice(type)) {
section.getSlice(type).set(x, y, z, null);
}
}
/** World positions a native structure wrote, in write order, duplicates allowed. */
public static final class WrittenBlocks {
private final IntArrayList xs = new IntArrayList();
private final IntArrayList ys = new IntArrayList();
private final IntArrayList zs = new IntArrayList();
public void add(int x, int y, int z) {
xs.add(x);
ys.add(y);
zs.add(z);
}
public boolean isEmpty() {
return xs.isEmpty();
}
int size() {
return xs.size();
}
int x(int index) {
return xs.getInt(index);
}
int y(int index) {
return ys.getInt(index);
}
int z(int index) {
return zs.getInt(index);
}
}
}
@@ -25,6 +25,7 @@ import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.builtin.prepare.ObjectRotation;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.modules.ModuleObjectPlacement;
import art.arcane.iris.core.modules.ObjectPlacementResult;
import art.arcane.iris.engine.object.prefab.ObjectTurn;
import art.arcane.volmlib.util.cache.CacheKey;
import art.arcane.iris.engine.framework.IrisStructureLocator;
@@ -60,6 +61,7 @@ import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.matter.MatterStructurePOI;
import art.arcane.volmlib.util.math.BlockPosition;
import art.arcane.volmlib.util.math.RNG;
import it.unimi.dsi.fastutil.longs.Long2IntMap;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
@@ -68,6 +70,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
/**
* Places the Iris structures of the dimension, its regions and biomes into the mantle for
@@ -149,26 +152,26 @@ public class StructurePlacing {
ObjectPlaceMode undergroundMode = mode.placeMode().has(PlaceTrait.CAVE_ANCHORED)
? mode : ObjectPlaceMode.STRUCTURE_PIECE;
for (PlacedStructurePiece p : pieces) {
if (placeObject(writer, structure, p, undergroundMode, p.getY(), rng,
if (placeObject(writer, structure, p, undergroundMode, false, rng,
foundationColumns, supportNonOccluding) == -1) {
failedPieces++;
}
}
} else if (mode.placeMode().has(PlaceTrait.FREE_HEIGHT)) {
for (PlacedStructurePiece p : pieces) {
if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, p.getY(), rng,
if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, false, rng,
foundationColumns, supportNonOccluding) == -1) {
failedPieces++;
}
}
} else if (pieces.size() == 1) {
if (placeObject(writer, structure, pieces.getFirst(), mode, -1, rng,
if (placeObject(writer, structure, pieces.getFirst(), mode, true, rng,
foundationColumns, supportNonOccluding) == -1) {
failedPieces++;
}
} else {
for (PlacedStructurePiece p : pieces) {
if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, p.getY(), rng,
if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, false, rng,
foundationColumns, supportNonOccluding) == -1) {
failedPieces++;
}
@@ -561,7 +564,7 @@ public class StructurePlacing {
}
private int placeObject(MantleWriter writer, IrisStructure structure, PlacedStructurePiece p,
ObjectPlaceMode mode, int y, RNG rng, Long2IntOpenHashMap foundationColumns,
ObjectPlaceMode mode, boolean sampledHeight, RNG rng, Long2IntOpenHashMap foundationColumns,
boolean supportNonOccluding) {
IrisObject object = p.getObject();
String objectKey = object.getLoadKey();
@@ -573,16 +576,20 @@ public class StructurePlacing {
builder.forcePlace(true);
}
ObjectPlacement config = builder.build();
int placeY = (y == -1) ? -1 : y - engine.getMinHeight();
String marker = structurePlacementMarker(structure, p, objectKey);
return ModuleObjectPlacement.place(object, p.getX(), placeY, p.getZ(), writer, config, rng, (position, state) -> {
BiConsumer<BlockPosition, PlatformBlockState> listener = (position, state) -> {
StructureFoundationPlanner.recordBaseCell(
foundationColumns, position.getX(), position.getY(), position.getZ(), state,
supportNonOccluding);
if (marker != null && shouldWriteStructureMarker(state)) {
writer.setData(position.getX(), position.getY(), position.getZ(), marker);
}
}, null, engine.getData()).heightOrRejected();
};
ObjectPlacementResult result = sampledHeight
? ModuleObjectPlacement.placeAutomatic(object, p.getX(), p.getZ(), writer, config, rng, listener, null, engine.getData())
: ModuleObjectPlacement.place(object, p.getX(), p.getY() - engine.getMinHeight(), p.getZ(), writer, config, rng,
listener, null, engine.getData());
return result.heightOrRejected();
}
/** The placement rotation that turns a placed piece the way {@code turn} does. */
@@ -135,17 +135,22 @@ public class IrisObject extends IrisRegistrant implements PlaceableObject {
return aabb.aquire(() -> getAABBFor(new IrisBlockVector(w, h, d)));
}
public synchronized IrisObject copy() {
IrisObject o = new IrisObject(w, h, d);
o.setLoadKey(getLoadKey());
o.setLoader(getLoader());
o.setLoadFile(getLoadFile());
o.setCenter(getCenter().clone());
public IrisObject copy() {
readLock.lock();
try {
IrisObject o = new IrisObject(w, h, d);
o.setLoadKey(getLoadKey());
o.setLoader(getLoader());
o.setLoadFile(getLoadFile());
o.setCenter(getCenter().clone());
blocks.forEach((i, v) -> o.blocks.put(i.clone(), v));
states.forEach((i, v) -> o.states.put(i.clone(), v.clone()));
blocks.forEach((i, v) -> o.blocks.put(i.clone(), v));
states.forEach((i, v) -> o.states.put(i.clone(), v.clone()));
return o;
return o;
} finally {
readLock.unlock();
}
}
public void readLegacy(InputStream in) throws IOException {
@@ -30,7 +30,9 @@ import art.arcane.iris.util.project.interpolation.Interpolation3D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Geometric transforms for {@link IrisObject}: rotation, scaling and the interpolated upscalers.
@@ -50,14 +52,23 @@ final class IrisObjectTransforms {
try {
VectorMap<PlatformBlockState> d = new VectorMap<>();
Set<IrisBlockVector> omitted = new HashSet<>();
for (var entry : self.blocks) {
d.put(turn.rotate(entry.getKey()), BlockStateRotation.rotate(turn, entry.getValue()));
PlatformBlockState rotated = BlockStateRotation.rotate(turn, entry.getValue());
if (rotated == null) {
omitted.add(entry.getKey());
continue;
}
d.put(turn.rotate(entry.getKey()), rotated);
}
VectorMap<TileData> dx = new VectorMap<>();
for (var entry : self.states) {
dx.put(turn.rotate(entry.getKey()), entry.getValue());
if (!omitted.contains(entry.getKey())) {
dx.put(turn.rotate(entry.getKey()), entry.getValue());
}
}
self.blocks = d;
@@ -79,28 +90,27 @@ final class IrisObjectTransforms {
scale = scale - 0.0001;
}
IrisPosition l1 = self.getAABB().max();
IrisPosition l2 = self.getAABB().min();
VectorMap<PlatformBlockState> placeBlock = new VectorMap<>();
IrisVector center = new IrisVector(self.getCenter().getX(), self.getCenter().getY(), self.getCenter().getZ());
if (self.getH() == 2) {
center = center.setY(center.getBlockY() + 0.5);
}
if (self.getW() == 2) {
center = center.setX(center.getBlockX() + 0.5);
}
if (self.getD() == 2) {
center = center.setZ(center.getBlockZ() + 0.5);
}
IrisObject oo = new IrisObject((int) Math.ceil((self.w * scale) + (scale * 2)), (int) Math.ceil((self.h * scale) + (scale * 2)), (int) Math.ceil((self.d * scale) + (scale * 2)));
oo.setLoadKey(self.getLoadKey());
oo.setLoader(self.getLoader());
oo.setLoadFile(self.getLoadFile());
IrisVector center;
IrisObject oo;
self.readLock.lock();
try {
center = new IrisVector(self.getCenter().getX(), self.getCenter().getY(), self.getCenter().getZ());
if (self.getH() == 2) {
center = center.setY(center.getBlockY() + 0.5);
}
if (self.getW() == 2) {
center = center.setX(center.getBlockX() + 0.5);
}
if (self.getD() == 2) {
center = center.setZ(center.getBlockZ() + 0.5);
}
oo = new IrisObject((int) Math.ceil((self.w * scale) + (scale * 2)), (int) Math.ceil((self.h * scale) + (scale * 2)), (int) Math.ceil((self.d * scale) + (scale * 2)));
oo.setLoadKey(self.getLoadKey());
oo.setLoader(self.getLoader());
oo.setLoadFile(self.getLoadFile());
for (var entry : self.blocks) {
PlatformBlockState bd = entry.getValue();
placeBlock.put(entry.getKey().clone().add(IrisObject.HALF).subtract(center)
@@ -209,7 +209,7 @@ public class IrisDimension extends IrisRegistrant {
@Desc("Overlay additional noise on top of the interoplated terrain.")
private KList<IrisShapedGeneratorStyle> overlayNoise = new KList<>();
@ArrayType(type = String.class, min = 1)
@Desc("External datapack sources owned by this dimension. Bukkit registers their resources server-wide, but Iris excludes their structure sets and definitions from generation and locate state in vanilla worlds and Iris dimensions that do not declare the same source. Editable auto-import is limited to resources supplied by the URLs declared by each Iris pack. Any registered datapack structure can be placed directly through nativeStructures without conversion. Replacing native generation requires a dimension-level structure placement with nativeSuppression set to REPLACE_SOURCE; provenance alone never disables native structures.")
@Desc("External Modrinth, HTTP(S) or file URL datapack sources owned by this dimension. Bukkit registers their resources server-wide, but Iris excludes their structure sets and definitions from generation and locate state in vanilla worlds and Iris dimensions that do not declare the same source. Local ZIPs under Iris/datapacks/imports are discovered automatically and enabled for every Iris dimension. Editable auto-import is limited to resources supplied by configured or discovered sources. Any registered datapack structure can be placed directly through nativeStructures without conversion. Replacing native generation requires a dimension-level structure placement with nativeSuppression set to REPLACE_SOURCE; provenance alone never disables native structures.")
private KList<String> datapackImports = new KList<>();
@RegistryListFunction(ComponentFlagFunction.class)
@ArrayType(type = String.class)
@@ -33,6 +33,7 @@ import art.arcane.iris.engine.framework.WrongEngineBroException;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.prefab.TileData;
import art.arcane.iris.util.common.data.IrisCustomData;
import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
import art.arcane.iris.platform.bukkit.BukkitBlockState;
import art.arcane.iris.spi.IrisLogging;
@@ -80,7 +81,9 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.loot.Lootable;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CancellationException;
@@ -194,12 +197,16 @@ public final class EngineBukkitOps {
}
static void materializeTiles(Engine engine, Chunk chunk, MantleChunk<Matter> mantleChunk) {
StaleRecords stale = new StaleRecords();
mantleChunk.iterate(TileWrapper.class, (x, y, z, value) -> {
int worldY = y + engine.getWorld().minHeight();
if (worldY < chunk.getWorld().getMinHeight() || worldY >= chunk.getWorld().getMaxHeight()) {
return;
}
Block block = chunk.getBlock(x & 15, worldY, z & 15);
if (stale.tileReplaced(block, value.getData())) {
return;
}
if (!TileData.setTileState(block, value.getData())) {
NamespacedKey blockTypeKey = KeyedType.getKey(block.getType());
String blockType = blockTypeKey == null ? block.getType().name() : blockTypeKey.toString();
@@ -208,21 +215,25 @@ public final class EngineBukkitOps {
}
});
mantleChunk.deleteSlices(TileWrapper.class);
stale.report("tile", chunk);
}
static void materializeCustomBlocks(Engine engine, Chunk chunk, MantleChunk<Matter> mantleChunk) {
StaleRecords stale = new StaleRecords();
mantleChunk.iterate(Identifier.class, (x, y, z, value) -> {
int worldY = y + engine.getWorld().minHeight();
if (worldY < chunk.getWorld().getMinHeight() || worldY >= chunk.getWorld().getMaxHeight()) {
return;
}
IrisServices.get(ExternalDataSVC.class).processUpdate(
engine,
chunk.getBlock(x & 15, worldY, z & 15),
value
);
ExternalDataSVC service = IrisServices.get(ExternalDataSVC.class);
Block block = chunk.getBlock(x & 15, worldY, z & 15);
if (stale.carrierReplaced(service, block, value)) {
return;
}
service.processUpdate(engine, block, value);
});
mantleChunk.deleteSlices(Identifier.class);
stale.report("custom block", chunk);
}
static void runMaterializationPasses(
@@ -693,4 +704,44 @@ public final class EngineBukkitOps {
record LootMutationTask(World world, int chunkX, int chunkZ, Runnable mutation) {
}
private static final class StaleRecords {
private final Map<Identifier, Material> carriers = new HashMap<>();
private int skipped;
private boolean carrierReplaced(ExternalDataSVC service, Block block, Identifier record) {
Material carrier = carriers.computeIfAbsent(record, key -> carrierType(service, key));
if (carrier == Material.AIR || block.getType() == carrier) {
return false;
}
skipped++;
return true;
}
private boolean tileReplaced(Block block, TileData tile) {
if (tile.resolveMaterial() == null || tile.isApplicable(block.getBlockData())) {
return false;
}
skipped++;
return true;
}
private void report(String records, Chunk chunk) {
if (skipped == 0) {
return;
}
IrisLogging.debug("Skipped %d stale %s records at chunk %d,%d in %s",
skipped, records, chunk.getX(), chunk.getZ(), chunk.getWorld().getName());
}
private static Material carrierType(ExternalDataSVC service, Identifier record) {
Optional<BlockData> resolved = service.getBlockData(record);
if (resolved.isEmpty()) {
return Material.AIR;
}
BlockData data = resolved.get();
Material type = (data instanceof IrisCustomData custom ? custom.getBase() : data).getMaterial();
return type == Material.CAVE_AIR || type == Material.VOID_AIR ? Material.AIR : type;
}
}
}