Skip to content

Commit

Permalink
Portal highlighting save/load to disk setting
Browse files Browse the repository at this point in the history
  • Loading branch information
rfresh2 committed Nov 7, 2023
1 parent 369a6f5 commit d9657c6
Show file tree
Hide file tree
Showing 12 changed files with 88 additions and 34 deletions.
48 changes: 35 additions & 13 deletions src/main/java/xaeroplus/module/impl/Portals.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package xaeroplus.module.impl;

import com.collarmc.pounce.Subscribe;
import it.unimi.dsi.fastutil.longs.Long2LongMap;
import net.minecraft.block.BlockState;
import net.minecraft.block.EndPortalBlock;
import net.minecraft.block.NetherPortalBlock;
Expand All @@ -23,6 +24,8 @@
import xaeroplus.util.ChunkUtils;
import xaeroplus.util.ColorHelper;
import xaeroplus.util.MutableBlockPos;
import xaeroplus.util.highlights.ChunkHighlightCache;
import xaeroplus.util.highlights.ChunkHighlightLocalCache;
import xaeroplus.util.highlights.ChunkHighlightSavingCache;
import xaeroplus.util.highlights.HighlightAtChunkPos;

Expand All @@ -37,27 +40,39 @@
public class Portals extends Module {

// todo: local cache setting
private ChunkHighlightSavingCache portalsCache;
private ChunkHighlightCache portalsCache = new ChunkHighlightLocalCache();
private final ExecutorService searchExecutor = Executors.newSingleThreadExecutor();
private final MinecraftClient mc = MinecraftClient.getInstance();
private int portalsColor = getColor(0, 255, 0, 100);
private static final String DATABASE_NAME = "XaeroPlusPortals";

public void setPortalsCache(final Boolean disk) {
try {
final Long2LongMap map = portalsCache.getHighlightsState();
portalsCache.onDisable();
if (disk) {
portalsCache = new ChunkHighlightSavingCache(DATABASE_NAME);
} else {
portalsCache = new ChunkHighlightLocalCache();
}
if (this.isEnabled()) {
portalsCache.onEnable();
if (map != null) portalsCache.loadPreviousState(map);
}
} catch (final Exception e) {
XaeroPlus.LOGGER.error("Error setting portals cache", e);
}
}

@Override
public void onEnable() {
if (portalsCache == null) {
portalsCache = new ChunkHighlightSavingCache(DATABASE_NAME);
portalsCache.onEnable();
searchAllLoadedChunks();
}
portalsCache.onEnable();
searchAllLoadedChunks();
}

@Override
public void onDisable() {
if (portalsCache != null) {
portalsCache.onDisable();
portalsCache = null;
}
portalsCache.onDisable();
}

public boolean inUnknownDimension() {
Expand All @@ -83,13 +98,20 @@ public void onPacketReceived(final PacketReceivedEvent event) {

@Subscribe
public void onXaeroWorldChangeEvent(final XaeroWorldChangeEvent event) {
if (XaeroPlusSettingRegistry.portalsSaveLoadToDisk.getValue()) {
if (inUnknownDimension() && portalsCache instanceof ChunkHighlightSavingCache) {
XaeroPlusSettingRegistry.portalsSaveLoadToDisk.setValue(false);
XaeroPlus.LOGGER.warn("Entered unknown dimension with saving cache on, disabling disk saving");
}
}
portalsCache.handleWorldChange();
}

@Subscribe
public void onClientTickEvent(final ClientTickEvent event) {
public void onClientTickEvent(final ClientTickEvent.Post event) {
portalsCache.handleTick();
}

private void findPortalInChunkAsync(final Chunk chunk) {
findPortalInChunkAsync(chunk, 0);
}
Expand All @@ -112,7 +134,7 @@ private void findPortalInChunkAsync(final Chunk chunk, final int waitMs) {
}

private boolean findPortalInChunk(final Chunk chunk) {
final boolean chunkHadPortal = portalsCache.isHighlighted(chunk.getPos().x, chunk.getPos().z);
final boolean chunkHadPortal = portalsCache.isHighlighted(chunk.getPos().x, chunk.getPos().z, ChunkUtils.getActualDimension());
final MutableBlockPos pos = new MutableBlockPos(0, 0, 0);
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
Expand Down Expand Up @@ -161,7 +183,7 @@ private void handleBlockChange(final BlockPos pos, final BlockState state) {
if (inUnknownDimension()) return;
int chunkX = ChunkUtils.posToChunkPos(pos.getX());
int chunkZ = ChunkUtils.posToChunkPos(pos.getZ());
if (portalsCache.isHighlighted(chunkX, chunkZ)) {
if (portalsCache.isHighlighted(chunkX, chunkZ, ChunkUtils.getActualDimension())) {
if (findPortalAtBlockPos(pos)) {
if (mc.world == null || mc.world.getChunkManager() == null) return;
WorldChunk worldChunk = mc.world.getChunkManager().getWorldChunk(chunkX, chunkZ, false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,13 @@ public final class XaeroPlusSettingRegistry {
(b) -> ModuleManager.getModule(Portals.class).setEnabled(b),
false,
SettingLocation.WORLD_MAP_MAIN);
public static final XaeroPlusBooleanSetting portalsSaveLoadToDisk = XaeroPlusBooleanSetting.create(
"Save/Load Portals to Disk",
"setting.world_map.portals_save_load_to_disk",
"setting.world_map.portals_save_load_to_disk.tooltip",
(b) -> ModuleManager.getModule(Portals.class).setPortalsCache(b),
true,
SettingLocation.WORLD_MAP_MAIN);
public static final XaeroPlusFloatSetting portalsAlphaSetting = XaeroPlusFloatSetting.create(
"Portal Highlights Opacity",
"setting.world_map.portals_opacity",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,19 @@ public boolean addHighlight(final int x, final int z, final long foundTime) {
return true;
}

public boolean removeHighlight(final int x, final int z) {
final long chunkPos = chunkPosToLong(x, z);
try {
if (lock.writeLock().tryLock(1, TimeUnit.SECONDS)) {
chunks.remove(chunkPos);
lock.writeLock().unlock();
}
} catch (final Exception e) {
XaeroPlus.LOGGER.error("Failed to add new highlight", e);
}
return true;
}

public boolean isHighlighted(final int x, final int z, RegistryKey<World> dimensionId) {
return isHighlighted(chunkPosToLong(x, z));
}
Expand Down Expand Up @@ -106,17 +119,6 @@ public void loadPreviousState(final Long2LongMap state) {
}
}

public void removeHighlight(final int x, final int z) {
try {
if (lock.writeLock().tryLock(1, TimeUnit.SECONDS)) {
chunks.remove(chunkPosToLong(x, z));
lock.writeLock().unlock();
}
} catch (final Exception e) {
XaeroPlus.LOGGER.error("Error removing highlight", e);
}
}

public void replaceState(final Long2LongOpenHashMap state) {
try {
if (lock.writeLock().tryLock(1, TimeUnit.SECONDS)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

public interface ChunkHighlightCache {
boolean addHighlight(final int x, final int z);
boolean removeHighlight(final int x, final int z);
boolean isHighlighted(final int x, final int z, RegistryKey<World> dimensionId);
List<HighlightAtChunkPos> getHighlightsInRegion(final int leafRegionX, final int leafRegionZ, final int level, RegistryKey<World> dimension);
void handleWorldChange();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,10 @@ public ListenableFuture<?> writeAllHighlightsToDatabase() {
}

@Override
public void removeHighlight(final int x, final int z) {
public boolean removeHighlight(final int x, final int z) {
super.removeHighlight(x, z);
database.removeHighlight(x, z, dimension);
return true;
}

public void close() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,18 @@ public void addHighlight(final int x, final int z, final long foundTime, final R
cacheForDimension.addHighlight(x, z, foundTime);
}

public boolean removeHighlight(final int x, final int z) {
try {
ChunkHighlightCacheDimensionHandler cacheForCurrentDimension = getCacheForCurrentDimension();
if (cacheForCurrentDimension == null) throw new RuntimeException("Didn't find cache for current dimension");
cacheForCurrentDimension.removeHighlight(x, z);
return true;
} catch (final Exception e) {
XaeroPlus.LOGGER.debug("Error removing highlight from saving cache: {}, {}", x, z, e);
return false;
}
}

public boolean isHighlighted(final int chunkPosX, final int chunkPosZ, final RegistryKey<World> dimensionId) {
ChunkHighlightCacheDimensionHandler cacheForDimension = getCacheForDimension(dimensionId);
if (cacheForDimension == null) return false;
Expand Down Expand Up @@ -227,13 +239,4 @@ public void handleTick() {
.forEach(cache -> cache.setWindow(0, 0, 0));
}
}

public void removeHighlight(final int x, final int z) {
try {
ChunkHighlightCacheDimensionHandler cacheForCurrentDimension = getCacheForCurrentDimension();
if (cacheForCurrentDimension != null) cacheForCurrentDimension.removeHighlight(x, z);
} catch (final Exception e) {
XaeroPlus.LOGGER.debug("Error removing highlight from saving cache: {}, {}", x, z, e);
}
}
}
2 changes: 2 additions & 0 deletions src/main/resources/assets/xaeroplus/lang/en_us.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@
"setting.world_map.old_chunks_color.tooltip": "Changes the color of OldChunks.",
"setting.world_map.portals": "Portal Highlights",
"setting.world_map.portals.tooltip": "Highlights chunks where Nether Portals and End Portals are found",
"setting.world_map.portals_save_load_to_disk": "Save/Load Portals to Disk",
"setting.world_map.portals_save_load_to_disk.tooltip": "Saves and loads Portals data to disk for each world and dimension. Requires Portal Highlights to be enabled",
"setting.world_map.portals_opacity": "Portals Opacity",
"setting.world_map.portals_opacity.tooltip": "Changes the color opacity of Portal Highlights.",
"setting.world_map.portals_color": "Portals Color",
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/assets/xaeroplus/lang/fr_ca.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@
"setting.world_map.old_chunks_color.tooltip": "Change la couleur des OldChunks.",
"setting.world_map.portals": "Mise en évidence des portails",
"setting.world_map.portals.tooltip": "Met en évidence les chunks où des portails ont été trouvés sur la Minimap et la WorldMap.",
"setting.world_map.portals_save_load_to_disk": "Enregistrer/Charger les Portails sur le Disque",
"setting.world_map.portals_save_load_to_disk.tooltip": "Enregistre et charge les données des Portails sur le disque pour chaque monde et dimension. Nécessite que les Points de Repère des Portails soient activés",
"setting.world_map.portals_opacity": "Opacité des portails",
"setting.world_map.portals_opacity.tooltip": "Change l'opacité de la couleur des portails mis en évidence.",
"setting.world_map.portals_color": "Couleur des portails",
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/assets/xaeroplus/lang/fr_fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@
"setting.world_map.old_chunks_color.tooltip": "Change la couleur des OldChunks.",
"setting.world_map.portals": "Mise en évidence des portails",
"setting.world_map.portals.tooltip": "Met en évidence les chunks où des portails ont été trouvés sur la Minimap et la WorldMap.",
"setting.world_map.portals_save_load_to_disk": "Enregistrer/Charger les Portails sur le Disque",
"setting.world_map.portals_save_load_to_disk.tooltip": "Enregistre et charge les données des Portails sur le disque pour chaque monde et dimension. Nécessite que les Points de Repère des Portails soient activés",
"setting.world_map.portals_opacity": "Opacité des portails",
"setting.world_map.portals_opacity.tooltip": "Change l'opacité de la couleur des portails mis en évidence.",
"setting.world_map.portals_color": "Couleur des portails",
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/assets/xaeroplus/lang/pl_pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@
"setting.world_map.old_chunks_color.tooltip": "Zmienia kolor OldChunks.",
"setting.world_map.portals": "Podświetlanie Portali",
"setting.world_map.portals.tooltip": "Podświetla chunki, na których znaleziono portale na Minimapie i Mapie Świata.",
"setting.world_map.portals_save_load_to_disk": "Zapisz/Wczytaj Portale na Dysk",
"setting.world_map.portals_save_load_to_disk.tooltip": "Zapisuje i wczytuje dane Portali na dysk dla każdego świata i wymiaru. Wymaga włączenia Wyróżniania Portali",
"setting.world_map.portals_opacity": "Nieprzezroczystość Portali",
"setting.world_map.portals_opacity.tooltip": "Zmienia nieprzezroczystość koloru Podświetlenia Portali.",
"setting.world_map.portals_color": "Kolor Portali",
Expand Down
8 changes: 8 additions & 0 deletions src/main/resources/assets/xaeroplus/lang/ru_ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@
"setting.world_map.old_chunks_opacity.tooltip": "Изменяет непрозрачность цвета OldChunks.",
"setting.world_map.old_chunks_color": "Цвет старых кусков",
"setting.world_map.old_chunks_color.tooltip": "Изменяет цвет OldChunks.",
"setting.world_map.portals": "Podświetlanie Portali",
"setting.world_map.portals.tooltip": "Podświetla chunki, na których znaleziono portale na Minimapie i Mapie Świata.",
"setting.world_map.portals_save_load_to_disk": "Сохранить/Загрузить порталы на диск",
"setting.world_map.portals_save_load_to_disk.tooltip": "Сохраняет и загружает данные порталов на диск для каждого мира и измерения. Требуется включить выделение порталов",
"setting.world_map.portals_opacity": "Nieprzezroczystość Portali",
"setting.world_map.portals_opacity.tooltip": "Zmienia nieprzezroczystość koloru Podświetlenia Portali.",
"setting.world_map.portals_color": "Kolor Portali",
"setting.world_map.portals_color.tooltip": "Zmienia kolor podświetlenia Portali.",
"setting.world_map.portal_skip_detection": "Обнаружение пропуска портала",
"setting.world_map.portal_skip_detection.tooltip": "Выделяет фрагменты, в которые могли быть загружены порталы. \n Это полезно при охоте на базу, чтобы определить, где игроки могут менять размеры вдоль тропы, чтобы избежать охотников. \n Следует отметить одну вещь: расстояние обзора 2b2t недостаточно велико, чтобы обнаружить области пропуска портала. Вам нужно загрузить окружающие фрагменты - в частности, область размером 15х15 фрагментов",
"setting.world_map.portal_skip_opacity": "Непрозрачность пропуска портала",
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/assets/xaeroplus/lang/zh_cn.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@
"setting.world_map.old_chunks_color.tooltip": "更改 OldChunks 的颜色。",
"setting.world_map.portals": "高亮传送门",
"setting.world_map.portals.tooltip": "高亮在小地图和世界地图上找到传送门的区块。",
"setting.world_map.portals_save_load_to_disk": "保存/加载传送门到磁盘",
"setting.world_map.portals_save_load_to_disk.tooltip": "为每个世界和维度保存和加载传送门数据到磁盘。需要启用传送门高亮功能",
"setting.world_map.portals_opacity": "传送门不透明度",
"setting.world_map.portals_opacity.tooltip": "更改高亮传送门颜色的不透明度。",
"setting.world_map.portals_color": "传送门颜色",
Expand Down

0 comments on commit d9657c6

Please sign in to comment.