Input:
import com.extendedclip.deluxemenus.DeluxeMenus;
import com.extendedclip.deluxemenus.menu.Menu;
import com.extendedclip.deluxemenus.menu.MenuHolder;
import com.extendedclip.deluxemenus.utils.AdventureUtils;
import com.extendedclip.deluxemenus.utils.DebugLevel;
import com.extendedclip.deluxemenus.utils.ExpUtils;
import com.extendedclip.deluxemenus.utils.StringUtils;
import com.extendedclip.deluxemenus.utils.VersionHelper;
import java.util.logging.Level;
import me.clip.placeholderapi.PlaceholderAPI;
import net.kyori.adventure.Adventure;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.scheduler.BukkitRunnable;
import org.jetbrains.annotations.NotNull;

Context:
src/main/java/com/extendedclip/deluxemenus/action/ClickActionTask.java
    final String executable = PlaceholderAPI.setPlaceholders((OfflinePlayer) player, exec);
    final MenuHolder holder = Menu.getMenuHolder(player);

    switch (actionType) {
      case META:
        if (!VersionHelper.IS_PDC_VERSION || DeluxeMenus.getInstance().getPersistentMetaHandler() == null) {
          DeluxeMenus.debug(DebugLevel.HIGHEST, Level.INFO, "Meta action not supported on this server version.");
          break;
        }
        try {
          final boolean result = DeluxeMenus.getInstance().getPersistentMetaHandler().setMeta(player, executable);
          if (!result) {
            DeluxeMenus.debug(DebugLevel.HIGHEST, Level.INFO, "Invalid meta action! Make sure you have the right syntax.");
            break;
          }
        } catch (final NumberFormatException exception) {
          DeluxeMenus.debug(DebugLevel.HIGHEST, Level.INFO, "Invalid integer value for meta action!");
        }
        break;

      case PLAYER:
        player.chat("/" + executable);
        break;

      case PLAYER_COMMAND_EVENT:
        Bukkit.getPluginManager().callEvent(new PlayerCommandPreprocessEvent(player, "/" + executable));
        break;

      case PLACEHOLDER:
        PlaceholderAPI.setPlaceholders(player, executable);
        break;

      case CHAT:
        player.chat(executable);
        break;

      case CONSOLE:
        Bukkit.dispatchCommand(Bukkit.getConsoleSender(), executable);
        break;

      case MINI_MESSAGE:
        plugin.adventure().player(player).sendMessage(MiniMessage.miniMessage().deserialize(executable));
        break;

      case MINI_BROADCAST:
        plugin.adventure().all().sendMessage(MiniMessage.miniMessage().deserialize(executable));
        break;

      case MESSAGE:
        player.sendMessage(StringUtils.color(executable));
        break;

      case BROADCAST:
        Bukkit.broadcastMessage(StringUtils.color(executable));
        break;

      case CLOSE:
        Menu.closeMenu(player, true, true);
        break;

      case OPEN_GUI_MENU:
      case OPEN_MENU:
        final Menu menuToOpen = Menu.getMenu(executable);
        if (menuToOpen == null) {
          DeluxeMenus.debug(DebugLevel.HIGHEST, Level.WARNING, "Could not find and open menu " + executable);
          break;
        }

        if (holder == null) {
          menuToOpen.openMenu(player);
          break;
        }

        menuToOpen.openMenu(player, holder.getTypedArgs(), holder.getPlaceholderPlayer());
        break;

      case CONNECT:
        DeluxeMenus.getInstance().connect(player, executable);
        break;

      case JSON_MESSAGE:
        AdventureUtils.sendJson(player, executable);
        break;

      case JSON_BROADCAST:
      case BROADCAST_JSON:
        plugin.adventure().all().sendMessage(AdventureUtils.fromJson(executable));
        break;

      case REFRESH:
        if (holder == null) {
          DeluxeMenus.debug(
              DebugLevel.HIGHEST,
              Level.WARNING,
              player.getName() + " does not have menu open! Nothing to refresh!"
          );
          break;
        }

        holder.refreshMenu();
        break;

      case TAKE_MONEY:
        if (DeluxeMenus.getInstance().getVault() == null || !DeluxeMenus.getInstance().getVault().hooked()) {
          DeluxeMenus.debug(DebugLevel.HIGHEST, Level.WARNING, "Vault not hooked! Cannot take money!");
          break;
        }

        try {
          DeluxeMenus.getInstance().getVault().takeMoney(player, Double.parseDouble(executable));
        } catch (final NumberFormatException exception) {
          DeluxeMenus.debug(
              DebugLevel.HIGHEST,
              Level.WARNING,
              "Amount for take money action: " + executable + ", is not a valid number!"
          );
        }
        break;

      case GIVE_MONEY:

src/main/java/com/extendedclip/deluxemenus/DeluxeMenus.java
public class DeluxeMenus extends JavaPlugin {

  public final static Map<String, Material> MATERIALS
          = Arrays.stream(Material.values()).collect(Collectors.toUnmodifiableMap(Enum::name, Function.identity()));
  private static DeluxeMenus instance;
  private static DebugLevel debugLevel = DebugLevel.LOWEST;
  private DeluxeMenusConfig menuConfig;
  private Map<String, ItemHook> itemHooks;
  private VaultHook vaultHook;
  private boolean checkUpdates;
  private ItemStack head;
  private PersistentMetaHandler persistentMetaHandler;
  private MenuItemMarker menuItemMarker;
  private DupeFixer dupeFixer;
  private BukkitAudiences adventure;

  @Override
  public void onLoad() {
    instance = this;

    this.persistentMetaHandler = new PersistentMetaHandler();

    if (NbtProvider.isAvailable()) {
      DeluxeMenus.debug(
          DebugLevel.HIGHEST,
          Level.INFO,
          "NMS hook has been setup successfully!"
      );
      return;
    }

    debug(
        DebugLevel.HIGHEST,
        Level.WARNING,
        "Could not setup a NMS hook for your server version!"
    );
  }

  @SuppressWarnings("deprecation")
  @Override
  public void onEnable() {
    if (!hookPlaceholderAPI()) {
      debug(
          DebugLevel.HIGHEST,
          Level.SEVERE,
          "Could not hook into PlaceholderAPI!",
          "DeluxeMenus will now disable!"
      );
      Bukkit.getPluginManager().disablePlugin(this);
      return;
    } else {
      debug(
          DebugLevel.HIGHEST,
          Level.INFO,
          "Successfully hooked into PlaceholderAPI!"
      );
    }

    menuItemMarker = new MenuItemMarker(this);
    dupeFixer = new DupeFixer(this, menuItemMarker);

    this.adventure = BukkitAudiences.create(this);

    setupItemHooks();

    if (Bukkit.getPluginManager().isPluginEnabled("Vault")) {
      vaultHook = new VaultHook();

      if (vaultHook.hooked()) {
        debug(
            DebugLevel.HIGHEST,
            Level.INFO,
            "Successfully hooked into Vault!"
        );
      }
    }

    if (!VersionHelper.IS_ITEM_LEGACY) {
      head = new ItemStack(Material.PLAYER_HEAD, 1);
    } else {
      head = new ItemStack(Material.valueOf("SKULL_ITEM"), 1, (short) 3);
    }

    menuConfig = new DeluxeMenusConfig(this);
    if (menuConfig.loadDefConfig()) {
      debugLevel(menuConfig.debugLevel());
      checkUpdates = getConfig().getBoolean("check_updates");
      debug(
          DebugLevel.HIGHEST,
          Level.INFO,
          menuConfig.loadGUIMenus() + " GUI menus loaded!"
      );
    } else {
      debug(
          DebugLevel.HIGHEST,
          Level.WARNING,
          "Failed to load from config.yml. Use /dm reload after fixing your errors."
      );
    }

    new PlayerListener(this);
    new DeluxeMenusCommands(this);
    Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");

    if (checkUpdates) {
      UpdateChecker updateChecker = new UpdateChecker(this);

      if (updateChecker.updateAvailable()) {
        debug(
            DebugLevel.HIGHEST,
            Level.INFO,
            "An update for DeluxeMenus (DeluxeMenus v" + updateChecker.getLatestVersion() + ")",
            "is available at https://www.spigotmc.org/resources/deluxemenus.11734/"
        );
      } else {
        debug(
            DebugLevel.HIGHEST,
            Level.INFO,
            "You are running the latest version of DeluxeMenus!"
        );
      }
    }

    startMetrics();

    new Expansion(this).register();
  }

  @Override
  public void onDisable() {
    Bukkit.getMessenger().unregisterOutgoingPluginChannel(this, "BungeeCord");

    Bukkit.getScheduler().cancelTasks(this);

    if (this.adventure != null) {
      this.adventure.close();
      this.adventure = null;
    }

    Menu.unloadForShutdown();

    itemHooks.clear();

    instance = null;
  }

  private void setupItemHooks() {
    itemHooks = new HashMap<>();

    if (PlaceholderAPIPlugin.getServerVersion().isSpigot()) {
      itemHooks.put(HeadType.NAMED.getHookName(), new NamedHeadHook(this));
      itemHooks.put(HeadType.BASE64.getHookName(), new BaseHeadHook());
      itemHooks.put(HeadType.TEXTURE.getHookName(), new TextureHeadHook());
    }

    if (Bukkit.getPluginManager().isPluginEnabled("HeadDatabase")) {
      try {
        Class.forName("me.arcaniax.hdb.api.HeadDatabaseAPI");
        itemHooks.put(HeadType.HDB.getHookName(), new HeadDatabaseHook());
      } catch (ClassNotFoundException ignored) {}
    }

    if (Bukkit.getPluginManager().isPluginEnabled("ItemsAdder")) {
      itemHooks.put("itemsadder", new ItemsAdderHook());
    }

    if (Bukkit.getPluginManager().isPluginEnabled("Oraxen")) {
      itemHooks.put("oraxen", new OraxenHook());
    }

    if (Bukkit.getPluginManager().isPluginEnabled("MMOItems")) {
      itemHooks.put("mmoitems", new MMOItemsHook());
    }
  }

  public Optional<ItemHook> getItemHook(String id) {
    return Optional.ofNullable(itemHooks.get(id));
  }

  public Map<String, ItemHook> getItemHooks() {
    return itemHooks;
  }

  public ItemStack getHead() {
    return head != null ? head : new ItemStack(Material.DIRT, 1);
  }

  public static DeluxeMenus getInstance() {
    return instance;
  }

  public static DebugLevel debugLevel() {
    return debugLevel;
  }

  public static void debugLevel(final DebugLevel level) {
    debugLevel = level;
  }

  public static DebugLevel printStacktraceLevel() {
    return DebugLevel.MEDIUM;
  }

  public static boolean shouldPrintStackTrace() {
    return debugLevel().getPriority() <= printStacktraceLevel().getPriority();
  }

  public static void printStacktrace(final String message, final Throwable throwable) {
    if (!shouldPrintStackTrace()) return;

    getInstance().getLogger().log(Level.SEVERE, message, throwable);
  }

  private void startMetrics() {
    Metrics metrics = new Metrics(this, 445);
    metrics.addCustomChart(new Metrics.SingleLineChart("menus", Menu::getLoadedMenuSize));
  }

  public void connect(Player p, String server) {
    ByteArrayDataOutput out = ByteStreams.newDataOutput();

    try {
      out.writeUTF("Connect");
      out.writeUTF(server);
    } catch (Exception e) {
      debug(
          DebugLevel.HIGHEST,
          Level.SEVERE,
          "There was a problem attempting to send " + p.getName() + " to server " + server + "!"
      );

      printStacktrace(
          "There was a problem attempting to send " + p.getName() + " to server " + server + "!",
          e
      );
    }

    p.sendPluginMessage(this, "BungeeCord", out.toByteArray());
  }

  public void sms(CommandSender s, Component msg) {
      adventure().sender(s).sendMessage(msg);
  }

  public void sms(CommandSender s, Messages msg) {
    adventure().sender(s).sendMessage(msg.message());
  }

  public static void debug(@NotNull final DebugLevel debugLevel, @NotNull final Level level, @NotNull final String... messages) {
    if (debugLevel().getPriority() > debugLevel.getPriority()) return;

    getInstance().getLogger().log(
        level,
        String.join(System.lineSeparator(), messages)
    );
  }

  private boolean hookPlaceholderAPI() {
    return Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null;
  }

  public MenuItemMarker getMenuItemMarker() {
    return menuItemMarker;
  }

  public DeluxeMenusConfig getConfiguration() {
    return menuConfig;
  }

  public VaultHook getVault() {
    return vaultHook;
  }

  public PersistentMetaHandler getPersistentMetaHandler() {
    return persistentMetaHandler;
  }

  public BukkitAudiences adventure() {
    if (this.adventure == null) {
      throw new IllegalStateException("Tried to access Adventure when the plugin was disabled!");
    }
    return this.adventure;
  }

  public void clearCaches() {
    itemHooks.values().stream()
            .filter(Objects::nonNull)
            .filter(hook -> hook instanceof SimpleCache)
            .map(hook -> (SimpleCache) hook)
            .forEach(SimpleCache::clearCache);
  }
}

src/main/java/com/extendedclip/deluxemenus/utils/StringUtils.java
public class StringUtils {

  private final static Pattern HEX_PATTERN = Pattern
      .compile("&(#[a-f0-9]{6})", Pattern.CASE_INSENSITIVE);

  /**
   * Translates the ampersand color codes like '&7' to their section symbol counterparts like '§7'.
   * <br>
   * It also translates hex colors like '&#aaFF00' to their section symbol counterparts like '§x§a§a§F§F§0§0'.
   *
   * @param input The string in which to translate the color codes.
   * @return The string with the translated colors.
   */
  @NotNull
  public static String color(@NotNull String input) {
    //Hex Support for 1.16.1+
    Matcher m = HEX_PATTERN.matcher(input);
    if (VersionHelper.IS_HEX_VERSION) {
      while (m.find()) {
        input = input.replace(m.group(), ChatColor.of(m.group(1)).toString());
      }
    }

    return ChatColor.translateAlternateColorCodes('&', input);
  }

}

src/main/java/com/extendedclip/deluxemenus/menu/MenuHolder.java
public class MenuHolder implements InventoryHolder {

  private final Player viewer;
  private Player placeholderPlayer;
  private String menuName;
  private Set<MenuItem> activeItems;
  private BukkitTask updateTask = null;
  private Inventory inventory;
  private boolean updating;
  private Map<String, String> typedArgs;

  public MenuHolder(Player viewer) {
    this.viewer = viewer;
  }

  public MenuHolder(Player viewer, String menuName,
      Set<MenuItem> activeItems, Inventory inventory) {
    this.viewer = viewer;
    this.menuName = menuName;
    this.activeItems = activeItems;
    this.inventory = inventory;
  }

  public String getViewerName() {
    return viewer.getName();
  }

  public BukkitTask getUpdateTask() {
    return updateTask;
  }

  public Player getViewer() {
    return viewer;
  }

  public String getMenuName() {
    return menuName;
  }

  public void setMenuName(String menuName) {
    this.menuName = menuName;
  }

  public Set<MenuItem> getActiveItems() {
    return activeItems;
  }

  public void setActiveItems(Set<MenuItem> items) {
    this.activeItems = items;
  }

  public MenuHolder getHolder() {
    return this;
  }

  public MenuItem getItem(int slot) {
    for (MenuItem item : activeItems) {
      if (item.options().slot() == slot) {
        return item;
      }
    }
    return null;
  }

  public Menu getMenu() {
    return Menu.getMenu(menuName);
  }

  public String setPlaceholders(String string) {
    // Set argument placeholders first
    if (this.typedArgs != null && !this.typedArgs.isEmpty()) {
      for (Entry<String, String> entry : typedArgs.entrySet()) {
        string = string.replace("{" + entry.getKey() + "}", entry.getValue());
      }
    }

    // Then set actual PAPI placeholders
    if (placeholderPlayer != null) {
      return PlaceholderAPI.setPlaceholders((OfflinePlayer) placeholderPlayer, string);
    } else {
      return this.getViewer() == null ? string
              : PlaceholderAPI.setPlaceholders((OfflinePlayer) this.getViewer(), string);
    }
  }

  public String setArguments(String string) {
    if (this.typedArgs == null || this.typedArgs.isEmpty()) {
      return string;
    }
    for (Entry<String, String> entry : this.typedArgs.entrySet()) {
      string = string.replace("{" + entry.getKey() + "}", entry.getValue());
    }
    return string;
  }

  public void refreshMenu() {

    Menu menu = getMenu();

    if (menu == null || menu.getMenuItems() == null || menu.getMenuItems().size() <= 0) {
      return;
    }

    setUpdating(true);

    stopPlaceholderUpdate();

    Bukkit.getScheduler().runTaskAsynchronously(DeluxeMenus.getInstance(), () -> {

      final Set<MenuItem> active = new HashSet<>();

      for (int i = 0; i < getInventory().getSize(); i++) {
        TreeMap<Integer, MenuItem> e = menu.getMenuItems().get(i);

        if (e == null) {
          getInventory().setItem(i, null);
          continue;
        }

        boolean m = false;
        for (MenuItem item : e.values()) {

          if (item.options().viewRequirements().isPresent()) {

            if (item.options().viewRequirements().get().evaluate(this)) {
              m = true;
              active.add(item);
              break;
            }
          } else {
            m = true;
            active.add(item);
            break;
          }
        }

        if (!m) {
          getInventory().setItem(i, null);
        }
      }

      if (active.isEmpty()) {
        Menu.closeMenu(getViewer(), true);
      }

      Bukkit.getScheduler().runTask(DeluxeMenus.getInstance(), () -> {

        boolean update = false;

        for (MenuItem item : active) {

          ItemStack iStack = item.getItemStack(this);

          int slot = item.options().slot();

          if (slot >= menu.getSize()) {
            continue;
          }

          if (item.options().updatePlaceholders()) {
            update = true;
          }

          getInventory().setItem(item.options().slot(), iStack);
        }

        setActiveItems(active);

        if (update) {
          startUpdatePlaceholdersTask();
        }

        setUpdating(false);
      });
    });
  }

  public void stopPlaceholderUpdate() {
    if (updateTask != null) {
      try {
        updateTask.cancel();
      } catch (Exception ignored) {
      }
      updateTask = null;
    }
  }

  public void startUpdatePlaceholdersTask() {

    if (updateTask != null) {
      stopPlaceholderUpdate();
    }

    updateTask = new BukkitRunnable() {

      @Override
      public void run() {

        if (updating) {
          return;
        }

        Set<MenuItem> items = getActiveItems();

        if (items == null) {
          return;
        }

        for (MenuItem item : items) {

          if (item.options().updatePlaceholders()) {

            ItemStack i = inventory.getItem(item.options().slot());

            if (i == null) {
              continue;
            }

            int amt = i.getAmount();

            if (item.options().dynamicAmount().isPresent()) {
              try {
               amt = Integer.parseInt(setPlaceholders(item.options().dynamicAmount().get()));
                if (amt <= 0) {
                  amt = 1;
                }
              } catch (Exception exception) {
                DeluxeMenus.printStacktrace(
                    "Something went wrong while updating item in slot " + item.options().slot() +
                        ". Invalid dynamic amount: " + setPlaceholders(item.options().dynamicAmount().get()),
                    exception
                );
              }
            }

            ItemMeta meta = i.getItemMeta();

            if (item.options().displayNameHasPlaceholders() && item.options().displayName().isPresent()) {
              meta.setDisplayName(StringUtils.color(setPlaceholders(item.options().displayName().get())));
            }

            if (item.options().loreHasPlaceholders()) {

              List<String> updated = new ArrayList<>();

              for (String line : item.options().lore()) {
                updated.add(StringUtils
                    .color(setPlaceholders(line)));
              }
              meta.setLore(updated);
            }

            i.setItemMeta(meta);
            i.setAmount(amt);
          }
        }
      }

    }.runTaskTimerAsynchronously(DeluxeMenus.getInstance(), 20L,
        20L * Menu.getMenu(menuName).getUpdateInterval());
  }

  public boolean isUpdating() {
    return updating;
  }

  public void setUpdating(boolean updating) {
    this.updating = updating;
  }

  @Override
  public Inventory getInventory() {
    return this.inventory;
  }

  public void setInventory(Inventory i) {
    this.inventory = i;
  }

  public Map<String, String> getTypedArgs() {
    return typedArgs;
  }

  public void setTypedArgs(Map<String, String> typedArgs) {
    this.typedArgs = typedArgs;
  }

  public void setPlaceholderPlayer(Player placeholderPlayer) {
    this.placeholderPlayer = placeholderPlayer;
  }

  public Player getPlaceholderPlayer() {
    return placeholderPlayer;
  }
}

src/main/java/com/extendedclip/deluxemenus/utils/ExpUtils.java
public final class ExpUtils {
    private ExpUtils() {
        throw new AssertionError("Util classes should not be initialized");
    }

    /**
     * Set the player's experience to the given value.
     * @param target The player to set the experience of.
     * @param stringAmount The amount of experience to set. Can end with an 'l' to set the experience levels.
     * @throws NumberFormatException If the stringAmount is not a valid number.
     */
    public static void setExp(
        @NotNull final Player target,
        @NotNull final String stringAmount
    ) throws NumberFormatException {
        long amount;
        final String lowerCase = stringAmount.toLowerCase(Locale.ENGLISH);

        if (stringAmount.contains("l")) {
            final int neededLevel = Integer.parseInt(lowerCase.replaceAll("l", "")) + target.getLevel();
            amount = getExpToLevel(neededLevel) + (getTotalExperience(target) - getExpToLevel(target.getLevel()));
            setTotalExperience(target, 0);
        }
        else {
            amount = Long.parseLong(lowerCase);
        }
        amount += getTotalExperience(target);
        if (amount > Integer.MAX_VALUE) {
            amount = Integer.MAX_VALUE;
        }
        if (amount < 0L) {
            amount = 0L;
        }
        setTotalExperience(target, (int) amount);
    }

    /**
     * Set the player's experience to the given value.
     * <br>
     * This method updates both the record total experience and displayed total experience.
     *
     * @param player The player to set the total experience for.
     * @param exp The amount of experience to set.
     * @throws IllegalArgumentException If the exp amount is less than 0.
     */
    public static void setTotalExperience(
        @NotNull final Player player,
        final int exp
    ) throws IllegalArgumentException {
        if (exp < 0) {
            throw new IllegalArgumentException("Experience is negative!");
        }

        player.setExp(0);
        player.setLevel(0);
        player.setTotalExperience(0);

        int amount = exp;
        while (amount > 0) {
            final int expToLevel = getExpAtLevel(player);
            amount -= expToLevel;
            if (amount >= 0) {
                player.giveExp(expToLevel);
            } else {
                amount += expToLevel;
                player.giveExp(amount);
                amount = 0;
            }
        }
    }

    /**
     * Get the amount of experience required to reach the given level.
     * @param player The player to get the experience for.
     * @return The amount of experience required to reach the given level.
     */
    private static int getExpAtLevel(@NotNull final Player player) {
        return getExpAtLevel(player.getLevel());
    }

    /**
     * Get the amount of experience points required to reach the next level from the given level.
     * @param level The level to calculate the required experience points to level up for.
     * @return The amount of experience required to reach the next level from the given one.
     */
    public static int getExpAtLevel(final int level) {
        if (level <= 15) {
            return (2 * level) + 7;
        }
        if (level <= 30) {
            return (5 * level) - 38;
        }
        return (9 * level) - 158;
    }

    /**
     * Translates the given amount of levels to the amount of experience points required to get to this level from 0.
     * @param level The amount of levels to translate.
     * @return The amount of experience points required to reach the given level from 0.
     */
    public static int getExpToLevel(final int level) {
        int currentLevel = 0;
        int exp = 0;

        while (currentLevel < level) {
            exp += getExpAtLevel(currentLevel);
            currentLevel++;
        }
        if (exp < 0) {
            exp = Integer.MAX_VALUE;
        }
        return exp;
    }

    /**
     * Get the total amount of experience points that the given player has right now.
     * @param player The player to get the experience for.
     * @return The total amount of experience points that the given player has.
     */
    public static int getTotalExperience(@NotNull final Player player) {
        int exp = Math.round(getExpAtLevel(player) * player.getExp());
        int currentLevel = player.getLevel();

        while (currentLevel > 0) {
            currentLevel--;
            exp += getExpAtLevel(currentLevel);
        }
        if (exp < 0) {
            exp = Integer.MAX_VALUE;
        }
        return exp;
    }
}

src/main/java/com/extendedclip/deluxemenus/utils/AdventureUtils.java
public final class AdventureUtils {
    private final static GsonComponentSerializer gson = GsonComponentSerializer.gson();

    private AdventureUtils() {
        throw new AssertionError("Util classes should not be initialized");
    }

    public static void sendJson(CommandSender sender, String json) {
        DeluxeMenus.getInstance().adventure().sender(sender).sendMessage(fromJson(json));
    }

    public static Component fromJson(String json) {
        return gson.deserialize(json);
    }
}

src/main/java/com/extendedclip/deluxemenus/utils/DebugLevel.java
public enum DebugLevel {
    LOWEST(0, "LOWEST"),
    LOW(1, "LOW"),
    MEDIUM(2, "MEDIUM"),
    HIGH(3, "HIGH"),
    HIGHEST(4, "HIGHEST");

    private final String[] names;
    private final int priority;

    private DebugLevel(final int priority, @NotNull final String... names) {
        this.priority = priority;
        this.names = names;
    }

    public int getPriority() {
        return priority;
    }

    private static final Map<String, DebugLevel> LEVELS = Arrays.stream(values())
        .flatMap(level -> Arrays.stream(level.names).map(name -> Map.entry(name.toLowerCase(Locale.ROOT), level)))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    public static @Nullable DebugLevel getByName(@NotNull final String name) {
        return LEVELS.get(name.toLowerCase(Locale.ROOT));
    }
}

src/main/java/com/extendedclip/deluxemenus/utils/VersionHelper.java
public final class VersionHelper {

    private static final String PACKAGE_NAME = Bukkit.getServer().getClass().getPackage().getName();
    public static final String NMS_VERSION = PACKAGE_NAME.substring(PACKAGE_NAME.lastIndexOf('.') + 1);

    // PlayerProfile API
    private static final int V1_18_1 = 1181;
    // Mojang obfuscation changes
    private static final int V1_17 = 1170;
    // Material and components on items change
    private static final int V1_13 = 1130;
    // PDC and customModelData
    private static final int V1_14 = 1140;
    // Hex colors
    private static final int V1_16 = 1160;
    // Paper adventure changes
    private static final int V1_16_5 = 1165;
    // SkullMeta#setOwningPlayer was added
    private static final int V1_12 = 1120;

    public static final int CURRENT_VERSION = getCurrentVersion();

    private static final boolean IS_PAPER = checkPaper();

    /**
     * Checks if current version includes the PlayerProfile API
     */
    public static final boolean HAS_PLAYER_PROFILES = CURRENT_VERSION >= V1_18_1;

    /**
     * Checks if the current version was a version without versioned packages.
     */
    public static final boolean HAS_OBFUSCATED_NAMES = CURRENT_VERSION >= V1_17;

    /**
     * Checks if the version supports Components or not
     * Paper versions above 1.16.5 would be true
     * Spigot always false
     */
    public static final boolean IS_COMPONENT = IS_PAPER && CURRENT_VERSION >= V1_16_5;

    /**
     * Checks if the version is lower than 1.13 due to the item changes
     */
    public static final boolean IS_ITEM_LEGACY = CURRENT_VERSION < V1_13;

    /**
     * Checks if the version supports {@link org.bukkit.persistence.PersistentDataContainer}
     */
    public static final boolean IS_PDC_VERSION = CURRENT_VERSION >= V1_14;

    /**
     * Checks if the version doesn't have {@link org.bukkit.inventory.meta.SkullMeta#setOwningPlayer(OfflinePlayer)} and
     * {@link org.bukkit.inventory.meta.SkullMeta#setOwner(String)} should be used instead
     */
    public static final boolean IS_SKULL_OWNER_LEGACY = CURRENT_VERSION <= V1_12;

    /**
     * Checks if the version has {@link org.bukkit.inventory.meta.ItemMeta#setCustomModelData(Integer)}
     */
    public static final boolean IS_CUSTOM_MODEL_DATA = CURRENT_VERSION >= V1_14;

    public static final boolean IS_HEX_VERSION = CURRENT_VERSION >= V1_16;

    private static List<InventoryType> CHEST_INVENTORY_TYPES = null;

    private static List<InventoryType> VALID_INVENTORY_TYPES = null;

    private static List<InventoryType> getChestInventoryTypes() {
        if (CHEST_INVENTORY_TYPES != null) return CHEST_INVENTORY_TYPES;

        if (CURRENT_VERSION >= V1_14) {
            CHEST_INVENTORY_TYPES = List.of(
                    InventoryType.BARREL,
                    InventoryType.CHEST,
                    InventoryType.CRAFTING,
                    InventoryType.CREATIVE,
                    InventoryType.ENDER_CHEST,
                    InventoryType.LECTERN,
                    InventoryType.MERCHANT,
                    InventoryType.SHULKER_BOX
            );

            return CHEST_INVENTORY_TYPES;
        }

        CHEST_INVENTORY_TYPES = List.of(
                InventoryType.CHEST,
                InventoryType.CRAFTING,
                InventoryType.CREATIVE,
                InventoryType.ENDER_CHEST,
                InventoryType.MERCHANT,
                InventoryType.SHULKER_BOX
        );

        return CHEST_INVENTORY_TYPES;
    }

    public static List<InventoryType> getValidInventoryTypes() {
        if (VALID_INVENTORY_TYPES != null) return VALID_INVENTORY_TYPES;

        final List<InventoryType> chestInventoryTypes = getChestInventoryTypes();
        final List<InventoryType> validInventoryTypes = new ArrayList<>();

        for (final InventoryType inventoryType : InventoryType.values()) {
            if (inventoryType != InventoryType.CHEST && chestInventoryTypes.contains(inventoryType)) continue;
            validInventoryTypes.add(inventoryType);
        }

        VALID_INVENTORY_TYPES = validInventoryTypes;
        return VALID_INVENTORY_TYPES;
    }

    /**
     * Check if the server has access to the Paper API
     * Taken from <a href="https://github.com/PaperMC/PaperLib">PaperLib</a>
     *
     * @return True if on Paper server (or forks), false anything else
     */
    private static boolean checkPaper() {
        try {
            Class.forName("com.destroystokyo.paper.PaperConfig");
            return true;
        } catch (ClassNotFoundException ignored) {
            return false;
        }
    }

    /**
     * Gets the current server version
     *
     * @return A protocol like number representing the version, for example 1.16.5 - 1165
     */
    private static int getCurrentVersion() {
        // No need to cache since will only run once
        final Matcher matcher = Pattern.compile("(?<version>\\d+\\.\\d+)(?<patch>\\.\\d+)?").matcher(Bukkit.getBukkitVersion());

        final StringBuilder stringBuilder = new StringBuilder();
        if (matcher.find()) {
            stringBuilder.append(matcher.group("version").replace(".", ""));
            final String patch = matcher.group("patch");
            if (patch == null) stringBuilder.append("0");
            else stringBuilder.append(patch.replace(".", ""));
        }

        //noinspection UnstableApiUsage
        final Integer version = Ints.tryParse(stringBuilder.toString());

        // Should never fail
        if (version == null) throw new RuntimeException("Could not retrieve server version!");

        return version;
    }

    public static String getNmsVersion() {
        final String version = Bukkit.getServer().getClass().getPackage().getName();
        return version.substring(version.lastIndexOf('.') + 1);
    }

    /**
     * Gets the NMS class from class name.
     *
     * @return The NMS class.
     */
    public static Class<?> getNMSClass(final String pkg, final String className) throws ClassNotFoundException {
        if (VersionHelper.HAS_OBFUSCATED_NAMES) {
            return Class.forName("net.minecraft." + pkg + "."  + className);
        }
        return Class.forName("net.minecraft.server." + VersionHelper.NMS_VERSION + "." + className);
    }

    /**
     * Gets the craft class from class name.
     *
     * @return The craft class.
     */
    public static Class<?> getCraftClass(@NotNull final String name) throws ClassNotFoundException {
        return Class.forName("org.bukkit.craftbukkit." + NMS_VERSION + "." + name);
    }

}

src/main/java/com/extendedclip/deluxemenus/menu/Menu.java
public class Menu extends Command {

  private static final Map<String, Menu> menus = new HashMap<>();
  private static final Set<MenuHolder> holders = new HashSet<>();
  private static final Map<UUID, Menu> lastMenus = new HashMap<>();
  private static CommandMap commandMap = null;
  private final String menuName;
  private final String menuTitle;
  private final int size;
  private final Map<Integer, TreeMap<Integer, MenuItem>> items;
  private InventoryType type;
  private List<String> menuCommands;
  private int updateInterval;
  private RequirementList openRequirements;
  private ClickHandler openHandler, closeHandler;
  private boolean registersCommand;
  // args
  private List<String> args;
  private List<RequirementList> argRequirements;
  private String argUsageMessage;

  public Menu(String menuName, String menuTitle, Map<Integer, TreeMap<Integer, MenuItem>> items,
      int size, List<String> menuCommands, boolean registerCommand, List<String> args, List<RequirementList> argRequirements) {
    super(menuCommands.get(0));
    this.menuName = menuName;
    this.menuTitle = StringUtils.color(menuTitle);
    this.items = items;
    this.size = size;
    this.menuCommands = menuCommands;
    this.registersCommand = registerCommand;
    this.args = args;
    this.argRequirements = argRequirements;
    if (registerCommand) {
      if (menuCommands.size() > 1) {
        this.setAliases(menuCommands.subList(1, menuCommands.size()));
      }
      addCommand();
    }
    menus.put(this.menuName, this);
  }

  public Menu(String menuName, String menuTitle, Map<Integer, TreeMap<Integer, MenuItem>> items,
      int size) {
    super(menuName);
    this.menuName = menuName;
    this.menuTitle = StringUtils.color(menuTitle);
    this.items = items;
    this.size = size;
    menus.put(this.menuName, this);
  }

  public static void unload(String menu) {
    for (Player p : Bukkit.getOnlinePlayers()) {
      if (inMenu(p, menu)) {
        closeMenu(p, true);
      }
    }
    Menu m = Menu.getMenu(menu);
    if (m == null) {
      return;
    }

    m.removeCommand();
    menus.remove(menu);
  }

  public static void unload() {
    for (Player p : Bukkit.getOnlinePlayers()) {
      if (inMenu(p)) {
        closeMenu(p, true);
      }
    }
    if (Menu.getAllMenus() != null) {
      for (Menu menu : Menu.getAllMenus()) {
        menu.removeCommand();
      }
    }
    menus.clear();
    holders.clear();
    lastMenus.clear();
  }

  public static void unloadForShutdown() {
    for (Player player : Bukkit.getOnlinePlayers()) {
      if (inMenu(player)) {
        closeMenuForShutdown(player);
      }
    }
    menus.clear();
  }

  public static int getLoadedMenuSize() {
    return menus.size();
  }

  public static Menu getMenu(Player p) {
    return getOpenMenu(p);
  }

  public static Collection<Menu> getAllMenus() {
    return !menus.isEmpty() ? menus.values() : null;
  }

  public static Menu getMenu(String menuName) {
    for (Entry<String, Menu> e : menus.entrySet()) {
      if (e.getKey().equalsIgnoreCase(menuName)) {
        return e.getValue();
      }
    }
    return null;
  }

  public static Menu getMenuByCommand(String command) {
    for (Menu m : menus.values()) {
      if (m.getMenuCommandUsed(command) != null) {
        return m;
      }
    }
    return null;
  }

  public static boolean isMenuCommand(String command) {
    return getMenuByCommand(command) != null;
  }

  public static boolean inMenu(Player p) {
    return holders.stream().anyMatch(h -> h.getViewerName().equals(p.getName()));
  }

  public static boolean inMenu(Player p, String menu) {
    return holders.stream().anyMatch(h -> h.getMenuName().equals(menu) && h.getViewerName().equals(p.getName()));
  }

  public static MenuHolder getMenuHolder(Player p) {
    return holders.stream().filter(h -> h.getViewerName().equals(p.getName())).findFirst()
        .orElse(null);
  }

  public static Menu getOpenMenu(Player p) {
    MenuHolder h = getMenuHolder(p);
    return h == null ? null : h.getMenu();
  }
  public static Menu getLastMenu(Player p) {
    return lastMenus.get(p.getUniqueId());
  }

  public static void cleanInventory(Player player, @NotNull final MenuItemMarker marker) {
    if (player == null) {
      return;
    }
    for (final ItemStack itemStack : player.getInventory().getContents()) {
      if (itemStack == null) continue;
      if (!marker.isMarked(itemStack)) continue;

      DeluxeMenus.debug(
              DebugLevel.LOWEST,
              Level.INFO,
                "Found a DeluxeMenus item in a player's inventory. Removing it."
      );
      player.getInventory().remove(itemStack);
    }
    player.updateInventory();
  }

  public static void closeMenu(final Player p, boolean close, boolean executeCloseActions) {

    MenuHolder holder = getMenuHolder(p);
    if (holder == null) {
      return;
    }

    holder.stopPlaceholderUpdate();

    if (executeCloseActions) {
      if (holder.getMenu().getCloseHandler() != null) {
        holder.getMenu().getCloseHandler().onClick(holder);
      }
    }

    if (close) {
      Bukkit.getScheduler().runTask(DeluxeMenus.getInstance(), () -> {
        p.closeInventory();
        cleanInventory(p, DeluxeMenus.getInstance().getMenuItemMarker());
      });
    }
    holders.remove(holder);
    lastMenus.put(p.getUniqueId(), holder.getMenu());
  }

  public static void closeMenuForShutdown(final Player p) {
    MenuHolder holder = getMenuHolder(p);
    if (holder == null) {
      return;
    }

    holder.stopPlaceholderUpdate();

    p.closeInventory();
    cleanInventory(p, DeluxeMenus.getInstance().getMenuItemMarker());
  }

  public static void closeMenu(final Player p, boolean close) {
    closeMenu(p, close, false);
  }

  private void addCommand() {
    if (commandMap == null) {
      try {
        final Field f = Bukkit.getServer().getClass().getDeclaredField("commandMap");
        f.setAccessible(true);
        commandMap = (CommandMap) f.get(Bukkit.getServer());
      } catch (Exception e) {
        e.printStackTrace();
        return;
      }
    }
    boolean registered = commandMap.register("DeluxeMenus", this);
    if (registered) {
      DeluxeMenus.debug(
          DebugLevel.LOW,
          Level.INFO,
          "Registered command: " + this.getName() + " for menu: " + this.getMenuName()
      );
    }
  }

  private void removeCommand() {
    if (commandMap != null && this.registersCommand()) {
      Field cMap;
      Field knownCommands;
      try {
        cMap = Bukkit.getServer().getClass().getDeclaredField("commandMap");
        cMap.setAccessible(true);
        knownCommands = SimpleCommandMap.class.getDeclaredField("knownCommands");
        knownCommands.setAccessible(true);
        ((Map<String, Command>) knownCommands.get((SimpleCommandMap) cMap.get(Bukkit.getServer())))
            .remove(this.getName());
        boolean unregistered = this.unregister((CommandMap) cMap.get(Bukkit.getServer()));
        this.unregister(commandMap);
        if (unregistered) {
          DeluxeMenus.debug(
              DebugLevel.HIGH,
              Level.INFO,
              "Successfully unregistered command: " + this.getName()
          );
        } else {
          DeluxeMenus.debug(
              DebugLevel.HIGHEST,
              Level.WARNING,
              "Failed to unregister command: " + this.getName()
          );
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }

  @Override
  public boolean execute(CommandSender sender, String commandLabel, String[] typedArgs) {
    if (!(sender instanceof Player)) {
      Msg.msg(sender, "Menus can only be opened by players!");
      return true;
    }

    Map<String, String> argMap = null;

    if (!this.args.isEmpty()) {
      DeluxeMenus.debug(DebugLevel.LOWEST, Level.INFO, "has args");
      if (typedArgs.length < this.args.size()) {
        if (this.argUsageMessage != null) {
          Msg.msg(sender, this.argUsageMessage);
        }
        return true;
      }
      argMap = new HashMap<>();
      int index = 0;
      for (String arg : this.args) {
        if (index + 1 == this.args.size()) {
          String last = String.join(" ", Arrays.asList(typedArgs).subList(index, typedArgs.length));
          DeluxeMenus.debug(DebugLevel.LOWEST, Level.INFO, "arg: " + arg + " => " + last);
          argMap.put(arg, last);
        } else {
          argMap.put(arg, typedArgs[index]);
          DeluxeMenus.debug(DebugLevel.LOWEST, Level.INFO, "arg: " + arg + " => " + typedArgs[index]);
        }
        index++;
      }
    }

    Player player = (Player) sender;
    DeluxeMenus.debug(DebugLevel.LOWEST, Level.INFO, "opening menu: " + this.menuName);
    openMenu(player, argMap, null);
    return true;
  }

  private boolean hasOpenBypassPerm(Player viewer) {
    return viewer.hasPermission("deluxemenus.openrequirement.bypass." + menuName)
        || viewer.hasPermission("deluxemenus.openrequirement.bypass.*");
  }

  private boolean handleOpenRequirements(MenuHolder holder) {
    if (openRequirements == null || openRequirements.getRequirements() == null) {
      return true;
    }

    if (holder.getViewer() != null && this.hasOpenBypassPerm(holder.getViewer())) {
      return true;
    }

    if (!openRequirements.evaluate(holder)) {
      if (openRequirements.getDenyHandler() != null) {
        openRequirements.getDenyHandler().onClick(holder);
      }
      return false;
    }
    return true;
  }

  private boolean handleArgRequirements(MenuHolder holder) {
    if (argRequirements == null) {
      return true;
    }

    for (RequirementList rl : argRequirements) {
      if (rl.getRequirements() == null) {
        continue;
      }

      if (!rl.evaluate(holder)) {
        if (rl.getDenyHandler() != null) {
          rl.getDenyHandler().onClick(holder);
        }
        return false;
      }
    }

    return true;
  }

  public void openMenu(final Player viewer) {
    openMenu(viewer, null, null);
  }

  public void openMenu(final Player viewer, final Map<String, String> args, final Player placeholderPlayer) {
    if (menuTitle == null || items == null || items.size() <= 0) {
      return;
    }

    final MenuHolder holder = new MenuHolder(viewer);
    if (placeholderPlayer != null) {
      holder.setPlaceholderPlayer(placeholderPlayer);
    }
    holder.setTypedArgs(args);

    if (!this.handleArgRequirements(holder)) {
      return;
    }

    if (!this.handleOpenRequirements(holder)) {
      return;
    }

    Bukkit.getScheduler().runTaskAsynchronously(DeluxeMenus.getInstance(), () -> {

      Set<MenuItem> activeItems = new HashSet<>();

      for (Entry<Integer, TreeMap<Integer, MenuItem>> entry : items.entrySet()) {

        for (MenuItem item : entry.getValue().values()) {

          int slot = item.options().slot();

          if (slot >= size) {
            DeluxeMenus.debug(
                DebugLevel.HIGHEST,
                Level.WARNING,
                "Item set to slot " + slot + " for menu: " + menuName + " exceeds the inventory size!",
                "This item will not be added to the menu!"
            );
            continue;
          }

          if (item.options().viewRequirements().isPresent()) {

            if (item.options().viewRequirements().get().evaluate(holder)) {

              activeItems.add(item);
              break;
            }
          } else {

            activeItems.add(item);
            break;
          }
        }
      }

      if (activeItems.isEmpty()) {
        return;
      }

      holder.setMenuName(menuName);
      holder.setActiveItems(activeItems);

      if (this.openHandler != null) {
        this.openHandler.onClick(holder);
      }

      String title = StringUtils.color(holder.setPlaceholders(this.menuTitle));

      Inventory inventory;

      if (type != null) {
        inventory = Bukkit.createInventory(holder, type, title);
      } else {
        inventory = Bukkit.createInventory(holder, size, title);
      }

      holder.setInventory(inventory);

      boolean update = false;

      for (MenuItem item : activeItems) {

        ItemStack iStack = item.getItemStack(holder);

        if (iStack == null) {
          continue;
        }

        iStack = DeluxeMenus.getInstance().getMenuItemMarker().mark(iStack);

        int slot = item.options().slot();

        if (slot >= size) {
          DeluxeMenus.debug(
              DebugLevel.HIGHEST,
              Level.WARNING,
              "Item set to slot " + slot + " for menu: " + menuName + " exceeds the inventory size!",
              "This item will not be added to the menu!"
          );
          continue;
        }

        if (item.options().updatePlaceholders()) {
          update = true;
        }

        inventory.setItem(item.options().slot(), iStack);
      }

      final boolean updatePlaceholders = update;

      Bukkit.getScheduler().runTask(DeluxeMenus.getInstance(), () -> {
        if (inMenu(holder.getViewer())) {
          closeMenu(holder.getViewer(), false);
        }

        viewer.openInventory(inventory);
        holders.add(holder);

        if (updatePlaceholders) {
          holder.startUpdatePlaceholdersTask();
        }
      });
    });
  }

  public String getMenuTitle() {
    return menuTitle;
  }

  public String getMenuName() {
    return this.menuName;
  }

  public List<String> getMenuCommands() {
    return this.menuCommands;
  }

  public Map<Integer, TreeMap<Integer, MenuItem>> getMenuItems() {
    return this.items;
  }

  public int getSize() {
    return this.size;
  }

  public int getUpdateInterval() {
    return updateInterval >= 1 ? updateInterval : 10;
  }

  public void setUpdateInterval(int updateInterval) {
    this.updateInterval = updateInterval;
  }

  public String getMenuCommandUsed(String command) {
    if (getMenuCommands() == null) {
      return null;
    }
    for (String c : getMenuCommands()) {
      if (command.equalsIgnoreCase(c)) {
        return c;
      }
    }
    return null;
  }

  public RequirementList getOpenRequirements() {
    return openRequirements;
  }

  public void setOpenRequirements(RequirementList openRequirements) {
    this.openRequirements = openRequirements;
  }

  public InventoryType getInventoryType() {
    return type;
  }

  public void setInventoryType(InventoryType type) {
    this.type = type;
  }

  public ClickHandler getOpenHandler() {
    return openHandler;
  }

  public void setOpenHandler(ClickHandler openHandler) {
    this.openHandler = openHandler;
  }

  public ClickHandler getCloseHandler() {
    return closeHandler;
  }

  public void setCloseHandler(ClickHandler closeHandler) {
    this.closeHandler = closeHandler;
  }

  public boolean registersCommand() {
    return registersCommand;
  }

  public String getArgUsageMessage() {
    return argUsageMessage;
  }

  public void setArgUsageMessage(String argUsageMessage) {
    this.argUsageMessage = argUsageMessage;
  }
}

Answer: if (DeluxeMenus.getInstance().getVault() == null || !DeluxeMenus.getInstance().getVault().hooked()) {

<think>
The switch case for GIVE_MONEY is analogous to the TAKE_MONEY case just above. The next line should start the vault availability check, matching the pattern used earlier. Therefore the next line is the if statement that verifies Vault is hooked before proceeding with the give money action.
</think>
if (DeluxeMenus.getInstance().getVault() == null || !DeluxeMenus.getInstance().getVault().hooked()) {


Input:
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import threestudio
            import trimesh
from dataclasses import dataclass, field
from threestudio.models.geometry.base import (
    BaseExplicitGeometry,
    BaseGeometry,
    contract_to_unisphere,
)
from threestudio.models.geometry.implicit_sdf import ImplicitSDF
from threestudio.models.geometry.implicit_volume import ImplicitVolume
from threestudio.models.isosurface import MarchingTetrahedraHelper
from threestudio.models.mesh import Mesh
from threestudio.models.networks import get_encoding, get_mlp
from threestudio.utils.misc import broadcast
from threestudio.utils.ops import scale_tensor
from threestudio.utils.typing import *
            from pysdf import SDF

Context:
threestudio/models/geometry/tetrahedra_sdf_grid.py

@threestudio.register("tetrahedra-sdf-grid")
class TetrahedraSDFGrid(BaseExplicitGeometry):
    @dataclass

threestudio/models/networks.py
def get_mlp(n_input_dims, n_output_dims, config) -> nn.Module:
    network: nn.Module
    if config.otype == "VanillaMLP":
        network = VanillaMLP(n_input_dims, n_output_dims, config_to_primitive(config))
    elif config.otype == "SphereInitVanillaMLP":
        network = SphereInitVanillaMLP(
            n_input_dims, n_output_dims, config_to_primitive(config)
        )
    else:
        assert (
            config.get("sphere_init", False) is False
        ), "sphere_init=True only supported by VanillaMLP"
        network = TCNNNetwork(n_input_dims, n_output_dims, config_to_primitive(config))
    return network

threestudio/utils/misc.py
def broadcast(tensor, src=0):
    if not _distributed_available():
        return tensor
    else:
        torch.distributed.broadcast(tensor, src=src)
        return tensor

threestudio/models/geometry/base.py
class BaseGeometry(BaseModule):
    @dataclass
    class Config(BaseModule.Config):
        pass

    cfg: Config

    @staticmethod
    def create_from(
        other: "BaseGeometry", cfg: Optional[Union[dict, DictConfig]] = None, **kwargs
    ) -> "BaseGeometry":
        raise TypeError(
            f"Cannot create {BaseGeometry.__name__} from {other.__class__.__name__}"
        )

    def export(self, *args, **kwargs) -> Dict[str, Any]:
        return {}

threestudio/models/mesh.py
class Mesh:
    def __init__(
        self, v_pos: Float[Tensor, "Nv 3"], t_pos_idx: Integer[Tensor, "Nf 3"], **kwargs
    ) -> None:
        self.v_pos: Float[Tensor, "Nv 3"] = v_pos
        self.t_pos_idx: Integer[Tensor, "Nf 3"] = t_pos_idx
        self._v_nrm: Optional[Float[Tensor, "Nv 3"]] = None
        self._v_tng: Optional[Float[Tensor, "Nv 3"]] = None
        self._v_tex: Optional[Float[Tensor, "Nt 3"]] = None
        self._t_tex_idx: Optional[Float[Tensor, "Nf 3"]] = None
        self._v_rgb: Optional[Float[Tensor, "Nv 3"]] = None
        self._edges: Optional[Integer[Tensor, "Ne 2"]] = None
        self.extras: Dict[str, Any] = {}
        for k, v in kwargs.items():
            self.add_extra(k, v)

    def add_extra(self, k, v) -> None:
        self.extras[k] = v

    def remove_outlier(self, outlier_n_faces_threshold: Union[int, float]) -> Mesh:
        if self.requires_grad:
            threestudio.debug("Mesh is differentiable, not removing outliers")
            return self

        # use trimesh to first split the mesh into connected components
        # then remove the components with less than n_face_threshold faces
        import trimesh

        # construct a trimesh object
        mesh = trimesh.Trimesh(
            vertices=self.v_pos.detach().cpu().numpy(),
            faces=self.t_pos_idx.detach().cpu().numpy(),
        )

        # split the mesh into connected components
        components = mesh.split(only_watertight=False)
        # log the number of faces in each component
        threestudio.debug(
            "Mesh has {} components, with faces: {}".format(
                len(components), [c.faces.shape[0] for c in components]
            )
        )

        n_faces_threshold: int
        if isinstance(outlier_n_faces_threshold, float):
            # set the threshold to the number of faces in the largest component multiplied by outlier_n_faces_threshold
            n_faces_threshold = int(
                max([c.faces.shape[0] for c in components]) * outlier_n_faces_threshold
            )
        else:
            # set the threshold directly to outlier_n_faces_threshold
            n_faces_threshold = outlier_n_faces_threshold

        # log the threshold
        threestudio.debug(
            "Removing components with less than {} faces".format(n_faces_threshold)
        )

        # remove the components with less than n_face_threshold faces
        components = [c for c in components if c.faces.shape[0] >= n_faces_threshold]

        # log the number of faces in each component after removing outliers
        threestudio.debug(
            "Mesh has {} components after removing outliers, with faces: {}".format(
                len(components), [c.faces.shape[0] for c in components]
            )
        )
        # merge the components
        mesh = trimesh.util.concatenate(components)

        # convert back to our mesh format
        v_pos = torch.from_numpy(mesh.vertices).to(self.v_pos)
        t_pos_idx = torch.from_numpy(mesh.faces).to(self.t_pos_idx)

        clean_mesh = Mesh(v_pos, t_pos_idx)
        # keep the extras unchanged

        if len(self.extras) > 0:
            clean_mesh.extras = self.extras
            threestudio.debug(
                f"The following extra attributes are inherited from the original mesh unchanged: {list(self.extras.keys())}"
            )
        return clean_mesh

    @property
    def requires_grad(self):
        return self.v_pos.requires_grad

    @property
    def v_nrm(self):
        if self._v_nrm is None:
            self._v_nrm = self._compute_vertex_normal()
        return self._v_nrm

    @property
    def v_tng(self):
        if self._v_tng is None:
            self._v_tng = self._compute_vertex_tangent()
        return self._v_tng

    @property
    def v_tex(self):
        if self._v_tex is None:
            self._v_tex, self._t_tex_idx = self._unwrap_uv()
        return self._v_tex

    @property
    def t_tex_idx(self):
        if self._t_tex_idx is None:
            self._v_tex, self._t_tex_idx = self._unwrap_uv()
        return self._t_tex_idx

    @property
    def v_rgb(self):
        return self._v_rgb

    @property
    def edges(self):
        if self._edges is None:
            self._edges = self._compute_edges()
        return self._edges

    def _compute_vertex_normal(self):
        i0 = self.t_pos_idx[:, 0]
        i1 = self.t_pos_idx[:, 1]
        i2 = self.t_pos_idx[:, 2]

        v0 = self.v_pos[i0, :]
        v1 = self.v_pos[i1, :]
        v2 = self.v_pos[i2, :]

        face_normals = torch.cross(v1 - v0, v2 - v0)

        # Splat face normals to vertices
        v_nrm = torch.zeros_like(self.v_pos)
        v_nrm.scatter_add_(0, i0[:, None].repeat(1, 3), face_normals)
        v_nrm.scatter_add_(0, i1[:, None].repeat(1, 3), face_normals)
        v_nrm.scatter_add_(0, i2[:, None].repeat(1, 3), face_normals)

        # Normalize, replace zero (degenerated) normals with some default value
        v_nrm = torch.where(
            dot(v_nrm, v_nrm) > 1e-20, v_nrm, torch.as_tensor([0.0, 0.0, 1.0]).to(v_nrm)
        )
        v_nrm = F.normalize(v_nrm, dim=1)

        if torch.is_anomaly_enabled():
            assert torch.all(torch.isfinite(v_nrm))

        return v_nrm

    def _compute_vertex_tangent(self):
        vn_idx = [None] * 3
        pos = [None] * 3
        tex = [None] * 3
        for i in range(0, 3):
            pos[i] = self.v_pos[self.t_pos_idx[:, i]]
            tex[i] = self.v_tex[self.t_tex_idx[:, i]]
            # t_nrm_idx is always the same as t_pos_idx
            vn_idx[i] = self.t_pos_idx[:, i]

        tangents = torch.zeros_like(self.v_nrm)
        tansum = torch.zeros_like(self.v_nrm)

        # Compute tangent space for each triangle
        uve1 = tex[1] - tex[0]
        uve2 = tex[2] - tex[0]
        pe1 = pos[1] - pos[0]
        pe2 = pos[2] - pos[0]

        nom = pe1 * uve2[..., 1:2] - pe2 * uve1[..., 1:2]
        denom = uve1[..., 0:1] * uve2[..., 1:2] - uve1[..., 1:2] * uve2[..., 0:1]

        # Avoid division by zero for degenerated texture coordinates
        tang = nom / torch.where(
            denom > 0.0, torch.clamp(denom, min=1e-6), torch.clamp(denom, max=-1e-6)
        )

        # Update all 3 vertices
        for i in range(0, 3):
            idx = vn_idx[i][:, None].repeat(1, 3)
            tangents.scatter_add_(0, idx, tang)  # tangents[n_i] = tangents[n_i] + tang
            tansum.scatter_add_(
                0, idx, torch.ones_like(tang)
            )  # tansum[n_i] = tansum[n_i] + 1
        tangents = tangents / tansum

        # Normalize and make sure tangent is perpendicular to normal
        tangents = F.normalize(tangents, dim=1)
        tangents = F.normalize(tangents - dot(tangents, self.v_nrm) * self.v_nrm)

        if torch.is_anomaly_enabled():
            assert torch.all(torch.isfinite(tangents))

        return tangents

    def _unwrap_uv(
        self, xatlas_chart_options: dict = {}, xatlas_pack_options: dict = {}
    ):
        threestudio.info("Using xatlas to perform UV unwrapping, may take a while ...")

        import xatlas

        atlas = xatlas.Atlas()
        atlas.add_mesh(
            self.v_pos.detach().cpu().numpy(),
            self.t_pos_idx.cpu().numpy(),
        )
        co = xatlas.ChartOptions()
        po = xatlas.PackOptions()
        for k, v in xatlas_chart_options.items():
            setattr(co, k, v)
        for k, v in xatlas_pack_options.items():
            setattr(po, k, v)
        atlas.generate(co, po)
        vmapping, indices, uvs = atlas.get_mesh(0)
        vmapping = (
            torch.from_numpy(
                vmapping.astype(np.uint64, casting="same_kind").view(np.int64)
            )
            .to(self.v_pos.device)
            .long()
        )
        uvs = torch.from_numpy(uvs).to(self.v_pos.device).float()
        indices = (
            torch.from_numpy(
                indices.astype(np.uint64, casting="same_kind").view(np.int64)
            )
            .to(self.v_pos.device)
            .long()
        )
        return uvs, indices

    def unwrap_uv(
        self, xatlas_chart_options: dict = {}, xatlas_pack_options: dict = {}
    ):
        self._v_tex, self._t_tex_idx = self._unwrap_uv(
            xatlas_chart_options, xatlas_pack_options
        )

    def set_vertex_color(self, v_rgb):
        assert v_rgb.shape[0] == self.v_pos.shape[0]
        self._v_rgb = v_rgb

    def _compute_edges(self):
        # Compute edges
        edges = torch.cat(
            [
                self.t_pos_idx[:, [0, 1]],
                self.t_pos_idx[:, [1, 2]],
                self.t_pos_idx[:, [2, 0]],
            ],
            dim=0,
        )
        edges = edges.sort()[0]
        edges = torch.unique(edges, dim=0)
        return edges

    def normal_consistency(self) -> Float[Tensor, ""]:
        edge_nrm: Float[Tensor, "Ne 2 3"] = self.v_nrm[self.edges]
        nc = (
            1.0 - torch.cosine_similarity(edge_nrm[:, 0], edge_nrm[:, 1], dim=-1)
        ).mean()
        return nc

    def _laplacian_uniform(self):
        # from stable-dreamfusion
        # https://github.com/ashawkey/stable-dreamfusion/blob/8fb3613e9e4cd1ded1066b46e80ca801dfb9fd06/nerf/renderer.py#L224
        verts, faces = self.v_pos, self.t_pos_idx

        V = verts.shape[0]
        F = faces.shape[0]

        # Neighbor indices
        ii = faces[:, [1, 2, 0]].flatten()
        jj = faces[:, [2, 0, 1]].flatten()
        adj = torch.stack([torch.cat([ii, jj]), torch.cat([jj, ii])], dim=0).unique(
            dim=1
        )
        adj_values = torch.ones(adj.shape[1]).to(verts)

        # Diagonal indices
        diag_idx = adj[0]

        # Build the sparse matrix
        idx = torch.cat((adj, torch.stack((diag_idx, diag_idx), dim=0)), dim=1)
        values = torch.cat((-adj_values, adj_values))

        # The coalesce operation sums the duplicate indices, resulting in the
        # correct diagonal
        return torch.sparse_coo_tensor(idx, values, (V, V)).coalesce()

    def laplacian(self) -> Float[Tensor, ""]:
        with torch.no_grad():
            L = self._laplacian_uniform()
        loss = L.mm(self.v_pos)
        loss = loss.norm(dim=1)
        loss = loss.mean()
        return loss

threestudio/models/geometry/implicit_sdf.py
class ImplicitSDF(BaseImplicitGeometry):
    @dataclass
    class Config(BaseImplicitGeometry.Config):
        n_input_dims: int = 3
        n_feature_dims: int = 3
        pos_encoding_config: dict = field(
            default_factory=lambda: {
                "otype": "HashGrid",
                "n_levels": 16,
                "n_features_per_level": 2,
                "log2_hashmap_size": 19,
                "base_resolution": 16,
                "per_level_scale": 1.447269237440378,
            }
        )
        mlp_network_config: dict = field(
            default_factory=lambda: {
                "otype": "VanillaMLP",
                "activation": "ReLU",
                "output_activation": "none",
                "n_neurons": 64,
                "n_hidden_layers": 1,
            }
        )
        normal_type: Optional[
            str
        ] = "finite_difference"  # in ['pred', 'finite_difference', 'finite_difference_laplacian']
        finite_difference_normal_eps: Union[
            float, str
        ] = 0.01  # in [float, "progressive"]
        shape_init: Optional[str] = None
        shape_init_params: Optional[Any] = None
        shape_init_mesh_up: str = "+z"
        shape_init_mesh_front: str = "+x"
        force_shape_init: bool = False
        sdf_bias: Union[float, str] = 0.0
        sdf_bias_params: Optional[Any] = None

        # no need to removal outlier for SDF
        isosurface_remove_outliers: bool = False

    cfg: Config

    def configure(self) -> None:
        super().configure()
        self.encoding = get_encoding(
            self.cfg.n_input_dims, self.cfg.pos_encoding_config
        )
        self.sdf_network = get_mlp(
            self.encoding.n_output_dims, 1, self.cfg.mlp_network_config
        )

        if self.cfg.n_feature_dims > 0:
            self.feature_network = get_mlp(
                self.encoding.n_output_dims,
                self.cfg.n_feature_dims,
                self.cfg.mlp_network_config,
            )

        if self.cfg.normal_type == "pred":
            self.normal_network = get_mlp(
                self.encoding.n_output_dims, 3, self.cfg.mlp_network_config
            )
        if self.cfg.isosurface_deformable_grid:
            assert (
                self.cfg.isosurface_method == "mt"
            ), "isosurface_deformable_grid only works with mt"
            self.deformation_network = get_mlp(
                self.encoding.n_output_dims, 3, self.cfg.mlp_network_config
            )

        self.finite_difference_normal_eps: Optional[float] = None

    def initialize_shape(self) -> None:
        if self.cfg.shape_init is None and not self.cfg.force_shape_init:
            return

        # do not initialize shape if weights are provided
        if self.cfg.weights is not None and not self.cfg.force_shape_init:
            return

        if self.cfg.sdf_bias != 0.0:
            threestudio.warn(
                "shape_init and sdf_bias are both specified, which may lead to unexpected results."
            )

        get_gt_sdf: Callable[[Float[Tensor, "N 3"]], Float[Tensor, "N 1"]]
        assert isinstance(self.cfg.shape_init, str)
        if self.cfg.shape_init == "ellipsoid":
            assert (
                isinstance(self.cfg.shape_init_params, Sized)
                and len(self.cfg.shape_init_params) == 3
            )
            size = torch.as_tensor(self.cfg.shape_init_params).to(self.device)

            def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]:
                return ((points_rand / size) ** 2).sum(
                    dim=-1, keepdim=True
                ).sqrt() - 1.0  # pseudo signed distance of an ellipsoid

            get_gt_sdf = func
        elif self.cfg.shape_init == "sphere":
            assert isinstance(self.cfg.shape_init_params, float)
            radius = self.cfg.shape_init_params

            def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]:
                return (points_rand**2).sum(dim=-1, keepdim=True).sqrt() - radius

            get_gt_sdf = func
        elif self.cfg.shape_init.startswith("mesh:"):
            assert isinstance(self.cfg.shape_init_params, float)
            mesh_path = self.cfg.shape_init[5:]
            if not os.path.exists(mesh_path):
                raise ValueError(f"Mesh file {mesh_path} does not exist.")

            import trimesh

            scene = trimesh.load(mesh_path)
            if isinstance(scene, trimesh.Trimesh):
                mesh = scene
            elif isinstance(scene, trimesh.scene.Scene):
                mesh = trimesh.Trimesh()
                for obj in scene.geometry.values():
                    mesh = trimesh.util.concatenate([mesh, obj])
            else:
                raise ValueError(f"Unknown mesh type at {mesh_path}.")

            # move to center
            centroid = mesh.vertices.mean(0)
            mesh.vertices = mesh.vertices - centroid

            # align to up-z and front-x
            dirs = ["+x", "+y", "+z", "-x", "-y", "-z"]
            dir2vec = {
                "+x": np.array([1, 0, 0]),
                "+y": np.array([0, 1, 0]),
                "+z": np.array([0, 0, 1]),
                "-x": np.array([-1, 0, 0]),
                "-y": np.array([0, -1, 0]),
                "-z": np.array([0, 0, -1]),
            }
            if (
                self.cfg.shape_init_mesh_up not in dirs
                or self.cfg.shape_init_mesh_front not in dirs
            ):
                raise ValueError(
                    f"shape_init_mesh_up and shape_init_mesh_front must be one of {dirs}."
                )
            if self.cfg.shape_init_mesh_up[1] == self.cfg.shape_init_mesh_front[1]:
                raise ValueError(
                    "shape_init_mesh_up and shape_init_mesh_front must be orthogonal."
                )
            z_, x_ = (
                dir2vec[self.cfg.shape_init_mesh_up],
                dir2vec[self.cfg.shape_init_mesh_front],
            )
            y_ = np.cross(z_, x_)
            std2mesh = np.stack([x_, y_, z_], axis=0).T
            mesh2std = np.linalg.inv(std2mesh)

            # scaling
            scale = np.abs(mesh.vertices).max()
            mesh.vertices = mesh.vertices / scale * self.cfg.shape_init_params
            mesh.vertices = np.dot(mesh2std, mesh.vertices.T).T

            from pysdf import SDF

            sdf = SDF(mesh.vertices, mesh.faces)

            def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]:
                # add a negative signed here
                # as in pysdf the inside of the shape has positive signed distance
                return torch.from_numpy(-sdf(points_rand.cpu().numpy())).to(
                    points_rand
                )[..., None]

            get_gt_sdf = func

        else:
            raise ValueError(
                f"Unknown shape initialization type: {self.cfg.shape_init}"
            )

        # Initialize SDF to a given shape when no weights are provided or force_shape_init is True
        optim = torch.optim.Adam(self.parameters(), lr=1e-3)
        from tqdm import tqdm

        for _ in tqdm(
            range(1000),
            desc=f"Initializing SDF to a(n) {self.cfg.shape_init}:",
            disable=get_rank() != 0,
        ):
            points_rand = (
                torch.rand((10000, 3), dtype=torch.float32).to(self.device) * 2.0 - 1.0
            )
            sdf_gt = get_gt_sdf(points_rand)
            sdf_pred = self.forward_sdf(points_rand)
            loss = F.mse_loss(sdf_pred, sdf_gt)
            optim.zero_grad()
            loss.backward()
            optim.step()

        # explicit broadcast to ensure param consistency across ranks
        for param in self.parameters():
            broadcast(param, src=0)

    def get_shifted_sdf(
        self, points: Float[Tensor, "*N Di"], sdf: Float[Tensor, "*N 1"]
    ) -> Float[Tensor, "*N 1"]:
        sdf_bias: Union[float, Float[Tensor, "*N 1"]]
        if self.cfg.sdf_bias == "ellipsoid":
            assert (
                isinstance(self.cfg.sdf_bias_params, Sized)
                and len(self.cfg.sdf_bias_params) == 3
            )
            size = torch.as_tensor(self.cfg.sdf_bias_params).to(points)
            sdf_bias = ((points / size) ** 2).sum(
                dim=-1, keepdim=True
            ).sqrt() - 1.0  # pseudo signed distance of an ellipsoid
        elif self.cfg.sdf_bias == "sphere":
            assert isinstance(self.cfg.sdf_bias_params, float)
            radius = self.cfg.sdf_bias_params
            sdf_bias = (points**2).sum(dim=-1, keepdim=True).sqrt() - radius
        elif isinstance(self.cfg.sdf_bias, float):
            sdf_bias = self.cfg.sdf_bias
        else:
            raise ValueError(f"Unknown sdf bias {self.cfg.sdf_bias}")
        return sdf + sdf_bias

    def forward(
        self, points: Float[Tensor, "*N Di"], output_normal: bool = False
    ) -> Dict[str, Float[Tensor, "..."]]:
        grad_enabled = torch.is_grad_enabled()

        if output_normal and self.cfg.normal_type == "analytic":
            torch.set_grad_enabled(True)
            points.requires_grad_(True)

        points_unscaled = points  # points in the original scale
        points = contract_to_unisphere(
            points, self.bbox, self.unbounded
        )  # points normalized to (0, 1)

        enc = self.encoding(points.view(-1, self.cfg.n_input_dims))
        sdf = self.sdf_network(enc).view(*points.shape[:-1], 1)
        sdf = self.get_shifted_sdf(points_unscaled, sdf)
        output = {"sdf": sdf}

        if self.cfg.n_feature_dims > 0:
            features = self.feature_network(enc).view(
                *points.shape[:-1], self.cfg.n_feature_dims
            )
            output.update({"features": features})

        if output_normal:
            if (
                self.cfg.normal_type == "finite_difference"
                or self.cfg.normal_type == "finite_difference_laplacian"
            ):
                assert self.finite_difference_normal_eps is not None
                eps: float = self.finite_difference_normal_eps
                if self.cfg.normal_type == "finite_difference_laplacian":
                    offsets: Float[Tensor, "6 3"] = torch.as_tensor(
                        [
                            [eps, 0.0, 0.0],
                            [-eps, 0.0, 0.0],
                            [0.0, eps, 0.0],
                            [0.0, -eps, 0.0],
                            [0.0, 0.0, eps],
                            [0.0, 0.0, -eps],
                        ]
                    ).to(points_unscaled)
                    points_offset: Float[Tensor, "... 6 3"] = (
                        points_unscaled[..., None, :] + offsets
                    ).clamp(-self.cfg.radius, self.cfg.radius)
                    sdf_offset: Float[Tensor, "... 6 1"] = self.forward_sdf(
                        points_offset
                    )
                    sdf_grad = (
                        0.5
                        * (sdf_offset[..., 0::2, 0] - sdf_offset[..., 1::2, 0])
                        / eps
                    )
                else:
                    offsets: Float[Tensor, "3 3"] = torch.as_tensor(
                        [[eps, 0.0, 0.0], [0.0, eps, 0.0], [0.0, 0.0, eps]]
                    ).to(points_unscaled)
                    points_offset: Float[Tensor, "... 3 3"] = (
                        points_unscaled[..., None, :] + offsets
                    ).clamp(-self.cfg.radius, self.cfg.radius)
                    sdf_offset: Float[Tensor, "... 3 1"] = self.forward_sdf(
                        points_offset
                    )
                    sdf_grad = (sdf_offset[..., 0::1, 0] - sdf) / eps
                normal = F.normalize(sdf_grad, dim=-1)
            elif self.cfg.normal_type == "pred":
                normal = self.normal_network(enc).view(*points.shape[:-1], 3)
                normal = F.normalize(normal, dim=-1)
                sdf_grad = normal
            elif self.cfg.normal_type == "analytic":
                sdf_grad = -torch.autograd.grad(
                    sdf,
                    points_unscaled,
                    grad_outputs=torch.ones_like(sdf),
                    create_graph=True,
                )[0]
                normal = F.normalize(sdf_grad, dim=-1)
                if not grad_enabled:
                    sdf_grad = sdf_grad.detach()
                    normal = normal.detach()
            else:
                raise AttributeError(f"Unknown normal type {self.cfg.normal_type}")
            output.update(
                {"normal": normal, "shading_normal": normal, "sdf_grad": sdf_grad}
            )
        return output

    def forward_sdf(self, points: Float[Tensor, "*N Di"]) -> Float[Tensor, "*N 1"]:
        points_unscaled = points
        points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)

        sdf = self.sdf_network(
            self.encoding(points.reshape(-1, self.cfg.n_input_dims))
        ).reshape(*points.shape[:-1], 1)
        sdf = self.get_shifted_sdf(points_unscaled, sdf)
        return sdf

    def forward_field(
        self, points: Float[Tensor, "*N Di"]
    ) -> Tuple[Float[Tensor, "*N 1"], Optional[Float[Tensor, "*N 3"]]]:
        points_unscaled = points
        points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)
        enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims))
        sdf = self.sdf_network(enc).reshape(*points.shape[:-1], 1)
        sdf = self.get_shifted_sdf(points_unscaled, sdf)
        deformation: Optional[Float[Tensor, "*N 3"]] = None
        if self.cfg.isosurface_deformable_grid:
            deformation = self.deformation_network(enc).reshape(*points.shape[:-1], 3)
        return sdf, deformation

    def forward_level(
        self, field: Float[Tensor, "*N 1"], threshold: float
    ) -> Float[Tensor, "*N 1"]:
        return field - threshold

    def export(self, points: Float[Tensor, "*N Di"], **kwargs) -> Dict[str, Any]:
        out: Dict[str, Any] = {}
        if self.cfg.n_feature_dims == 0:
            return out
        points_unscaled = points
        points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)
        enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims))
        features = self.feature_network(enc).view(
            *points.shape[:-1], self.cfg.n_feature_dims
        )
        out.update(
            {
                "features": features,
            }
        )
        return out

    def update_step(self, epoch: int, global_step: int, on_load_weights: bool = False):
        if (
            self.cfg.normal_type == "finite_difference"
            or self.cfg.normal_type == "finite_difference_laplacian"
        ):
            if isinstance(self.cfg.finite_difference_normal_eps, float):
                self.finite_difference_normal_eps = (
                    self.cfg.finite_difference_normal_eps
                )
            elif self.cfg.finite_difference_normal_eps == "progressive":
                # progressive finite difference eps from Neuralangelo
                # https://arxiv.org/abs/2306.03092
                hg_conf: Any = self.cfg.pos_encoding_config
                assert (
                    hg_conf.otype == "ProgressiveBandHashGrid"
                ), "finite_difference_normal_eps=progressive only works with ProgressiveBandHashGrid"
                current_level = min(
                    hg_conf.start_level
                    + max(global_step - hg_conf.start_step, 0) // hg_conf.update_steps,
                    hg_conf.n_levels,
                )
                grid_res = hg_conf.base_resolution * hg_conf.per_level_scale ** (
                    current_level - 1
                )
                grid_size = 2 * self.cfg.radius / grid_res
                if grid_size != self.finite_difference_normal_eps:
                    threestudio.info(
                        f"Update finite_difference_normal_eps to {grid_size}"
                    )
                self.finite_difference_normal_eps = grid_size
            else:
                raise ValueError(
                    f"Unknown finite_difference_normal_eps={self.cfg.finite_difference_normal_eps}"
                )

threestudio/utils/ops.py
def scale_tensor(
    dat: Num[Tensor, "... D"], inp_scale: ValidScale, tgt_scale: ValidScale
):
    if inp_scale is None:
        inp_scale = (0, 1)
    if tgt_scale is None:
        tgt_scale = (0, 1)
    if isinstance(tgt_scale, Tensor):
        assert dat.shape[-1] == tgt_scale.shape[-1]
    dat = (dat - inp_scale[0]) / (inp_scale[1] - inp_scale[0])
    dat = dat * (tgt_scale[1] - tgt_scale[0]) + tgt_scale[0]
    return dat

threestudio/models/geometry/base.py
def contract_to_unisphere(
    x: Float[Tensor, "... 3"], bbox: Float[Tensor, "2 3"], unbounded: bool = False
) -> Float[Tensor, "... 3"]:
    if unbounded:
        x = scale_tensor(x, bbox, (0, 1))
        x = x * 2 - 1  # aabb is at [-1, 1]
        mag = x.norm(dim=-1, keepdim=True)
        mask = mag.squeeze(-1) > 1
        x[mask] = (2 - 1 / mag[mask]) * (x[mask] / mag[mask])
        x = x / 4 + 0.5  # [-inf, inf] is at [0, 1]
    else:
        x = scale_tensor(x, bbox, (0, 1))
    return x

threestudio/models/geometry/implicit_volume.py
class ImplicitVolume(BaseImplicitGeometry):
    @dataclass
    class Config(BaseImplicitGeometry.Config):
        n_input_dims: int = 3
        n_feature_dims: int = 3
        density_activation: Optional[str] = "softplus"
        density_bias: Union[float, str] = "blob_magic3d"
        density_blob_scale: float = 10.0
        density_blob_std: float = 0.5
        pos_encoding_config: dict = field(
            default_factory=lambda: {
                "otype": "HashGrid",
                "n_levels": 16,
                "n_features_per_level": 2,
                "log2_hashmap_size": 19,
                "base_resolution": 16,
                "per_level_scale": 1.447269237440378,
            }
        )
        mlp_network_config: dict = field(
            default_factory=lambda: {
                "otype": "VanillaMLP",
                "activation": "ReLU",
                "output_activation": "none",
                "n_neurons": 64,
                "n_hidden_layers": 1,
            }
        )
        normal_type: Optional[
            str
        ] = "finite_difference"  # in ['pred', 'finite_difference', 'finite_difference_laplacian']
        finite_difference_normal_eps: Union[
            float, str
        ] = 0.01  # in [float, "progressive"]

        # automatically determine the threshold
        isosurface_threshold: Union[float, str] = 25.0

        # 4D Gaussian Annealing
        anneal_density_blob_std_config: Optional[dict] = None

    cfg: Config

    def configure(self) -> None:
        super().configure()
        self.encoding = get_encoding(
            self.cfg.n_input_dims, self.cfg.pos_encoding_config
        )
        self.density_network = get_mlp(
            self.encoding.n_output_dims, 1, self.cfg.mlp_network_config
        )
        if self.cfg.n_feature_dims > 0:
            self.feature_network = get_mlp(
                self.encoding.n_output_dims,
                self.cfg.n_feature_dims,
                self.cfg.mlp_network_config,
            )
        if self.cfg.normal_type == "pred":
            self.normal_network = get_mlp(
                self.encoding.n_output_dims, 3, self.cfg.mlp_network_config
            )

        self.finite_difference_normal_eps: Optional[float] = None

    def get_activated_density(
        self, points: Float[Tensor, "*N Di"], density: Float[Tensor, "*N 1"]
    ) -> Tuple[Float[Tensor, "*N 1"], Float[Tensor, "*N 1"]]:
        density_bias: Union[float, Float[Tensor, "*N 1"]]
        if self.cfg.density_bias == "blob_dreamfusion":
            # pre-activation density bias
            density_bias = (
                self.cfg.density_blob_scale
                * torch.exp(
                    -0.5 * (points**2).sum(dim=-1) / self.cfg.density_blob_std**2
                )[..., None]
            )
        elif self.cfg.density_bias == "blob_magic3d":
            # pre-activation density bias
            density_bias = (
                self.cfg.density_blob_scale
                * (
                    1
                    - torch.sqrt((points**2).sum(dim=-1)) / self.cfg.density_blob_std
                )[..., None]
            )
        elif isinstance(self.cfg.density_bias, float):
            density_bias = self.cfg.density_bias
        else:
            raise ValueError(f"Unknown density bias {self.cfg.density_bias}")
        raw_density: Float[Tensor, "*N 1"] = density + density_bias
        density = get_activation(self.cfg.density_activation)(raw_density)
        return raw_density, density

    def forward(
        self, points: Float[Tensor, "*N Di"], output_normal: bool = False
    ) -> Dict[str, Float[Tensor, "..."]]:
        grad_enabled = torch.is_grad_enabled()

        if output_normal and self.cfg.normal_type == "analytic":
            torch.set_grad_enabled(True)
            points.requires_grad_(True)

        points_unscaled = points  # points in the original scale
        points = contract_to_unisphere(
            points, self.bbox, self.unbounded
        )  # points normalized to (0, 1)

        enc = self.encoding(points.view(-1, self.cfg.n_input_dims))
        density = self.density_network(enc).view(*points.shape[:-1], 1)
        raw_density, density = self.get_activated_density(points_unscaled, density)

        output = {
            "density": density,
        }

        if self.cfg.n_feature_dims > 0:
            features = self.feature_network(enc).view(
                *points.shape[:-1], self.cfg.n_feature_dims
            )
            output.update({"features": features})

        if output_normal:
            if (
                self.cfg.normal_type == "finite_difference"
                or self.cfg.normal_type == "finite_difference_laplacian"
            ):
                # TODO: use raw density
                assert self.finite_difference_normal_eps is not None
                eps: float = self.finite_difference_normal_eps
                if self.cfg.normal_type == "finite_difference_laplacian":
                    offsets: Float[Tensor, "6 3"] = torch.as_tensor(
                        [
                            [eps, 0.0, 0.0],
                            [-eps, 0.0, 0.0],
                            [0.0, eps, 0.0],
                            [0.0, -eps, 0.0],
                            [0.0, 0.0, eps],
                            [0.0, 0.0, -eps],
                        ]
                    ).to(points_unscaled)
                    points_offset: Float[Tensor, "... 6 3"] = (
                        points_unscaled[..., None, :] + offsets
                    ).clamp(-self.cfg.radius, self.cfg.radius)
                    density_offset: Float[Tensor, "... 6 1"] = self.forward_density(
                        points_offset
                    )
                    normal = (
                        -0.5
                        * (density_offset[..., 0::2, 0] - density_offset[..., 1::2, 0])
                        / eps
                    )
                else:
                    offsets: Float[Tensor, "3 3"] = torch.as_tensor(
                        [[eps, 0.0, 0.0], [0.0, eps, 0.0], [0.0, 0.0, eps]]
                    ).to(points_unscaled)
                    points_offset: Float[Tensor, "... 3 3"] = (
                        points_unscaled[..., None, :] + offsets
                    ).clamp(-self.cfg.radius, self.cfg.radius)
                    density_offset: Float[Tensor, "... 3 1"] = self.forward_density(
                        points_offset
                    )
                    normal = -(density_offset[..., 0::1, 0] - density) / eps
                normal = F.normalize(normal, dim=-1)
            elif self.cfg.normal_type == "pred":
                normal = self.normal_network(enc).view(*points.shape[:-1], 3)
                normal = F.normalize(normal, dim=-1)
            elif self.cfg.normal_type == "analytic":
                normal = -torch.autograd.grad(
                    density,
                    points_unscaled,
                    grad_outputs=torch.ones_like(density),
                    create_graph=True,
                )[0]
                normal = F.normalize(normal, dim=-1)
                if not grad_enabled:
                    normal = normal.detach()
            else:
                raise AttributeError(f"Unknown normal type {self.cfg.normal_type}")
            output.update({"normal": normal, "shading_normal": normal})

        torch.set_grad_enabled(grad_enabled)
        return output

    def forward_density(self, points: Float[Tensor, "*N Di"]) -> Float[Tensor, "*N 1"]:
        points_unscaled = points
        points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)

        density = self.density_network(
            self.encoding(points.reshape(-1, self.cfg.n_input_dims))
        ).reshape(*points.shape[:-1], 1)

        _, density = self.get_activated_density(points_unscaled, density)
        return density

    def forward_field(
        self, points: Float[Tensor, "*N Di"]
    ) -> Tuple[Float[Tensor, "*N 1"], Optional[Float[Tensor, "*N 3"]]]:
        if self.cfg.isosurface_deformable_grid:
            threestudio.warn(
                f"{self.__class__.__name__} does not support isosurface_deformable_grid. Ignoring."
            )
        density = self.forward_density(points)
        return density, None

    def forward_level(
        self, field: Float[Tensor, "*N 1"], threshold: float
    ) -> Float[Tensor, "*N 1"]:
        return -(field - threshold)

    def export(self, points: Float[Tensor, "*N Di"], **kwargs) -> Dict[str, Any]:
        out: Dict[str, Any] = {}
        if self.cfg.n_feature_dims == 0:
            return out
        points_unscaled = points
        points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)
        enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims))
        features = self.feature_network(enc).view(
            *points.shape[:-1], self.cfg.n_feature_dims
        )
        out.update(
            {
                "features": features,
            }
        )
        return out

    @staticmethod
    @torch.no_grad()
    def create_from(
        other: BaseGeometry,
        cfg: Optional[Union[dict, DictConfig]] = None,
        copy_net: bool = True,
        **kwargs,
    ) -> "ImplicitVolume":
        if isinstance(other, ImplicitVolume):
            instance = ImplicitVolume(cfg, **kwargs)
            instance.encoding.load_state_dict(other.encoding.state_dict())
            instance.density_network.load_state_dict(other.density_network.state_dict())
            if copy_net:
                if (
                    instance.cfg.n_feature_dims > 0
                    and other.cfg.n_feature_dims == instance.cfg.n_feature_dims
                ):
                    instance.feature_network.load_state_dict(
                        other.feature_network.state_dict()
                    )
                if (
                    instance.cfg.normal_type == "pred"
                    and other.cfg.normal_type == "pred"
                ):
                    instance.normal_network.load_state_dict(
                        other.normal_network.state_dict()
                    )
            return instance
        else:
            raise TypeError(
                f"Cannot create {ImplicitVolume.__name__} from {other.__class__.__name__}"
            )

    # FIXME: use progressive normal eps
    def update_step(
        self, epoch: int, global_step: int, on_load_weights: bool = False
    ) -> None:
        if self.cfg.anneal_density_blob_std_config is not None:
            min_step = self.cfg.anneal_density_blob_std_config.min_anneal_step
            max_step = self.cfg.anneal_density_blob_std_config.max_anneal_step
            if global_step >= min_step and global_step <= max_step:
                end_val = self.cfg.anneal_density_blob_std_config.end_val
                start_val = self.cfg.anneal_density_blob_std_config.start_val
                self.density_blob_std = start_val + (global_step - min_step) * (
                    end_val - start_val
                ) / (max_step - min_step)

        if (
            self.cfg.normal_type == "finite_difference"
            or self.cfg.normal_type == "finite_difference_laplacian"
        ):
            if isinstance(self.cfg.finite_difference_normal_eps, float):
                self.finite_difference_normal_eps = (
                    self.cfg.finite_difference_normal_eps
                )
            elif self.cfg.finite_difference_normal_eps == "progressive":
                # progressive finite difference eps from Neuralangelo
                # https://arxiv.org/abs/2306.03092
                hg_conf: Any = self.cfg.pos_encoding_config
                assert (
                    hg_conf.otype == "ProgressiveBandHashGrid"
                ), "finite_difference_normal_eps=progressive only works with ProgressiveBandHashGrid"
                current_level = min(
                    hg_conf.start_level
                    + max(global_step - hg_conf.start_step, 0) // hg_conf.update_steps,
                    hg_conf.n_levels,
                )
                grid_res = hg_conf.base_resolution * hg_conf.per_level_scale ** (
                    current_level - 1
                )
                grid_size = 2 * self.cfg.radius / grid_res
                if grid_size != self.finite_difference_normal_eps:
                    threestudio.info(
                        f"Update finite_difference_normal_eps to {grid_size}"
                    )
                self.finite_difference_normal_eps = grid_size
            else:
                raise ValueError(
                    f"Unknown finite_difference_normal_eps={self.cfg.finite_difference_normal_eps}"
                )

threestudio/models/isosurface.py
class MarchingTetrahedraHelper(IsosurfaceHelper):
    def __init__(self, resolution: int, tets_path: str):
        super().__init__()
        self.resolution = resolution
        self.tets_path = tets_path

        self.triangle_table: Float[Tensor, "..."]
        self.register_buffer(
            "triangle_table",
            torch.as_tensor(
                [
                    [-1, -1, -1, -1, -1, -1],
                    [1, 0, 2, -1, -1, -1],
                    [4, 0, 3, -1, -1, -1],
                    [1, 4, 2, 1, 3, 4],
                    [3, 1, 5, -1, -1, -1],
                    [2, 3, 0, 2, 5, 3],
                    [1, 4, 0, 1, 5, 4],
                    [4, 2, 5, -1, -1, -1],
                    [4, 5, 2, -1, -1, -1],
                    [4, 1, 0, 4, 5, 1],
                    [3, 2, 0, 3, 5, 2],
                    [1, 3, 5, -1, -1, -1],
                    [4, 1, 2, 4, 3, 1],
                    [3, 0, 4, -1, -1, -1],
                    [2, 0, 1, -1, -1, -1],
                    [-1, -1, -1, -1, -1, -1],
                ],
                dtype=torch.long,
            ),
            persistent=False,
        )
        self.num_triangles_table: Integer[Tensor, "..."]
        self.register_buffer(
            "num_triangles_table",
            torch.as_tensor(
                [0, 1, 1, 2, 1, 2, 2, 1, 1, 2, 2, 1, 2, 1, 1, 0], dtype=torch.long
            ),
            persistent=False,
        )
        self.base_tet_edges: Integer[Tensor, "..."]
        self.register_buffer(
            "base_tet_edges",
            torch.as_tensor([0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3], dtype=torch.long),
            persistent=False,
        )

        tets = np.load(self.tets_path)
        self._grid_vertices: Float[Tensor, "..."]
        self.register_buffer(
            "_grid_vertices",
            torch.from_numpy(tets["vertices"]).float(),
            persistent=False,
        )
        self.indices: Integer[Tensor, "..."]
        self.register_buffer(
            "indices", torch.from_numpy(tets["indices"]).long(), persistent=False
        )

        self._all_edges: Optional[Integer[Tensor, "Ne 2"]] = None

    def normalize_grid_deformation(
        self, grid_vertex_offsets: Float[Tensor, "Nv 3"]
    ) -> Float[Tensor, "Nv 3"]:
        return (
            (self.points_range[1] - self.points_range[0])
            / (self.resolution)  # half tet size is approximately 1 / self.resolution
            * torch.tanh(grid_vertex_offsets)
        )  # FIXME: hard-coded activation

    @property
    def grid_vertices(self) -> Float[Tensor, "Nv 3"]:
        return self._grid_vertices

    @property
    def all_edges(self) -> Integer[Tensor, "Ne 2"]:
        if self._all_edges is None:
            # compute edges on GPU, or it would be VERY SLOW (basically due to the unique operation)
            edges = torch.tensor(
                [0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3],
                dtype=torch.long,
                device=self.indices.device,
            )
            _all_edges = self.indices[:, edges].reshape(-1, 2)
            _all_edges_sorted = torch.sort(_all_edges, dim=1)[0]
            _all_edges = torch.unique(_all_edges_sorted, dim=0)
            self._all_edges = _all_edges
        return self._all_edges

    def sort_edges(self, edges_ex2):
        with torch.no_grad():
            order = (edges_ex2[:, 0] > edges_ex2[:, 1]).long()
            order = order.unsqueeze(dim=1)

            a = torch.gather(input=edges_ex2, index=order, dim=1)
            b = torch.gather(input=edges_ex2, index=1 - order, dim=1)

        return torch.stack([a, b], -1)

    def _forward(self, pos_nx3, sdf_n, tet_fx4):
        with torch.no_grad():
            occ_n = sdf_n > 0
            occ_fx4 = occ_n[tet_fx4.reshape(-1)].reshape(-1, 4)
            occ_sum = torch.sum(occ_fx4, -1)
            valid_tets = (occ_sum > 0) & (occ_sum < 4)
            occ_sum = occ_sum[valid_tets]

            # find all vertices
            all_edges = tet_fx4[valid_tets][:, self.base_tet_edges].reshape(-1, 2)
            all_edges = self.sort_edges(all_edges)
            unique_edges, idx_map = torch.unique(all_edges, dim=0, return_inverse=True)

            unique_edges = unique_edges.long()
            mask_edges = occ_n[unique_edges.reshape(-1)].reshape(-1, 2).sum(-1) == 1
            mapping = (
                torch.ones(
                    (unique_edges.shape[0]), dtype=torch.long, device=pos_nx3.device
                )
                * -1
            )
            mapping[mask_edges] = torch.arange(
                mask_edges.sum(), dtype=torch.long, device=pos_nx3.device
            )
            idx_map = mapping[idx_map]  # map edges to verts

            interp_v = unique_edges[mask_edges]
        edges_to_interp = pos_nx3[interp_v.reshape(-1)].reshape(-1, 2, 3)
        edges_to_interp_sdf = sdf_n[interp_v.reshape(-1)].reshape(-1, 2, 1)
        edges_to_interp_sdf[:, -1] *= -1

        denominator = edges_to_interp_sdf.sum(1, keepdim=True)

        edges_to_interp_sdf = torch.flip(edges_to_interp_sdf, [1]) / denominator
        verts = (edges_to_interp * edges_to_interp_sdf).sum(1)

        idx_map = idx_map.reshape(-1, 6)

        v_id = torch.pow(2, torch.arange(4, dtype=torch.long, device=pos_nx3.device))
        tetindex = (occ_fx4[valid_tets] * v_id.unsqueeze(0)).sum(-1)
        num_triangles = self.num_triangles_table[tetindex]

        # Generate triangle indices
        faces = torch.cat(
            (
                torch.gather(
                    input=idx_map[num_triangles == 1],
                    dim=1,
                    index=self.triangle_table[tetindex[num_triangles == 1]][:, :3],
                ).reshape(-1, 3),
                torch.gather(
                    input=idx_map[num_triangles == 2],
                    dim=1,
                    index=self.triangle_table[tetindex[num_triangles == 2]][:, :6],
                ).reshape(-1, 3),
            ),
            dim=0,
        )

        return verts, faces

    def forward(
        self,
        level: Float[Tensor, "N3 1"],
        deformation: Optional[Float[Tensor, "N3 3"]] = None,
    ) -> Mesh:
        if deformation is not None:
            grid_vertices = self.grid_vertices + self.normalize_grid_deformation(
                deformation
            )
        else:
            grid_vertices = self.grid_vertices

        v_pos, t_pos_idx = self._forward(grid_vertices, level, self.indices)

        mesh = Mesh(
            v_pos=v_pos,
            t_pos_idx=t_pos_idx,
            # extras
            grid_vertices=grid_vertices,
            tet_edges=self.all_edges,
            grid_level=level,
            grid_deformation=deformation,
        )

        return mesh

Answer: class Config(BaseExplicitGeometry.Config):

<think>
Inside the TetrahedraSDFGrid class we see the @dataclass decorator, which in other geometry classes is used to define an inner Config dataclass inheriting from the base geometry's Config. After the imports, the next logical line is the declaration of this inner Config class.
</think>
class Config(BaseExplicitGeometry.Config):