use of org.spongepowered.api.data.DataView in project LanternServer by LanternPowered.
the class LanternWorldPropertiesIO method write.
static void write(Path folder, LevelData levelData) throws IOException {
final DataView rootDataView = levelData.worldData;
final DataView dataView = rootDataView.getView(DATA).orElseGet(() -> rootDataView.createView(DATA));
dataView.set(NAME, levelData.worldName);
if (levelData.dimensionMap != null) {
final BitSet dimensionMap = levelData.dimensionMap;
final DataView dimensionData = rootDataView.createView(FORGE).createView(DIMENSION_DATA);
final int[] data = new int[(dimensionMap.length() + Integer.SIZE - 1) / Integer.SIZE];
for (int i = 0; i < data.length; i++) {
int val = 0;
for (int j = 0; j < Integer.SIZE; j++) {
val |= dimensionMap.get(i * Integer.SIZE + j) ? (1 << j) : 0;
}
data[i] = val;
}
dimensionData.set(DIMENSION_ARRAY, data);
}
IOHelper.write(folder.resolve(LEVEL_DATA), file -> {
NbtStreamUtils.write(rootDataView, Files.newOutputStream(file), true);
return true;
});
final DataView spongeRootContainer = levelData.spongeWorldData == null ? DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED) : levelData.spongeWorldData;
final DataView spongeContainer = spongeRootContainer.getView(DataQueries.SPONGE_DATA).orElseGet(() -> spongeRootContainer.createView(DataQueries.SPONGE_DATA));
spongeContainer.set(UUID_MOST, levelData.uniqueId.getMostSignificantBits());
spongeContainer.set(UUID_LEAST, levelData.uniqueId.getLeastSignificantBits());
if (levelData.dimensionId != null) {
spongeContainer.set(DIMENSION_INDEX, levelData.dimensionId);
}
IOHelper.write(folder.resolve(SPONGE_LEVEL_DATA), file -> {
NbtStreamUtils.write(spongeRootContainer, Files.newOutputStream(file), true);
return true;
});
}
use of org.spongepowered.api.data.DataView in project LanternServer by LanternPowered.
the class LanternWorldPropertiesIO method read.
static LevelData read(Path directory, @Nullable String worldName, @Nullable UUID uniqueId) throws IOException {
final DataView rootDataView = IOHelper.read(directory.resolve(LEVEL_DATA), file -> NbtStreamUtils.read(Files.newInputStream(file), true)).orElseThrow(() -> new FileNotFoundException("Unable to find " + LEVEL_DATA + "!"));
final DataView dataView = rootDataView.getView(DATA).get();
if (worldName == null) {
worldName = dataView.getString(NAME).get();
}
final DataView spongeRootDataView = IOHelper.read(directory.resolve(SPONGE_LEVEL_DATA), file -> NbtStreamUtils.read(Files.newInputStream(file), true)).orElse(null);
final DataView spongeContainer = spongeRootDataView != null ? spongeRootDataView.getView(DataQueries.SPONGE_DATA).orElse(null) : null;
if (uniqueId == null) {
// Try for the sponge (lantern) storage format
if (spongeContainer != null) {
final Long most = spongeContainer.getLong(UUID_MOST).orElseGet(() -> spongeContainer.getLong(OLD_UUID_MOST).orElse(null));
final Long least = spongeContainer.getLong(UUID_LEAST).orElseGet(() -> spongeContainer.getLong(OLD_UUID_LEAST).orElse(null));
if (most != null && least != null) {
uniqueId = new UUID(most, least);
}
}
// The uuid storage bukkit used, try this one first
final Path uuidFile;
if (uniqueId == null && Files.exists((uuidFile = directory.resolve(BUKKIT_UUID_DATA)))) {
try (DataInputStream in = new DataInputStream(Files.newInputStream(uuidFile))) {
uniqueId = new UUID(in.readLong(), in.readLong());
} catch (IOException e) {
Lantern.getLogger().error("Unable to access {}, ignoring...", BUKKIT_UUID_DATA, e);
}
Files.delete(uuidFile);
}
if (uniqueId == null) {
uniqueId = UUID.randomUUID();
}
}
BitSet dimensionMap = null;
if (rootDataView.contains(FORGE)) {
final DataView forgeView = rootDataView.getView(FORGE).get();
if (forgeView.contains(DIMENSION_DATA)) {
dimensionMap = new BitSet(LanternWorldManager.DIMENSION_MAP_SIZE);
final int[] intArray = (int[]) forgeView.getView(DIMENSION_DATA).get().get(DIMENSION_ARRAY).get();
for (int i = 0; i < intArray.length; i++) {
for (int j = 0; j < Integer.SIZE; j++) {
dimensionMap.set(i * Integer.SIZE + j, (intArray[i] & (1 << j)) != 0);
}
}
}
}
final Integer dimensionId = spongeContainer != null ? spongeContainer.getInt(DIMENSION_INDEX).orElse(null) : null;
return new LevelData(worldName, uniqueId, rootDataView, spongeRootDataView, dimensionId, dimensionMap);
}
use of org.spongepowered.api.data.DataView in project LanternServer by LanternPowered.
the class LanternWorldPropertiesIO method convert.
static LanternWorldProperties convert(LevelData levelData, WorldConfig worldConfig, boolean copyLevelSettingsToConfig) {
final LanternWorldProperties properties = new LanternWorldProperties(levelData.uniqueId, levelData.worldName, worldConfig);
final DataView dataView = levelData.worldData.getView(DATA).get();
final DataView spongeRootDataView = levelData.spongeWorldData;
final DataView spongeDataView;
if (spongeRootDataView != null) {
spongeDataView = spongeRootDataView.getView(DataQueries.SPONGE_DATA).orElse(null);
spongeDataView.remove(DataQueries.SPONGE_DATA);
} else {
spongeDataView = null;
}
final DataView lanternDataView = spongeDataView == null ? null : spongeDataView.getView(LANTERN).orElse(null);
properties.setLastPlayedTime(dataView.getLong(LAST_PLAYED).get());
properties.mapFeatures = dataView.getInt(MAP_FEATURES).get() > 0;
properties.setInitialized(dataView.getInt(INITIALIZED).get() > 0);
dataView.getInt(DIFFICULTY_LOCKED).ifPresent(v -> properties.setDifficultyLocked(v > 0));
final LanternWorldBorder border = properties.getWorldBorder();
dataView.getDouble(BORDER_CENTER_X).ifPresent(v -> border.centerX = v);
dataView.getDouble(BORDER_CENTER_Z).ifPresent(v -> border.centerZ = v);
dataView.getDouble(BORDER_SIZE_START).ifPresent(v -> border.diameterStart = v);
dataView.getDouble(BORDER_SIZE_END).ifPresent(v -> border.diameterEnd = v);
dataView.getLong(BORDER_SIZE_LERP_TIME).ifPresent(v -> border.lerpTime = v);
dataView.getDouble(BORDER_DAMAGE).ifPresent(v -> border.damage = v);
dataView.getDouble(BORDER_DAMAGE_THRESHOLD).ifPresent(v -> border.damageThreshold = v);
dataView.getInt(BORDER_WARNING_BLOCKS).ifPresent(v -> border.warningDistance = v);
dataView.getInt(BORDER_WARNING_TIME).ifPresent(v -> border.warningTime = v);
if (spongeRootDataView != null) {
properties.setAdditionalProperties(spongeRootDataView.copy().remove(DataQueries.SPONGE_DATA));
}
// Get the sponge properties
if (spongeDataView != null) {
// This can be null, this is provided in the lantern-server
final String dimensionTypeId = spongeDataView.getString(DIMENSION_TYPE).get();
if (dimensionTypeId.equalsIgnoreCase(OVERWORLD)) {
properties.setDimensionType(DimensionTypes.OVERWORLD);
} else if (dimensionTypeId.equalsIgnoreCase(NETHER)) {
properties.setDimensionType(DimensionTypes.NETHER);
} else if (dimensionTypeId.equalsIgnoreCase(END)) {
properties.setDimensionType(DimensionTypes.THE_END);
} else {
final DimensionType dimensionType = Sponge.getRegistry().getType(DimensionType.class, dimensionTypeId).orElse(null);
if (dimensionType == null) {
Lantern.getLogger().warn("Could not find a dimension type with id {} for the world {}, falling back to overworld...", dimensionTypeId, levelData.worldName);
}
properties.setDimensionType(dimensionType == null ? DimensionTypes.OVERWORLD : dimensionType);
}
PortalAgentType portalAgentType = null;
if (spongeDataView.contains(PORTAL_AGENT_TYPE)) {
final String portalAgentTypeId = spongeDataView.getString(PORTAL_AGENT_TYPE).get();
portalAgentType = Sponge.getRegistry().getType(PortalAgentType.class, portalAgentTypeId).orElse(null);
if (portalAgentType == null) {
Lantern.getLogger().warn("Could not find a portal agent type with id {} for the world {}, falling back to default...", portalAgentTypeId, levelData.worldName);
}
}
properties.setPortalAgentType(portalAgentType == null ? PortalAgentTypes.DEFAULT : portalAgentType);
spongeDataView.getInt(GENERATE_BONUS_CHEST).ifPresent(v -> properties.setGenerateBonusChest(v > 0));
spongeDataView.getInt(SERIALIZATION_BEHAVIOR).ifPresent(v -> properties.setSerializationBehavior(v == 0 ? SerializationBehaviors.MANUAL : v == 1 ? SerializationBehaviors.AUTOMATIC : SerializationBehaviors.NONE));
// Tracker
final Optional<List<DataView>> optTrackerUniqueIdViews = spongeDataView.getViewList(TRACKER_UUID_TABLE);
if (optTrackerUniqueIdViews.isPresent()) {
final List<DataView> trackerUniqueIdViews = optTrackerUniqueIdViews.get();
final Object2IntMap<UUID> trackerUniqueIds = properties.getTrackerIdAllocator().getUniqueIds();
final List<UUID> uniqueIdsByIndex = properties.getTrackerIdAllocator().getUniqueIdsByIndex();
for (DataView view : trackerUniqueIdViews) {
UUID uniqueId = null;
if (!view.isEmpty()) {
final long most = view.getLong(UUID_MOST).get();
final long least = view.getLong(UUID_LEAST).get();
uniqueId = new UUID(most, least);
trackerUniqueIds.put(uniqueId, uniqueIdsByIndex.size());
}
uniqueIdsByIndex.add(uniqueId);
}
}
}
// Weather
final WeatherData weatherData = properties.getWeatherData();
if (lanternDataView != null) {
final DataView weatherView = lanternDataView.getView(WEATHER).get();
final String weatherTypeId = weatherView.getString(WEATHER_TYPE).get();
final Optional<Weather> weatherType = Sponge.getRegistry().getType(Weather.class, weatherTypeId);
if (weatherType.isPresent()) {
weatherData.setWeather((LanternWeather) weatherType.get());
} else {
Lantern.getLogger().info("Unknown weather type: {}, the server will default to {}", weatherTypeId, weatherData.getWeather().getId());
}
weatherData.setRunningDuration(weatherView.getLong(WEATHER_RUNNING_DURATION).get());
weatherData.setRemainingDuration(weatherView.getLong(WEATHER_REMAINING_DURATION).get());
} else {
final boolean raining = dataView.getInt(RAINING).get() > 0;
final long rainTime = dataView.getLong(RAIN_TIME).get();
final boolean thundering = dataView.getInt(THUNDERING).get() > 0;
final long thunderTime = dataView.getLong(THUNDER_TIME).get();
final long clearWeatherTime = dataView.getLong(CLEAR_WEATHER_TIME).get();
if (thundering) {
weatherData.setWeather((LanternWeather) Weathers.THUNDER_STORM);
weatherData.setRemainingDuration(thunderTime);
} else if (raining) {
weatherData.setWeather((LanternWeather) Weathers.RAIN);
weatherData.setRemainingDuration(rainTime);
} else {
weatherData.setRemainingDuration(clearWeatherTime);
}
}
// Time
final TimeData timeData = properties.getTimeData();
final long age = dataView.getLong(AGE).get();
timeData.setAge(age);
final long time = dataView.getLong(TIME).orElse(age);
timeData.setDayTime(time);
if (lanternDataView != null && lanternDataView.contains(MOON_PHASE)) {
timeData.setMoonPhase(MoonPhase.valueOf(lanternDataView.getString(MOON_PHASE).get().toUpperCase()));
} else {
timeData.setMoonPhase(MoonPhase.values()[(int) (time / TimeUniverse.TICKS_IN_A_DAY) % 8]);
}
// Get the spawn position
final Optional<Integer> spawnX = dataView.getInt(SPAWN_X);
final Optional<Integer> spawnY = dataView.getInt(SPAWN_Y);
final Optional<Integer> spawnZ = dataView.getInt(SPAWN_Z);
if (spawnX.isPresent() && spawnY.isPresent() && spawnZ.isPresent()) {
properties.setSpawnPosition(new Vector3i(spawnX.get(), spawnY.get(), spawnZ.get()));
}
// Get the game rules
final DataView rulesView = dataView.getView(GAME_RULES).orElse(null);
if (rulesView != null) {
for (Entry<DataQuery, Object> en : rulesView.getValues(false).entrySet()) {
try {
properties.getRules().getOrCreateRule(RuleType.getOrCreate(en.getKey().toString(), RuleDataTypes.STRING, "")).setRawValue((String) en.getValue());
} catch (IllegalArgumentException e) {
Lantern.getLogger().warn("An error occurred while loading a game rule ({}) this one will be skipped", en.getKey().toString(), e);
}
}
}
if (copyLevelSettingsToConfig) {
worldConfig.getGeneration().setSeed(dataView.getLong(SEED).get());
worldConfig.setGameMode(GameModeRegistryModule.get().getByInternalId(dataView.getInt(GAME_MODE).get()).orElse(GameModes.SURVIVAL));
worldConfig.setHardcore(dataView.getInt(HARDCORE).get() > 0);
worldConfig.setDifficulty(DifficultyRegistryModule.get().getByInternalId(dataView.getInt(DIFFICULTY).get()).orElse(Difficulties.NORMAL));
if (dataView.contains(GENERATOR_NAME)) {
final String genName0 = dataView.getString(GENERATOR_NAME).get();
final String genName = genName0.indexOf(':') == -1 ? "minecraft:" + genName0 : genName0;
final GeneratorType generatorType = Sponge.getRegistry().getType(GeneratorType.class, genName).orElse(properties.getDimensionType().getDefaultGeneratorType());
DataContainer generatorSettings = null;
if (dataView.contains(GENERATOR_OPTIONS)) {
String options = dataView.getString(GENERATOR_OPTIONS).get();
String customSettings = null;
if (genName0.equalsIgnoreCase("flat")) {
customSettings = options;
// custom generator options to the flat generator
if (dataView.contains(GENERATOR_OPTIONS_EXTRA)) {
options = dataView.getString(GENERATOR_OPTIONS_EXTRA).get();
} else {
options = "";
}
}
if (!options.isEmpty()) {
try {
generatorSettings = JsonDataFormat.readContainer(options, false);
} catch (Exception e) {
Lantern.getLogger().warn("Unknown generator settings format \"{}\" for type {}, using defaults...", options, genName, e);
}
}
if (generatorSettings == null) {
generatorSettings = generatorType.getGeneratorSettings();
}
if (customSettings != null) {
generatorSettings.set(AbstractFlatGeneratorType.SETTINGS, customSettings);
}
} else {
generatorSettings = generatorType.getGeneratorSettings();
}
worldConfig.getGeneration().setGeneratorType(generatorType);
worldConfig.getGeneration().setGeneratorSettings(generatorSettings);
worldConfig.setLowHorizon(generatorType == GeneratorTypes.FLAT);
}
if (spongeDataView != null) {
spongeDataView.getInt(ENABLED).ifPresent(v -> worldConfig.setWorldEnabled(v > 0));
worldConfig.setKeepSpawnLoaded(spongeDataView.getInt(KEEP_SPAWN_LOADED).map(v -> v > 0).orElse(properties.getDimensionType().doesKeepSpawnLoaded()));
spongeDataView.getInt(LOAD_ON_STARTUP).ifPresent(v -> worldConfig.setKeepSpawnLoaded(v > 0));
spongeDataView.getStringList(GENERATOR_MODIFIERS).ifPresent(v -> {
final List<String> modifiers = worldConfig.getGeneration().getGenerationModifiers();
modifiers.clear();
modifiers.addAll(v);
properties.updateWorldGenModifiers(modifiers);
});
} else {
final LanternDimensionType dimensionType = properties.getDimensionType();
worldConfig.setKeepSpawnLoaded(dimensionType.doesKeepSpawnLoaded());
worldConfig.setDoesWaterEvaporate(dimensionType.doesWaterEvaporate());
}
}
return properties;
}
use of org.spongepowered.api.data.DataView in project LanternServer by LanternPowered.
the class LanternLoadingTicketIO method load.
static Multimap<String, LanternLoadingTicket> load(Path worldFolder, LanternChunkManager chunkManager, LanternChunkTicketManager service) throws IOException {
final Multimap<String, LanternLoadingTicket> tickets = HashMultimap.create();
final Path file = worldFolder.resolve(TICKETS_FILE);
if (!Files.exists(file)) {
return tickets;
}
final DataContainer dataContainer = NbtStreamUtils.read(Files.newInputStream(file), true);
final Set<String> callbacks = service.getCallbacks().keySet();
final List<DataView> ticketHolders = dataContainer.getViewList(HOLDER_LIST).get();
for (DataView ticketHolder : ticketHolders) {
final String holderName = ticketHolder.getString(HOLDER_NAME).get();
if (!Sponge.getPluginManager().isLoaded(holderName)) {
Lantern.getLogger().warn("Found chunk loading data for plugin {} which is currently not available or active" + " - it will be removed from the world save", holderName);
continue;
}
if (!callbacks.contains(holderName)) {
Lantern.getLogger().warn("The plugin {} has registered persistent chunk loading data but doesn't seem" + " to want to be called back with it - it will be removed from the world save", holderName);
continue;
}
final int maxNumChunks = chunkManager.getMaxChunksForPluginTicket(holderName);
final List<DataView> ticketEntries = ticketHolder.getViewList(TICKETS).get();
for (DataView ticketEntry : ticketEntries) {
final int type = ticketEntry.getInt(TICKET_TYPE).get();
UUID playerUUID = null;
if (ticketEntry.contains(PLAYER_UUID)) {
playerUUID = UUID.fromString(ticketEntry.getString(PLAYER_UUID).get());
}
int numChunks = maxNumChunks;
if (ticketEntry.contains(CHUNK_NUMBER)) {
numChunks = ticketEntry.getInt(CHUNK_NUMBER).get();
} else if (ticketEntry.contains(CHUNK_LIST_DEPTH)) {
numChunks = ticketEntry.getInt(CHUNK_LIST_DEPTH).get();
}
final LanternLoadingTicket ticket;
if (type == TYPE_NORMAL) {
if (playerUUID != null) {
ticket = new LanternPlayerLoadingTicket(holderName, chunkManager, playerUUID, maxNumChunks, numChunks);
} else {
ticket = new LanternLoadingTicket(holderName, chunkManager, maxNumChunks, numChunks);
}
} else if (type == TYPE_ENTITY) {
final LanternEntityLoadingTicket ticket0;
if (playerUUID != null) {
ticket0 = new LanternPlayerEntityLoadingTicket(holderName, chunkManager, playerUUID, maxNumChunks, numChunks);
} else {
ticket0 = new LanternEntityLoadingTicket(holderName, chunkManager, maxNumChunks, numChunks);
}
final int chunkX = ticketEntry.getInt(CHUNK_X).get();
final int chunkZ = ticketEntry.getInt(CHUNK_Z).get();
final long uuidMost = ticketEntry.getLong(ENTITY_UUID_MOST).get();
final long uuidLeast = ticketEntry.getLong(ENTITY_UUID_LEAST).get();
final Vector2i chunkCoords = new Vector2i(chunkX, chunkZ);
final UUID uuid = new UUID(uuidMost, uuidLeast);
ticket0.setEntityReference(new EntityReference(chunkCoords, uuid));
ticket = ticket0;
} else {
Lantern.getLogger().warn("Unknown ticket entry type {} for {}, skipping...", type, holderName);
continue;
}
if (ticketEntry.contains(MOD_DATA)) {
ticket.extraData = ticketEntry.getView(MOD_DATA).get().copy();
}
tickets.put(holderName, ticket);
chunkManager.attach(ticket);
}
}
return tickets;
}
use of org.spongepowered.api.data.DataView in project SpongeCommon by SpongePowered.
the class MixinPacketBuffer method cbuf$getDataView.
public DataView cbuf$getDataView(int index) {
final int oldIndex = this.readerIndex();
this.readerIndex(index);
final DataView data = this.cbuf$readDataView();
this.readerIndex(oldIndex);
return data;
}
Aggregations