idk
This commit is contained in:
commit
428877fbf6
1072 files changed
+160209
No files matched your search
@@ -0,0 +1,10 @@
|
||||
dependencies {
|
||||
compileOnly(project(":api"))
|
||||
listOf("v1_19_R3", "v1_20_R1", "v1_20_R2", "v1_20_R3").forEach { compileOnly(project(":nms:$it")) }
|
||||
compileOnly("io.papermc.paper:paper-api:1.20.4-R0.1-SNAPSHOT")
|
||||
compileOnly("net.citizensnpcs:citizens-main:2.0.44-SNAPSHOT") { isTransitive = false }
|
||||
compileOnly("me.libraryaddict.disguises:libsdisguises:26.11.10") { isTransitive = false }
|
||||
compileOnly("com.viaversion:viaversion-api:5.12.2") { isTransitive = false }
|
||||
compileOnly("org.jsoup:jsoup:1.17.2")
|
||||
compileOnly(files("${rootDir}/libs/mineskin-java-client-3.2.1-SNAPSHOT.jar"))
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
package com.ticxo.modelengine.core;
|
||||
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.ServerInfo;
|
||||
import com.ticxo.modelengine.api.animation.AnimationHandlerRegistry;
|
||||
import com.ticxo.modelengine.api.animation.AnimationPropertyRegistry;
|
||||
import com.ticxo.modelengine.api.animation.ModelState;
|
||||
import com.ticxo.modelengine.api.animation.handler.AnimationHandler;
|
||||
import com.ticxo.modelengine.api.animation.keyframe.KeyframeTypeRegistry;
|
||||
import com.ticxo.modelengine.api.animation.keyframe.KeyframeTypes;
|
||||
import com.ticxo.modelengine.api.animation.keyframe.data.KeyframeReaderRegistry;
|
||||
import com.ticxo.modelengine.api.animation.property.SimpleProperty;
|
||||
import com.ticxo.modelengine.api.animation.script.ScriptReaderRegistry;
|
||||
import com.ticxo.modelengine.api.command.AbstractCommand;
|
||||
import com.ticxo.modelengine.api.entity.BaseEntity;
|
||||
import com.ticxo.modelengine.api.entity.EntityDataTrackers;
|
||||
import com.ticxo.modelengine.api.entity.Hitbox;
|
||||
import com.ticxo.modelengine.api.entity.data.AbstractEntityData;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.interaction.InteractionTracker;
|
||||
import com.ticxo.modelengine.api.lod.AnimationLODHandler;
|
||||
import com.ticxo.modelengine.api.menu.ScreenManager;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.ModelRegistry;
|
||||
import com.ticxo.modelengine.api.model.ModelUpdaters;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.api.model.PivotOverrideRegistry;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorRegistry;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.model.bone.render.DefaultRenderType;
|
||||
import com.ticxo.modelengine.api.model.bone.type.PlayerLimb;
|
||||
import com.ticxo.modelengine.api.model.limb.UserLimbRegistry;
|
||||
import com.ticxo.modelengine.api.model.render.ModelRenderer;
|
||||
import com.ticxo.modelengine.api.mount.MountControllerTypeRegistry;
|
||||
import com.ticxo.modelengine.api.mount.MountPairManager;
|
||||
import com.ticxo.modelengine.api.mount.controller.MountControllerTypes;
|
||||
import com.ticxo.modelengine.api.utils.CompatibilityManager;
|
||||
import com.ticxo.modelengine.api.utils.TFile;
|
||||
import com.ticxo.modelengine.api.utils.config.ConfigCache;
|
||||
import com.ticxo.modelengine.api.utils.config.ConfigManager;
|
||||
import com.ticxo.modelengine.api.utils.config.ConfigProperty;
|
||||
import com.ticxo.modelengine.api.utils.logger.TLogger;
|
||||
import com.ticxo.modelengine.api.utils.scheduling.BukkitPlatformScheduler;
|
||||
import com.ticxo.modelengine.api.utils.scheduling.FoliaPlatformScheduler;
|
||||
import com.ticxo.modelengine.api.utils.scheduling.PlatformScheduler;
|
||||
import com.ticxo.modelengine.api.utils.ticker.DualTicker;
|
||||
import com.ticxo.modelengine.api.vfx.VFX;
|
||||
import com.ticxo.modelengine.api.vfx.VFXUpdater;
|
||||
import com.ticxo.modelengine.api.vfx.render.VFXRenderer;
|
||||
import com.ticxo.modelengine.core.animation.handler.PriorityHandler;
|
||||
import com.ticxo.modelengine.core.animation.handler.StateMachineHandler;
|
||||
import com.ticxo.modelengine.core.animation.script.ModelEngineScriptReader;
|
||||
import com.ticxo.modelengine.core.citizens.CitizensCommand;
|
||||
import com.ticxo.modelengine.core.citizens.ModelTrait;
|
||||
import com.ticxo.modelengine.core.command.MECommand;
|
||||
import com.ticxo.modelengine.core.generator.ModelGeneratorImpl;
|
||||
import com.ticxo.modelengine.core.generator.skin.MineSkinGeneratorService;
|
||||
import com.ticxo.modelengine.core.generator.skin.SkinSplitterImpl;
|
||||
import com.ticxo.modelengine.core.javasupport.Java21Access;
|
||||
import com.ticxo.modelengine.core.javasupport.Java25Access;
|
||||
import com.ticxo.modelengine.core.libsdisguises.DisguiseCompatibility;
|
||||
import com.ticxo.modelengine.core.listener.ChatListener;
|
||||
import com.ticxo.modelengine.core.listener.EntityListener;
|
||||
import com.ticxo.modelengine.core.listener.InventoryListener;
|
||||
import com.ticxo.modelengine.core.listener.PlayerListener;
|
||||
import com.ticxo.modelengine.core.listener.WorldListener;
|
||||
import com.ticxo.modelengine.core.model.ActiveModelImpl;
|
||||
import com.ticxo.modelengine.core.model.ModeledEntityImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.behavior.GhostImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.behavior.HeadForcedImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.behavior.HeadImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.behavior.HeldItemImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.behavior.LeashImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.behavior.MountImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.behavior.NameTagImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.behavior.PlayerLimbImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.behavior.SegmentImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.behavior.SubHitboxImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.behavior.TailImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.behavior.UserLimbImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.manager.LeashManagerImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.manager.MountManagerImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.render.HeldItemRendererImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.render.LeashRendererImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.render.MountRendererImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.render.NameTagRendererImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.render.SegmentRendererImpl;
|
||||
import com.ticxo.modelengine.core.model.bone.render.SubHitboxRendererImpl;
|
||||
import com.ticxo.modelengine.core.vfx.VFXImpl;
|
||||
import com.ticxo.modelengine.v1_19_R3.NMSHandler_v1_19_R3;
|
||||
import com.ticxo.modelengine.v1_20_R1.NMSHandler_v1_20_R1;
|
||||
import com.ticxo.modelengine.v1_20_R2.NMSHandler_v1_20_R2;
|
||||
import com.ticxo.modelengine.v1_20_R3.NMSHandler_v1_20_R3;
|
||||
import com.viaversion.viaversion.api.Via;
|
||||
import java.io.File;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import net.citizensnpcs.api.CitizensAPI;
|
||||
import net.citizensnpcs.api.trait.TraitInfo;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.PluginCommand;
|
||||
import org.bukkit.entity.ItemDisplay.ItemDisplayTransform;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class ModelEngine extends ModelEngineAPI {
|
||||
public static ModelEngine CORE;
|
||||
private AbstractCommand commandRoot;
|
||||
private PluginManager pluginManager;
|
||||
private DisguiseCompatibility disguiseCompatibility;
|
||||
|
||||
public void onLoad() {
|
||||
ModelEngineAPI.API = this;
|
||||
CORE = this;
|
||||
TLogger.logger = this.getLogger();
|
||||
this.pluginManager = Bukkit.getPluginManager();
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
this.configureConfig();
|
||||
this.configureNMSHandler();
|
||||
this.gson = new GsonBuilder().create();
|
||||
this.scheduler = (PlatformScheduler)(ServerInfo.IS_FOLIA ? new FoliaPlatformScheduler() : new BukkitPlatformScheduler());
|
||||
this.modelRegistry = new ModelRegistry();
|
||||
this.modelGenerator = new ModelGeneratorImpl(this);
|
||||
this.configureKeyframeTypeRegistry();
|
||||
this.keyframeReaderRegistry = new KeyframeReaderRegistry();
|
||||
this.configureScriptReaderRegistry();
|
||||
this.configureBoneBehaviorRegistry();
|
||||
this.configureTicker();
|
||||
this.configureMountControllerTypeRegistry();
|
||||
this.configureAnimationHandlerRegistry();
|
||||
this.configureAnimationPropertyRegistry();
|
||||
this.configureCommands();
|
||||
this.configureCompatibility();
|
||||
this.configureSkinSplitter();
|
||||
this.configureSkinGenerator();
|
||||
this.configureUserLimbRegistry();
|
||||
this.pivotOverrideRegistry = new PivotOverrideRegistry();
|
||||
this.pluginManager.registerEvents(new PlayerListener(), this);
|
||||
this.pluginManager.registerEvents(new EntityListener(), this);
|
||||
this.pluginManager.registerEvents(new WorldListener(), this);
|
||||
this.pluginManager.registerEvents(new InventoryListener(), this);
|
||||
this.pluginManager.registerEvents(new ChatListener(), this);
|
||||
Bukkit.getMessenger().registerOutgoingPluginChannel(this, "modelengine:bulk_data");
|
||||
if (Bukkit.getPluginManager().getPlugin("MythicMobs") == null) {
|
||||
this.modelGenerator.importModels(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
if (this.ticker != null) {
|
||||
this.ticker.stop();
|
||||
}
|
||||
|
||||
if (this.modelUpdaters != null) {
|
||||
this.modelUpdaters.saveAllModels();
|
||||
}
|
||||
}
|
||||
|
||||
private void configureConfig() {
|
||||
this.configManager = new ConfigManager(this);
|
||||
this.configCache = new ConfigCache();
|
||||
|
||||
for (ConfigProperty value : ConfigProperty.values()) {
|
||||
this.configManager.register(value);
|
||||
}
|
||||
|
||||
for (ModelState value : ModelState.values()) {
|
||||
this.configManager.register(value);
|
||||
}
|
||||
|
||||
this.configManager.save();
|
||||
this.configManager.registerReferenceUpdate(AbstractEntityData::updateConfig);
|
||||
this.configManager.registerReferenceUpdate(AnimationLODHandler::updateConfig);
|
||||
this.configManager.registerReferenceUpdate(this.configCache::updateConfig);
|
||||
}
|
||||
|
||||
private void configureKeyframeTypeRegistry() {
|
||||
this.keyframeTypeRegistry = new KeyframeTypeRegistry();
|
||||
this.keyframeTypeRegistry.registerKeyframeType(KeyframeTypes.POSITION);
|
||||
this.keyframeTypeRegistry.registerKeyframeType(KeyframeTypes.ROTATION);
|
||||
this.keyframeTypeRegistry.registerKeyframeType(KeyframeTypes.SCALE);
|
||||
this.keyframeTypeRegistry.registerKeyframeType(KeyframeTypes.SCRIPT);
|
||||
}
|
||||
|
||||
private void configureScriptReaderRegistry() {
|
||||
this.scriptReaderRegistry = new ScriptReaderRegistry();
|
||||
this.scriptReaderRegistry.registerAndDefault("meg", new ModelEngineScriptReader());
|
||||
}
|
||||
|
||||
private void configureBoneBehaviorRegistry() {
|
||||
this.boneBehaviorRegistry = new BoneBehaviorRegistry();
|
||||
BoneBehaviorTypes.HEAD = BoneBehaviorType.Builder.of(HeadImpl::new, null, "head")
|
||||
.optional("local", Boolean.class)
|
||||
.optional("inherited", Boolean.class)
|
||||
.predicate(BoneBehaviorType::noProcedural)
|
||||
.forced(HeadForcedImpl::new)
|
||||
.build();
|
||||
BoneBehaviorTypes.GHOST = BoneBehaviorType.Builder.of(GhostImpl::new, null, "ghost").renderType(DefaultRenderType.NONE).build();
|
||||
BoneBehaviorTypes.MOUNT = BoneBehaviorType.Builder.of(MountImpl::new, MountManagerImpl::new, "mount")
|
||||
.required("driver", Boolean.class)
|
||||
.renderType(MountRendererImpl::new)
|
||||
.build();
|
||||
BoneBehaviorTypes.SUB_HITBOX = BoneBehaviorType.Builder.of(SubHitboxImpl::new, null, "sub_hitbox")
|
||||
.required("dimension", Hitbox.class)
|
||||
.optional("obb", Boolean.class)
|
||||
.optional("origin", Vector3f.class)
|
||||
.optional("rotation", Vector3f.class)
|
||||
.optional("cube_origin", Vector3f.class)
|
||||
.renderType(SubHitboxRendererImpl::new)
|
||||
.ignoreCubes()
|
||||
.build();
|
||||
BoneBehaviorTypes.NAMETAG = BoneBehaviorType.Builder.of(NameTagImpl::new, null, "nametag").renderType(NameTagRendererImpl::new).build();
|
||||
BoneBehaviorTypes.ITEM = BoneBehaviorType.Builder.of(HeldItemImpl::new, null, "item")
|
||||
.required("display", ItemDisplayTransform.class)
|
||||
.renderType(HeldItemRendererImpl::new)
|
||||
.build();
|
||||
BoneBehaviorTypes.SEGMENT = BoneBehaviorType.Builder.of(SegmentImpl::new, null, "segment")
|
||||
.required("back_pivot", Boolean.class)
|
||||
.optional("bounded", Boolean.class)
|
||||
.optional("min_x", Float.class)
|
||||
.optional("max_x", Float.class)
|
||||
.optional("min_y", Float.class)
|
||||
.optional("max_y", Float.class)
|
||||
.optional("min_z", Float.class)
|
||||
.optional("max_z", Float.class)
|
||||
.optional("extend_rate", Float.class)
|
||||
.optional("elasticity", Float.class)
|
||||
.renderType(SegmentRendererImpl::new)
|
||||
.pivot()
|
||||
.build();
|
||||
BoneBehaviorTypes.TAIL = BoneBehaviorType.Builder.of(TailImpl::new, null, "tail")
|
||||
.required("back_pivot", Boolean.class)
|
||||
.optional("bounded", Boolean.class)
|
||||
.optional("min_x", Float.class)
|
||||
.optional("max_x", Float.class)
|
||||
.optional("min_y", Float.class)
|
||||
.optional("max_y", Float.class)
|
||||
.optional("min_z", Float.class)
|
||||
.optional("max_z", Float.class)
|
||||
.optional("extend_rate", Float.class)
|
||||
.optional("elasticity", Float.class)
|
||||
.build();
|
||||
BoneBehaviorTypes.LEASH = BoneBehaviorType.Builder.of(LeashImpl::new, LeashManagerImpl::new, "leash")
|
||||
.optional("main", Boolean.class)
|
||||
.renderType(LeashRendererImpl::new)
|
||||
.build();
|
||||
BoneBehaviorTypes.PLAYER_LIMB = BoneBehaviorType.Builder.of(PlayerLimbImpl::new, null, "player_limb")
|
||||
.required("limb", PlayerLimb.Limb.class)
|
||||
.renderType(DefaultRenderType.NONE)
|
||||
.ignoreCubes()
|
||||
.build();
|
||||
BoneBehaviorTypes.USER_LIMB = BoneBehaviorType.Builder.of(UserLimbImpl::new, null, "user_limb")
|
||||
.required("type", String.class)
|
||||
.renderType(DefaultRenderType.NONE)
|
||||
.ignoreCubes()
|
||||
.build();
|
||||
this.boneBehaviorRegistry.register(BoneBehaviorTypes.HEAD);
|
||||
this.boneBehaviorRegistry.register(BoneBehaviorTypes.GHOST);
|
||||
this.boneBehaviorRegistry.register(BoneBehaviorTypes.MOUNT);
|
||||
this.boneBehaviorRegistry.register(BoneBehaviorTypes.SUB_HITBOX);
|
||||
this.boneBehaviorRegistry.register(BoneBehaviorTypes.NAMETAG);
|
||||
this.boneBehaviorRegistry.register(BoneBehaviorTypes.ITEM);
|
||||
this.boneBehaviorRegistry.register(BoneBehaviorTypes.SEGMENT);
|
||||
this.boneBehaviorRegistry.register(BoneBehaviorTypes.TAIL);
|
||||
this.boneBehaviorRegistry.register(BoneBehaviorTypes.LEASH);
|
||||
this.boneBehaviorRegistry.register(BoneBehaviorTypes.PLAYER_LIMB);
|
||||
this.boneBehaviorRegistry.register(BoneBehaviorTypes.USER_LIMB);
|
||||
}
|
||||
|
||||
private void configureAnimationHandlerRegistry() {
|
||||
this.animationHandlerRegistry = new AnimationHandlerRegistry();
|
||||
this.animationHandlerRegistry.register("priority", PriorityHandler::create);
|
||||
this.animationHandlerRegistry.register("state_machine", StateMachineHandler::create);
|
||||
}
|
||||
|
||||
private void configureAnimationPropertyRegistry() {
|
||||
this.animationPropertyRegistry = new AnimationPropertyRegistry();
|
||||
this.animationPropertyRegistry.register("simple", SimpleProperty::create);
|
||||
}
|
||||
|
||||
private void configureTicker() {
|
||||
this.ticker = new DualTicker(this, this.getScheduler());
|
||||
this.mountPairManager = new MountPairManager();
|
||||
this.dataTrackers = new EntityDataTrackers(this, this.getScheduler());
|
||||
this.modelUpdaters = new ModelUpdaters();
|
||||
this.vfxUpdater = new VFXUpdater();
|
||||
this.interactionTracker = new InteractionTracker();
|
||||
this.screenManager = new ScreenManager();
|
||||
DualTicker.queueRepeatingSyncTask(this.mountPairManager::updatePassengerPosition, 0, 0);
|
||||
DualTicker.queueRepeatingSyncTask(() -> ServerInfo.CURRENT_TICK++, 0, 0);
|
||||
DualTicker.queueRepeatingAsyncTask(this.vfxUpdater::updateAllVFXs, 0, 0);
|
||||
DualTicker.queueRepeatingAsyncTask(this.interactionTracker::raytraceHitboxes, 0, 0);
|
||||
DualTicker.queueRepeatingSyncTask(this.screenManager::updateAllScreens, 0, 0);
|
||||
this.ticker.start();
|
||||
}
|
||||
|
||||
private void configureMountControllerTypeRegistry() {
|
||||
this.mountControllerTypeRegistry = new MountControllerTypeRegistry();
|
||||
this.mountControllerTypeRegistry.registerAndDefault("walking", MountControllerTypes.WALKING);
|
||||
this.mountControllerTypeRegistry.register("force_walking", MountControllerTypes.WALKING_FORCE);
|
||||
this.mountControllerTypeRegistry.register("flying", MountControllerTypes.FLYING);
|
||||
this.mountControllerTypeRegistry.register("force_flying", MountControllerTypes.FLYING_FORCE);
|
||||
}
|
||||
|
||||
private void configureNMSHandler() {
|
||||
String var1 = ServerInfo.NMS_VERSION;
|
||||
switch (var1) {
|
||||
case "1.19.4":
|
||||
this.nmsHandler = new NMSHandler_v1_19_R3();
|
||||
break;
|
||||
case "1.20":
|
||||
case "1.20.1":
|
||||
this.nmsHandler = new NMSHandler_v1_20_R1();
|
||||
break;
|
||||
case "1.20.2":
|
||||
case "1.20.3":
|
||||
this.nmsHandler = new NMSHandler_v1_20_R2();
|
||||
break;
|
||||
case "1.20.4":
|
||||
this.nmsHandler = new NMSHandler_v1_20_R3();
|
||||
break;
|
||||
default:
|
||||
this.nmsHandler = Java21Access.createNMSHandler.call(ServerInfo.NMS_VERSION);
|
||||
if (this.nmsHandler != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.nmsHandler = Java25Access.createNMSHandler.call(ServerInfo.NMS_VERSION);
|
||||
}
|
||||
|
||||
if (this.nmsHandler == null) {
|
||||
throw new RuntimeException("Unsupported NMS Version: " + ServerInfo.NMS_VERSION);
|
||||
}
|
||||
}
|
||||
|
||||
private void configureCommands() {
|
||||
PluginCommand command = this.getCommand("meg");
|
||||
if (command != null) {
|
||||
command.setExecutor(this.commandRoot = new MECommand(this));
|
||||
}
|
||||
}
|
||||
|
||||
private void configureCompatibility() {
|
||||
this.compatibilityManager = new CompatibilityManager(this);
|
||||
this.compatibilityManager.registerSupport("Citizens", () -> this::configureCitizensSupport);
|
||||
this.compatibilityManager.registerSupport("LibsDisguises", () -> this::configureLibsDisguises);
|
||||
this.compatibilityManager.registerSupport("ViaVersion", () -> plugin -> {
|
||||
ServerInfo.HAS_VIAVERSION = true;
|
||||
return true;
|
||||
});
|
||||
Java21Access.registerCompatibility.call(this.compatibilityManager, this);
|
||||
}
|
||||
|
||||
private void configureSkinSplitter() {
|
||||
File internalSkinFolder = TFile.createDirectory(this.getDataFolder(), "internals", "skins");
|
||||
SkinSplitterImpl splitter = new SkinSplitterImpl(
|
||||
TFile.createFile(internalSkinFolder, "steve_mapped.bbmodel"), TFile.createFile(internalSkinFolder, "alex_mapped.bbmodel")
|
||||
);
|
||||
splitter.copyMapped(this);
|
||||
splitter.reloadMapping();
|
||||
this.skinSplitter = splitter;
|
||||
}
|
||||
|
||||
private void configureSkinGenerator() {
|
||||
this.skinGenerator = new MineSkinGeneratorService();
|
||||
this.configManager.registerReferenceUpdate(this.skinGenerator::onReload);
|
||||
}
|
||||
|
||||
private void configureUserLimbRegistry() {
|
||||
this.userLimbRegistry = new UserLimbRegistry(this);
|
||||
this.userLimbRegistry.generateDefaults();
|
||||
}
|
||||
|
||||
private boolean configureCitizensSupport(Plugin plugin) {
|
||||
ServerInfo.HAS_CITIZENS = true;
|
||||
CitizensAPI.getTraitFactory().registerTrait(TraitInfo.create(ModelTrait.class));
|
||||
this.commandRoot.addSubCommands(new CitizensCommand(this.commandRoot));
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean configureLibsDisguises(Plugin plugin) {
|
||||
this.pluginManager.registerEvents(this.disguiseCompatibility = new DisguiseCompatibility(), this);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModeledEntity createModeledEntityImpl(BaseEntity<?> base, Consumer<ModeledEntity> consumer) {
|
||||
return new ModeledEntityImpl(base, consumer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActiveModel createActiveModelImpl(
|
||||
ModelBlueprint blueprint, Function<ActiveModel, ModelRenderer> rendererSupplier, Function<ActiveModel, AnimationHandler> handlerSupplier
|
||||
) {
|
||||
return new ActiveModelImpl(blueprint, rendererSupplier, handlerSupplier);
|
||||
}
|
||||
|
||||
@Override
|
||||
public VFX createVFXImpl(BaseEntity<?> base, Function<VFX, VFXRenderer> rendererSupplier, Consumer<VFX> consumer) {
|
||||
return new VFXImpl(base, rendererSupplier, consumer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getDisguiseRelayOrDefault(UUID uuid) {
|
||||
return this.disguiseCompatibility == null ? uuid : this.disguiseCompatibility.getRelayOrDefault(uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AnimationHandler getPriorityHandler(ActiveModel activeModel) {
|
||||
return new PriorityHandler(activeModel);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AnimationHandler getStateMachineHandler(ActiveModel activeModel) {
|
||||
return new StateMachineHandler(activeModel);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int playerProtocolVersion(UUID uuid) {
|
||||
return ServerInfo.HAS_VIAVERSION ? Via.getAPI().getPlayerVersion(uuid) : getNetworkHandler().getProtocolVersion();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
package com.ticxo.modelengine.core.animation.handler;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.animation.AnimationPropertyRegistry;
|
||||
import com.ticxo.modelengine.api.animation.BlueprintAnimation;
|
||||
import com.ticxo.modelengine.api.animation.ModelState;
|
||||
import com.ticxo.modelengine.api.animation.Timeline;
|
||||
import com.ticxo.modelengine.api.animation.handler.AnimationHandler;
|
||||
import com.ticxo.modelengine.api.animation.handler.IPriorityHandler;
|
||||
import com.ticxo.modelengine.api.animation.keyframe.KeyframeType;
|
||||
import com.ticxo.modelengine.api.animation.keyframe.KeyframeTypeRegistry;
|
||||
import com.ticxo.modelengine.api.animation.keyframe.type.AbstractKeyframe;
|
||||
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
|
||||
import com.ticxo.modelengine.api.animation.property.SimpleProperty;
|
||||
import com.ticxo.modelengine.api.entity.BaseEntity;
|
||||
import com.ticxo.modelengine.api.events.AnimationEndEvent;
|
||||
import com.ticxo.modelengine.api.events.AnimationPlayEvent;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.utils.data.io.SavedData;
|
||||
import com.ticxo.modelengine.api.utils.state.StateMachine;
|
||||
import com.ticxo.modelengine.api.utils.state.StateNode;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.UnaryOperator;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class PriorityHandler implements IPriorityHandler {
|
||||
private final ActiveModel activeModel;
|
||||
private final ModelBlueprint blueprint;
|
||||
private final Map<String, IAnimationProperty> properties = Maps.newConcurrentMap();
|
||||
private final Map<String, IAnimationProperty> updatedProperties = Maps.newConcurrentMap();
|
||||
private final Map<ModelState, AnimationHandler.DefaultProperty> defaultProperties = Maps.newConcurrentMap();
|
||||
private final StateMachine<BaseEntity<?>> stateMachine = new StateMachine<>();
|
||||
private boolean firstSpawn = true;
|
||||
|
||||
public PriorityHandler(ActiveModel activeModel) {
|
||||
this.activeModel = activeModel;
|
||||
this.blueprint = activeModel.getBlueprint();
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.IDLE, 0.25, 0.25, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.WALK, 0.25, 0.25, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.STRAFE, 0.25, 0.25, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.JUMP_START, 0.0, 0.25, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.JUMP, 0.0, 0.0, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.JUMP_END, 0.0, 0.25, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.HOVER, 0.25, 0.25, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.FLY, 0.25, 0.25, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.SPAWN, 0.0, 0.25, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.DEATH, 0.0, 0.0, 1.0));
|
||||
this.configureAnimation();
|
||||
}
|
||||
|
||||
private void configureAnimation() {
|
||||
StateNode<BaseEntity<?>> spawn = this.stateMachine.createNode();
|
||||
StateNode<BaseEntity<?>> idle = this.stateMachine.createNode();
|
||||
StateNode<BaseEntity<?>> walk = this.stateMachine.createNode();
|
||||
StateNode<BaseEntity<?>> strafe = this.stateMachine.createNode();
|
||||
StateNode<BaseEntity<?>> jumpStart = this.stateMachine.createNode();
|
||||
StateNode<BaseEntity<?>> jumpLoop = this.stateMachine.createNode();
|
||||
StateNode<BaseEntity<?>> jumpEnd = this.stateMachine.createNode();
|
||||
StateNode<BaseEntity<?>> hover = this.stateMachine.createNode();
|
||||
StateNode<BaseEntity<?>> fly = this.stateMachine.createNode();
|
||||
StateNode<BaseEntity<?>> death = this.stateMachine.createNode();
|
||||
spawn.setExitAction(baseEntity -> this.playState(ModelState.SPAWN));
|
||||
spawn.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
spawn.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
spawn.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover);
|
||||
spawn.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart);
|
||||
spawn.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe);
|
||||
spawn.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk);
|
||||
spawn.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle);
|
||||
idle.setEntryAction(baseEntity -> this.playState(ModelState.IDLE));
|
||||
idle.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
idle.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
idle.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover);
|
||||
idle.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart);
|
||||
idle.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP), jumpLoop);
|
||||
idle.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe);
|
||||
idle.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk);
|
||||
idle.setExitAction(baseEntity -> this.stopState(ModelState.IDLE));
|
||||
walk.setEntryAction(baseEntity -> this.playState(ModelState.WALK));
|
||||
walk.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
walk.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
walk.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover);
|
||||
walk.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart);
|
||||
walk.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP), jumpLoop);
|
||||
walk.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe);
|
||||
walk.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle);
|
||||
walk.setExitAction(baseEntity -> this.stopState(ModelState.WALK));
|
||||
strafe.setEntryAction(baseEntity -> this.playState(ModelState.STRAFE));
|
||||
strafe.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
strafe.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
strafe.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover);
|
||||
strafe.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart);
|
||||
strafe.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP), jumpLoop);
|
||||
strafe.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk);
|
||||
strafe.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle);
|
||||
strafe.setExitAction(baseEntity -> this.stopState(ModelState.STRAFE));
|
||||
jumpStart.setEntryAction(baseEntity -> this.playState(ModelState.JUMP_START));
|
||||
jumpStart.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
jumpStart.setCommonPredicate(baseEntity -> this.hasFinishedPlaying(ModelState.JUMP_START));
|
||||
jumpStart.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
jumpStart.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover);
|
||||
jumpStart.addConnectedNode(baseEntity -> !baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_END), jumpEnd);
|
||||
jumpStart.addConnectedNode(baseEntity -> !baseEntity.isJumping() && this.isWalking(this.activeModel), walk);
|
||||
jumpStart.addConnectedNode(baseEntity -> !baseEntity.isJumping() && !this.isWalking(this.activeModel), idle);
|
||||
jumpStart.addConnectedNode(baseEntity -> this.hasFinishedPlaying(ModelState.JUMP_START) && this.hasAnimation(ModelState.JUMP), jumpLoop);
|
||||
jumpLoop.setEntryAction(baseEntity -> this.playState(ModelState.JUMP));
|
||||
jumpLoop.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
jumpLoop.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
jumpLoop.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover);
|
||||
jumpLoop.addConnectedNode(baseEntity -> !baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_END), jumpEnd);
|
||||
jumpLoop.addConnectedNode(baseEntity -> !baseEntity.isJumping() && this.isWalking(this.activeModel), walk);
|
||||
jumpLoop.addConnectedNode(baseEntity -> !baseEntity.isJumping() && !this.isWalking(this.activeModel), idle);
|
||||
jumpLoop.setExitAction(baseEntity -> this.stopState(ModelState.JUMP));
|
||||
jumpEnd.setEntryAction(baseEntity -> this.playState(ModelState.JUMP_END));
|
||||
jumpEnd.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
jumpEnd.setCommonPredicate(baseEntity -> this.hasFinishedPlaying(ModelState.JUMP_END));
|
||||
jumpEnd.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
jumpEnd.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover);
|
||||
jumpEnd.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart);
|
||||
jumpEnd.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe);
|
||||
jumpEnd.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk);
|
||||
jumpEnd.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle);
|
||||
hover.setEntryAction(baseEntity -> this.playState(ModelState.HOVER));
|
||||
hover.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
hover.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
hover.addConnectedNode(baseEntity -> !baseEntity.isFlying() && baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe);
|
||||
hover.addConnectedNode(baseEntity -> !baseEntity.isFlying() && this.isWalking(this.activeModel), walk);
|
||||
hover.addConnectedNode(baseEntity -> !baseEntity.isFlying() && !this.isWalking(this.activeModel), idle);
|
||||
hover.setExitAction(baseEntity -> this.stopState(ModelState.HOVER));
|
||||
fly.setEntryAction(baseEntity -> this.playState(ModelState.FLY));
|
||||
fly.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
fly.addConnectedNode(baseEntity -> baseEntity.isFlying() && !this.isWalking(this.activeModel) && this.hasAnimation(ModelState.HOVER), hover);
|
||||
fly.addConnectedNode(baseEntity -> !baseEntity.isFlying() && baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe);
|
||||
fly.addConnectedNode(baseEntity -> !baseEntity.isFlying() && this.isWalking(this.activeModel), walk);
|
||||
fly.addConnectedNode(baseEntity -> !baseEntity.isFlying() && !this.isWalking(this.activeModel), idle);
|
||||
fly.setExitAction(baseEntity -> this.stopState(ModelState.FLY));
|
||||
death.setEntryAction(baseEntity -> {
|
||||
this.forceStopAllAnimations();
|
||||
this.playState(ModelState.DEATH);
|
||||
});
|
||||
this.stateMachine.setEntryNode(spawn);
|
||||
}
|
||||
|
||||
private boolean hasAnimation(ModelState state) {
|
||||
return this.blueprint.getAnimations().containsKey(state.getString());
|
||||
}
|
||||
|
||||
private boolean hasFinishedPlaying(ModelState state) {
|
||||
IAnimationProperty animation = this.getAnimation(state.getString());
|
||||
return animation == null || animation.getPhase() == IAnimationProperty.Phase.LERPOUT;
|
||||
}
|
||||
|
||||
private void stopState(ModelState state) {
|
||||
AnimationHandler.DefaultProperty defProperty = this.getDefaultProperty(state);
|
||||
this.stopAnimation(defProperty.getAnimation());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void prepare() {
|
||||
this.stateMachine.execute(this.activeModel.getModeledEntity().getBase());
|
||||
this.firstSpawn = false;
|
||||
this.updatedProperties.clear();
|
||||
this.updatedProperties.putAll(this.properties);
|
||||
|
||||
for (String name : List.copyOf(this.properties.keySet())) {
|
||||
IAnimationProperty property = this.updatedProperties.get(name);
|
||||
if (property != null && !property.update()) {
|
||||
this.updatedProperties.remove(name);
|
||||
this.forceStopAnimation(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateBone(ModelBone bone) {
|
||||
this.updateBone(bone, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateBone(ModelBone bone, @Nullable UnaryOperator<IAnimationProperty> propertyMapper) {
|
||||
bone.setHasGlobalRotation(false);
|
||||
KeyframeTypeRegistry registry = ModelEngineAPI.getAPI().getKeyframeTypeRegistry();
|
||||
ArrayDeque<IAnimationProperty> stack = new ArrayDeque<>();
|
||||
|
||||
for (String typeName : registry.getKeys()) {
|
||||
KeyframeType<? extends AbstractKeyframe<?>, ?> type = (KeyframeType<? extends AbstractKeyframe<?>, ?>)registry.get(typeName);
|
||||
if (!type.isGlobal()) {
|
||||
this.fillUpdateStack(stack, type, bone);
|
||||
|
||||
while (!stack.isEmpty()) {
|
||||
IAnimationProperty property = stack.pop();
|
||||
Timeline timeline = property.getBlueprintAnimation().getTimelines().get(property.getBlueprintBone(bone).getUuid());
|
||||
if (timeline != null && timeline.isGlobalRotation()) {
|
||||
bone.setHasGlobalRotation(true);
|
||||
}
|
||||
|
||||
type.updateBone(IPriorityHandler.class, this, bone, propertyMapper == null ? property : propertyMapper.apply(property));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasFinishedAllAnimations() {
|
||||
for (IAnimationProperty property : this.properties.values()) {
|
||||
if (!property.isFinished()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDefaultProperty(AnimationHandler.DefaultProperty defaultProperty) {
|
||||
this.defaultProperties.put(defaultProperty.getState(), defaultProperty);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AnimationHandler.DefaultProperty getDefaultProperty(ModelState state) {
|
||||
return this.defaultProperties.get(state);
|
||||
}
|
||||
|
||||
private void fillUpdateStack(ArrayDeque<IAnimationProperty> stack, KeyframeType<?, ?> type, ModelBone bone) {
|
||||
UUID boneUuid = bone.getBlueprintBone().getUuid();
|
||||
|
||||
for (IAnimationProperty property : this.updatedProperties.values()) {
|
||||
if (property.getBlueprintAnimation().getModelBlueprint() != this.blueprint) {
|
||||
stack.push(property);
|
||||
if (property.isOverride()
|
||||
&& property.containsKeyframe(type, property.getBlueprintBone(bone).getUuid())
|
||||
&& property.getPhase() == IAnimationProperty.Phase.PLAY) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (String name : this.blueprint.getAnimationDescendingPriority()) {
|
||||
IAnimationProperty propertyx = this.updatedProperties.get(name);
|
||||
if (propertyx != null) {
|
||||
stack.push(propertyx);
|
||||
if (propertyx.isOverride() && propertyx.containsKeyframe(type, boneUuid) && propertyx.getPhase() == IAnimationProperty.Phase.PLAY) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tickGlobal() {
|
||||
KeyframeTypeRegistry registry = ModelEngineAPI.getAPI().getKeyframeTypeRegistry();
|
||||
|
||||
for (IAnimationProperty property : this.properties.values()) {
|
||||
for (String typeName : registry.getKeys()) {
|
||||
KeyframeType<? extends AbstractKeyframe<?>, ?> type = (KeyframeType<? extends AbstractKeyframe<?>, ?>)registry.get(typeName);
|
||||
if (type.isGlobal()) {
|
||||
type.updateModel(IPriorityHandler.class, this, property);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forEachProperty(BiConsumer<String, IAnimationProperty> consumer) {
|
||||
this.properties.forEach(consumer);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public IAnimationProperty getAnimation(String animation) {
|
||||
return this.properties.get(animation);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, IAnimationProperty> getAnimations() {
|
||||
return ImmutableMap.copyOf(this.properties);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public IAnimationProperty playAnimation(String animation, double lerpIn, double lerpOut, double speed, boolean force) {
|
||||
BlueprintAnimation blueprintAnimation = this.blueprint.getAnimations().get(animation);
|
||||
if (blueprintAnimation == null) {
|
||||
return null;
|
||||
} else {
|
||||
SimpleProperty property = new SimpleProperty(this.activeModel, blueprintAnimation, lerpIn, lerpOut, speed);
|
||||
return this.playAnimation(property, force) ? property : null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean playAnimation(IAnimationProperty property, boolean force) {
|
||||
AnimationPlayEvent event = new AnimationPlayEvent(this.activeModel, property);
|
||||
ModelEngineAPI.callEvent(event);
|
||||
if (event.isCancelled()) {
|
||||
return false;
|
||||
} else {
|
||||
String name = property.getName();
|
||||
if (!this.properties.containsKey(name)) {
|
||||
this.properties.put(name, property);
|
||||
return true;
|
||||
} else {
|
||||
IAnimationProperty old = this.properties.get(name);
|
||||
if (!force && !old.canReplace()) {
|
||||
return false;
|
||||
} else {
|
||||
this.properties.put(name, property);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void playState(ModelState state) {
|
||||
AnimationHandler.DefaultProperty defProperty = this.getDefaultProperty(state);
|
||||
IAnimationProperty property = this.firstSpawn
|
||||
? defProperty.build(this.activeModel, 0.0, defProperty.getLerpOut(), defProperty.getSpeed())
|
||||
: defProperty.build(this.activeModel);
|
||||
if (property != null) {
|
||||
property.setForceLoopMode(state.getLoopMode());
|
||||
property.setForceOverride(state.getOverride());
|
||||
this.playAnimation(property, false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPlayingAnimation(String animation) {
|
||||
return this.properties.containsKey(animation);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopAnimation(String animation) {
|
||||
IAnimationProperty property = this.properties.get(animation);
|
||||
if (property != null) {
|
||||
if (property.getLerpOut() > 1.0E-5F) {
|
||||
property.stop();
|
||||
} else {
|
||||
this.forceStopAnimation(animation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forceStopAnimation(String animation) {
|
||||
IAnimationProperty property = this.properties.remove(animation);
|
||||
if (property != null) {
|
||||
AnimationEndEvent event = new AnimationEndEvent(this.activeModel, property);
|
||||
ModelEngineAPI.callEvent(event);
|
||||
if (property instanceof SimpleProperty simpleProperty && simpleProperty.getOnEndTask() != null) {
|
||||
simpleProperty.getOnEndTask().run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forceStopAllAnimations() {
|
||||
for (IAnimationProperty property : this.properties.values()) {
|
||||
AnimationEndEvent event = new AnimationEndEvent(this.activeModel, property);
|
||||
ModelEngineAPI.callEvent(event);
|
||||
if (property instanceof SimpleProperty simpleProperty && simpleProperty.getOnEndTask() != null) {
|
||||
simpleProperty.getOnEndTask().run();
|
||||
}
|
||||
}
|
||||
|
||||
this.properties.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(SavedData data) {
|
||||
IPriorityHandler.super.save(data);
|
||||
SavedData animationData = new SavedData();
|
||||
this.getAnimations().forEach((key, property) -> property.save().ifPresent(propertyData -> animationData.putData(key, propertyData)));
|
||||
data.putData("animations", animationData);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(SavedData data) {
|
||||
IPriorityHandler.super.load(data);
|
||||
AnimationPropertyRegistry registry = ModelEngineAPI.getAnimationPropertyRegistry();
|
||||
data.getData("animations").ifPresent(animationData -> {
|
||||
for (String key : animationData.keySet()) {
|
||||
animationData.getData(key).ifPresent(propertyData -> {
|
||||
IAnimationProperty property = registry.createAnimationProperty(this, propertyData);
|
||||
this.playAnimation(property, true);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static PriorityHandler create(ActiveModel model, SavedData data) {
|
||||
PriorityHandler handler = new PriorityHandler(model);
|
||||
handler.load(data);
|
||||
return handler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActiveModel getActiveModel() {
|
||||
return this.activeModel;
|
||||
}
|
||||
}
|
||||
+720
@@ -0,0 +1,720 @@
|
||||
package com.ticxo.modelengine.core.animation.handler;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.animation.AnimationPropertyRegistry;
|
||||
import com.ticxo.modelengine.api.animation.BlueprintAnimation;
|
||||
import com.ticxo.modelengine.api.animation.ModelState;
|
||||
import com.ticxo.modelengine.api.animation.Timeline;
|
||||
import com.ticxo.modelengine.api.animation.handler.AnimationHandler;
|
||||
import com.ticxo.modelengine.api.animation.handler.IStateMachineHandler;
|
||||
import com.ticxo.modelengine.api.animation.keyframe.KeyframeType;
|
||||
import com.ticxo.modelengine.api.animation.keyframe.KeyframeTypeRegistry;
|
||||
import com.ticxo.modelengine.api.animation.keyframe.type.AbstractKeyframe;
|
||||
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
|
||||
import com.ticxo.modelengine.api.animation.property.SimpleProperty;
|
||||
import com.ticxo.modelengine.api.entity.BaseEntity;
|
||||
import com.ticxo.modelengine.api.events.AnimationEndEvent;
|
||||
import com.ticxo.modelengine.api.events.AnimationPlayEvent;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.utils.config.ConfigProperty;
|
||||
import com.ticxo.modelengine.api.utils.data.io.DataIO;
|
||||
import com.ticxo.modelengine.api.utils.data.io.SavedData;
|
||||
import com.ticxo.modelengine.api.utils.logger.TLogger;
|
||||
import com.ticxo.modelengine.api.utils.state.StateMachine;
|
||||
import com.ticxo.modelengine.api.utils.state.StateNode;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
import java.util.TreeMap;
|
||||
import java.util.UUID;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.function.UnaryOperator;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class StateMachineHandler implements IStateMachineHandler {
|
||||
private static int DEFAULT_PRIORITY;
|
||||
private final ActiveModel activeModel;
|
||||
private final ModelBlueprint blueprint;
|
||||
private final Map<ModelState, AnimationHandler.DefaultProperty> defaultProperties = Maps.newConcurrentMap();
|
||||
private final TreeMap<Integer, StateMachineHandler.AnimationStateMachine> stateMachines = new TreeMap<>();
|
||||
private final Queue<Runnable> actionQueue = new ConcurrentLinkedQueue<>();
|
||||
private boolean firstSpawn = true;
|
||||
|
||||
public StateMachineHandler(ActiveModel activeModel) {
|
||||
this.activeModel = activeModel;
|
||||
this.blueprint = activeModel.getBlueprint();
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.IDLE, 0.25, 0.0, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.WALK, 0.25, 0.0, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.STRAFE, 0.25, 0.0, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.JUMP_START, 0.0, 0.0, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.JUMP, 0.0, 0.0, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.JUMP_END, 0.0, 0.0, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.HOVER, 0.25, 0.0, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.FLY, 0.25, 0.0, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.SPAWN, 0.0, 0.0, 1.0));
|
||||
this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.DEATH, 0.0, 0.0, 1.0));
|
||||
this.configureAnimation();
|
||||
}
|
||||
|
||||
private void configureAnimation() {
|
||||
StateMachineHandler.AnimationStateMachine stateMachine = new StateMachineHandler.AnimationStateMachine(false);
|
||||
StateNode<BaseEntity<?>> root = stateMachine.getRootNode();
|
||||
StateNode<BaseEntity<?>> spawn = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.SPAWN));
|
||||
StateNode<BaseEntity<?>> idle = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.IDLE));
|
||||
StateNode<BaseEntity<?>> walk = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.WALK));
|
||||
StateNode<BaseEntity<?>> strafe = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.STRAFE));
|
||||
StateNode<BaseEntity<?>> jumpStart = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.JUMP_START));
|
||||
StateNode<BaseEntity<?>> jumpLoop = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.JUMP));
|
||||
StateNode<BaseEntity<?>> jumpEnd = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.JUMP_END));
|
||||
StateNode<BaseEntity<?>> hover = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.HOVER));
|
||||
StateNode<BaseEntity<?>> fly = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.FLY));
|
||||
StateNode<BaseEntity<?>> death = stateMachine.createAnimationNode(() -> {
|
||||
this.forceStopAllAnimations();
|
||||
return this.createStateProperty(ModelState.DEATH);
|
||||
});
|
||||
root.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
root.addConnectedNode(baseEntity -> this.hasAnimation(ModelState.SPAWN), spawn);
|
||||
root.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
root.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover);
|
||||
root.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart);
|
||||
root.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP), jumpLoop);
|
||||
root.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe);
|
||||
root.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk);
|
||||
root.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle);
|
||||
spawn.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
spawn.setCommonPredicate(baseEntity -> stateMachine.hasFinishedPlaying(ModelState.SPAWN));
|
||||
spawn.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
spawn.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover);
|
||||
spawn.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart);
|
||||
spawn.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP), jumpLoop);
|
||||
spawn.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe);
|
||||
spawn.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk);
|
||||
spawn.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle);
|
||||
idle.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
idle.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
idle.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover);
|
||||
idle.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart);
|
||||
idle.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP), jumpLoop);
|
||||
idle.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe);
|
||||
idle.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk);
|
||||
walk.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
walk.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
walk.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover);
|
||||
walk.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart);
|
||||
walk.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP), jumpLoop);
|
||||
walk.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe);
|
||||
walk.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle);
|
||||
strafe.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
strafe.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
strafe.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover);
|
||||
strafe.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart);
|
||||
strafe.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP), jumpLoop);
|
||||
strafe.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk);
|
||||
strafe.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle);
|
||||
jumpStart.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
jumpStart.setCommonPredicate(baseEntity -> stateMachine.hasFinishedPlaying(ModelState.JUMP_START));
|
||||
jumpStart.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
jumpStart.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover);
|
||||
jumpStart.addConnectedNode(baseEntity -> !baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_END), jumpEnd);
|
||||
jumpStart.addConnectedNode(baseEntity -> !baseEntity.isJumping() && this.isWalking(this.activeModel), walk);
|
||||
jumpStart.addConnectedNode(baseEntity -> !baseEntity.isJumping() && !this.isWalking(this.activeModel), idle);
|
||||
jumpLoop.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
jumpLoop.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
jumpLoop.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover);
|
||||
jumpLoop.addConnectedNode(baseEntity -> !baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_END), jumpEnd);
|
||||
jumpLoop.addConnectedNode(baseEntity -> !baseEntity.isJumping() && this.isWalking(this.activeModel), walk);
|
||||
jumpLoop.addConnectedNode(baseEntity -> !baseEntity.isJumping() && !this.isWalking(this.activeModel), idle);
|
||||
jumpEnd.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
jumpEnd.setCommonPredicate(baseEntity -> stateMachine.hasFinishedPlaying(ModelState.JUMP_END));
|
||||
jumpEnd.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
jumpEnd.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover);
|
||||
jumpEnd.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart);
|
||||
jumpEnd.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe);
|
||||
jumpEnd.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk);
|
||||
jumpEnd.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle);
|
||||
hover.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
hover.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly);
|
||||
hover.addConnectedNode(baseEntity -> !baseEntity.isFlying() && baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe);
|
||||
hover.addConnectedNode(baseEntity -> !baseEntity.isFlying() && this.isWalking(this.activeModel), walk);
|
||||
hover.addConnectedNode(baseEntity -> !baseEntity.isFlying() && !this.isWalking(this.activeModel), idle);
|
||||
fly.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death);
|
||||
fly.addConnectedNode(baseEntity -> baseEntity.isFlying() && !this.isWalking(this.activeModel) && this.hasAnimation(ModelState.HOVER), hover);
|
||||
fly.addConnectedNode(baseEntity -> !baseEntity.isFlying() && baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe);
|
||||
fly.addConnectedNode(baseEntity -> !baseEntity.isFlying() && this.isWalking(this.activeModel), walk);
|
||||
fly.addConnectedNode(baseEntity -> !baseEntity.isFlying() && !this.isWalking(this.activeModel), idle);
|
||||
this.stateMachines.put(DEFAULT_PRIORITY, stateMachine);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void prepare() {
|
||||
while (!this.actionQueue.isEmpty()) {
|
||||
this.actionQueue.poll().run();
|
||||
}
|
||||
|
||||
synchronized (this.stateMachines) {
|
||||
this.stateMachines.values().forEach(machine -> {
|
||||
machine.materializeQueued();
|
||||
machine.execute(this.activeModel.getModeledEntity().getBase());
|
||||
machine.queuedAnimation = null;
|
||||
});
|
||||
}
|
||||
|
||||
this.firstSpawn = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateBone(ModelBone bone) {
|
||||
this.updateBone(bone, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateBone(ModelBone bone, @Nullable UnaryOperator<IAnimationProperty> propertyMapper) {
|
||||
bone.setHasGlobalRotation(false);
|
||||
KeyframeTypeRegistry registry = ModelEngineAPI.getAPI().getKeyframeTypeRegistry();
|
||||
ArrayDeque<StateMachineHandler.AnimationStateMachine> stack = new ArrayDeque<>();
|
||||
|
||||
for (String typeName : registry.getKeys()) {
|
||||
KeyframeType<? extends AbstractKeyframe<?>, ?> type = (KeyframeType<? extends AbstractKeyframe<?>, ?>)registry.get(typeName);
|
||||
if (!type.isGlobal()) {
|
||||
this.fillUpdateStack(stack, type, bone);
|
||||
|
||||
while (!stack.isEmpty()) {
|
||||
StateMachineHandler.AnimationStateMachine stateMachine = stack.pop();
|
||||
IAnimationProperty currentProperty = stateMachine.currentAnimation;
|
||||
IAnimationProperty lastProperty = stateMachine.lastAnimation;
|
||||
bone.setHasGlobalRotation(this.isGlobalRotation(currentProperty, bone) || this.isGlobalRotation(lastProperty, bone));
|
||||
if (propertyMapper != null) {
|
||||
currentProperty = propertyMapper.apply(currentProperty);
|
||||
lastProperty = propertyMapper.apply(lastProperty);
|
||||
}
|
||||
|
||||
type.updateBone(IStateMachineHandler.class, this, bone, currentProperty, lastProperty);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isGlobalRotation(IAnimationProperty property, ModelBone bone) {
|
||||
if (property == null) {
|
||||
return false;
|
||||
} else {
|
||||
BlueprintAnimation animation = property.getBlueprintAnimation();
|
||||
if (animation == null) {
|
||||
return false;
|
||||
} else {
|
||||
Map<UUID, Timeline> timelines = animation.getTimelines();
|
||||
if (timelines == null) {
|
||||
return false;
|
||||
} else {
|
||||
Timeline timeline = timelines.get(bone.getBlueprintBone().getUuid());
|
||||
return timeline == null ? false : timeline.isGlobalRotation();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasFinishedAllAnimations() {
|
||||
synchronized (this.stateMachines) {
|
||||
for (StateMachineHandler.AnimationStateMachine machine : this.stateMachines.values()) {
|
||||
if (machine.currentAnimation != null && !machine.currentAnimation.isFinished() && !machine.currentAnimation.isIgnoreDeath()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDefaultProperty(AnimationHandler.DefaultProperty defaultProperty) {
|
||||
this.defaultProperties.put(defaultProperty.getState(), defaultProperty);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AnimationHandler.DefaultProperty getDefaultProperty(ModelState state) {
|
||||
return this.defaultProperties.get(state);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tickGlobal() {
|
||||
synchronized (this.stateMachines) {
|
||||
for (StateMachineHandler.AnimationStateMachine machine : this.stateMachines.values()) {
|
||||
if (machine.currentAnimation != null) {
|
||||
KeyframeTypeRegistry registry = ModelEngineAPI.getAPI().getKeyframeTypeRegistry();
|
||||
|
||||
for (String typeName : registry.getKeys()) {
|
||||
KeyframeType<? extends AbstractKeyframe<?>, ?> type = (KeyframeType<? extends AbstractKeyframe<?>, ?>)registry.get(typeName);
|
||||
if (type.isGlobal()) {
|
||||
type.updateModel(IStateMachineHandler.class, this, machine.currentAnimation, machine.lastAnimation);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public IAnimationProperty playAnimation(String animation, double lerpIn, double lerpOut, double speed, boolean force) {
|
||||
return this.playAnimation(1, animation, lerpIn, lerpOut, speed, force);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean playAnimation(IAnimationProperty property, boolean force) {
|
||||
return this.playAnimation(1, property, force);
|
||||
}
|
||||
|
||||
private void fillUpdateStack(ArrayDeque<StateMachineHandler.AnimationStateMachine> stack, KeyframeType<?, ?> type, ModelBone bone) {
|
||||
if (!this.stateMachines.isEmpty()) {
|
||||
UUID boneUuid = bone.getBlueprintBone().getUuid();
|
||||
|
||||
for (Entry<Integer, StateMachineHandler.AnimationStateMachine> entry = this.stateMachines.lastEntry();
|
||||
entry != null;
|
||||
entry = this.stateMachines.lowerEntry(entry.getKey())
|
||||
) {
|
||||
StateMachineHandler.AnimationStateMachine machine = entry.getValue();
|
||||
IAnimationProperty currentProperty = machine.currentAnimation;
|
||||
IAnimationProperty lastProperty = machine.lastAnimation;
|
||||
if (currentProperty != null) {
|
||||
stack.push(machine);
|
||||
if (this.isLastProperty(currentProperty, type, boneUuid) && (lastProperty == null || this.isLastProperty(lastProperty, type, boneUuid))) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isLastProperty(IAnimationProperty property, KeyframeType<?, ?> type, UUID boneUuid) {
|
||||
return property.isOverride() && property.containsKeyframe(type, boneUuid) && property.getPhase() == IAnimationProperty.Phase.PLAY;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public IAnimationProperty getAnimation(String animation) {
|
||||
synchronized (this.stateMachines) {
|
||||
for (StateMachineHandler.AnimationStateMachine machine : this.stateMachines.values()) {
|
||||
if (machine.isQueued(this.blueprint, animation)) {
|
||||
return machine.queuedAnimation;
|
||||
}
|
||||
|
||||
if (machine.isPlaying(animation)) {
|
||||
return machine.currentAnimation;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, IAnimationProperty> getAnimations() {
|
||||
HashMap<String, IAnimationProperty> map = new HashMap<>();
|
||||
|
||||
for (Entry<Integer, StateMachineHandler.AnimationStateMachine> entry : this.stateMachines.entrySet()) {
|
||||
int id = entry.getKey();
|
||||
StateMachineHandler.AnimationStateMachine stateMachine = entry.getValue();
|
||||
IAnimationProperty animation = stateMachine.getEffectiveAnimation();
|
||||
if (animation != null) {
|
||||
map.put(id + ":" + animation.getName(), animation);
|
||||
}
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public IAnimationProperty getAnimation(int priority, ModelBlueprint source, String animation) {
|
||||
StateMachineHandler.AnimationStateMachine machine = this.stateMachines.get(priority);
|
||||
if (machine == null) {
|
||||
return null;
|
||||
} else if (machine.isQueued(source, animation)) {
|
||||
return machine.queuedAnimation;
|
||||
} else {
|
||||
return machine.isPlaying(source, animation) ? machine.currentAnimation : null;
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public IAnimationProperty playAnimation(int priority, ModelBlueprint source, String animation, double lerpIn, double lerpOut, double speed, boolean force) {
|
||||
BlueprintAnimation blueprintAnimation = source.getAnimations().get(animation);
|
||||
if (blueprintAnimation == null) {
|
||||
return null;
|
||||
} else {
|
||||
SimpleProperty property = new SimpleProperty(this.activeModel, blueprintAnimation, lerpIn, lerpOut, speed);
|
||||
return this.playAnimation(priority, property, force) ? property : null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean playAnimation(int priority, IAnimationProperty property, boolean force) {
|
||||
AnimationPlayEvent event = new AnimationPlayEvent(this.activeModel, property);
|
||||
ModelEngineAPI.callEvent(event);
|
||||
if (event.isCancelled()) {
|
||||
return false;
|
||||
} else {
|
||||
synchronized (this.stateMachines) {
|
||||
StateMachineHandler.AnimationStateMachine machine = this.stateMachines
|
||||
.computeIfAbsent(priority, id -> new StateMachineHandler.AnimationStateMachine(true));
|
||||
if (force || machine.queuedAnimation == null && !machine.isPlaying(property.getName())) {
|
||||
machine.queuedAnimation = property;
|
||||
machine.queuedForce = force;
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refreshState(AnimationHandler.DefaultProperty property) {
|
||||
StateMachineHandler.AnimationStateMachine machine = this.stateMachines.get(DEFAULT_PRIORITY);
|
||||
if (machine != null && machine.isPlaying(property.getAnimation())) {
|
||||
machine.forceReentry(this.activeModel.getModeledEntity().getBase());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPlayingAnimation(String animation) {
|
||||
return this.getAnimation(animation) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPlayingAnimation(int priority, ModelBlueprint source, String animation) {
|
||||
return this.getAnimation(priority, source, animation) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopAnimation(String animation) {
|
||||
this.stateMachines.keySet().forEach(integer -> this.stopAnimation(integer, animation));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopAnimation(int priority, ModelBlueprint source, String animation) {
|
||||
StateMachineHandler.AnimationStateMachine machine = this.stateMachines.get(priority);
|
||||
if (machine != null) {
|
||||
if (machine.isQueued(source, animation)) {
|
||||
machine.queuedAnimation = null;
|
||||
} else {
|
||||
if (machine.isPlaying(source, animation)) {
|
||||
if (machine.currentAnimation.getLerpOut() > 1.0E-5F) {
|
||||
machine.currentAnimation.stop();
|
||||
} else {
|
||||
machine.getCurrentNode().addForceConnectedNode(baseEntity -> true, machine.getRootNode());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forceStopAnimation(String animation) {
|
||||
this.stateMachines.keySet().forEach(integer -> this.forceStopAnimation(integer, animation));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forceStopAnimation(int priority, ModelBlueprint source, String animation) {
|
||||
StateMachineHandler.AnimationStateMachine machine = this.stateMachines.get(priority);
|
||||
if (machine != null) {
|
||||
if (machine.isQueued(source, animation)) {
|
||||
machine.queuedAnimation = null;
|
||||
} else {
|
||||
if (machine.isPlaying(source, animation)) {
|
||||
machine.getCurrentNode().addForceConnectedNode(baseEntity -> true, machine.getRootNode());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forceStopAllAnimations() {
|
||||
this.actionQueue.add(() -> this.stateMachines.keySet().removeIf(key -> {
|
||||
if (key == DEFAULT_PRIORITY) {
|
||||
return false;
|
||||
} else {
|
||||
StateMachineHandler.AnimationStateMachine machine = this.stateMachines.get(key);
|
||||
return machine.getCurrentAnimation() == null || !machine.getCurrentAnimation().isIgnoreDeath();
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
private boolean hasAnimation(ModelState state) {
|
||||
return this.blueprint.getAnimations().containsKey(state.getString());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private IAnimationProperty createStateProperty(ModelState state) {
|
||||
AnimationHandler.DefaultProperty defProperty = this.getDefaultProperty(state);
|
||||
IAnimationProperty property = this.firstSpawn
|
||||
? defProperty.buildRef(this.activeModel, 0.0, defProperty.getLerpOut(), defProperty.getSpeed())
|
||||
: defProperty.buildRef(this.activeModel);
|
||||
if (property != null) {
|
||||
property.setForceLoopMode(state.getLoopMode());
|
||||
property.setForceOverride(state.getOverride());
|
||||
}
|
||||
|
||||
return property;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(SavedData data) {
|
||||
IStateMachineHandler.super.save(data);
|
||||
SavedData stateMachinesData = new SavedData();
|
||||
this.stateMachines.forEach((id, asm) -> asm.save().ifPresent(smd -> stateMachinesData.putData(Integer.toString(id), smd)));
|
||||
data.putData("state_machines", stateMachinesData);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(SavedData data) {
|
||||
IStateMachineHandler.super.load(data);
|
||||
data.getData("state_machines").ifPresent(stateMachinesData -> {
|
||||
for (String key : stateMachinesData.keySet()) {
|
||||
int id = Integer.parseInt(key);
|
||||
stateMachinesData.getData(key).ifPresent(smd -> {
|
||||
StateMachineHandler.AnimationStateMachine asm = new StateMachineHandler.AnimationStateMachine(true);
|
||||
asm.load(smd);
|
||||
this.stateMachines.put(id, asm);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static StateMachineHandler create(ActiveModel model, SavedData data) {
|
||||
StateMachineHandler handler = new StateMachineHandler(model);
|
||||
handler.load(data);
|
||||
return handler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActiveModel getActiveModel() {
|
||||
return this.activeModel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModelBlueprint getBlueprint() {
|
||||
return this.blueprint;
|
||||
}
|
||||
|
||||
public TreeMap<Integer, StateMachineHandler.AnimationStateMachine> getStateMachines() {
|
||||
return this.stateMachines;
|
||||
}
|
||||
|
||||
static {
|
||||
ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> DEFAULT_PRIORITY = ConfigProperty.DEFAULT_PRIORITY.getInt());
|
||||
}
|
||||
|
||||
public class AnimationStateMachine extends StateMachine<BaseEntity<?>> implements DataIO {
|
||||
protected final boolean saved;
|
||||
protected StateNode<BaseEntity<?>> rootNode;
|
||||
@Nullable
|
||||
protected IAnimationProperty lastAnimation;
|
||||
@Nullable
|
||||
protected IAnimationProperty currentAnimation;
|
||||
@Nullable
|
||||
protected IAnimationProperty queuedAnimation;
|
||||
protected boolean queuedForce;
|
||||
|
||||
@Override
|
||||
public StateNode<BaseEntity<?>> getCurrentNode() {
|
||||
return this.currentNode == null ? this.getRootNode() : this.currentNode;
|
||||
}
|
||||
|
||||
public StateNode<BaseEntity<?>> getRootNode() {
|
||||
if (this.rootNode == null) {
|
||||
this.rootNode = new StateNode<>(this);
|
||||
this.rootNode.setEntryAction(baseEntity -> this.currentAnimation = null);
|
||||
this.rootNode.setExitAction(baseEntity -> {
|
||||
this.rootNode.clearForceConnectedNodes();
|
||||
this.rootNode.clearConnectedNodes();
|
||||
this.lastAnimation = this.currentAnimation;
|
||||
});
|
||||
this.setEntryNode(this.rootNode);
|
||||
}
|
||||
|
||||
return this.rootNode;
|
||||
}
|
||||
|
||||
public StateNode<BaseEntity<?>> createAnimationNode(Supplier<IAnimationProperty> propertySupplier) {
|
||||
StateNode<BaseEntity<?>> node = new StateNode<>(this);
|
||||
node.setEntryAction(baseEntity -> this.currentAnimation = propertySupplier.get());
|
||||
node.setAction(baseEntity -> {
|
||||
if (this.currentAnimation != null) {
|
||||
this.currentAnimation.update();
|
||||
}
|
||||
|
||||
if (this.lastAnimation != null && this.lastAnimation != this.currentAnimation) {
|
||||
this.lastAnimation.update();
|
||||
}
|
||||
});
|
||||
node.setExitAction(baseEntity -> {
|
||||
AnimationEndEvent event = new AnimationEndEvent(StateMachineHandler.this.activeModel, this.currentAnimation);
|
||||
ModelEngineAPI.callEvent(event);
|
||||
if (this.currentAnimation instanceof SimpleProperty simpleProperty && simpleProperty.getOnEndTask() != null) {
|
||||
simpleProperty.getOnEndTask().run();
|
||||
}
|
||||
|
||||
this.lastAnimation = this.currentAnimation;
|
||||
});
|
||||
return node;
|
||||
}
|
||||
|
||||
private void materializeQueued() {
|
||||
if (this.queuedAnimation != null) {
|
||||
IAnimationProperty property = this.queuedAnimation;
|
||||
StateNode<BaseEntity<?>> currentNode = this.getCurrentNode();
|
||||
StateNode<BaseEntity<?>> node = this.createAnimationNode(() -> property);
|
||||
if (this.queuedForce) {
|
||||
currentNode.clearConnectedNodes();
|
||||
currentNode.clearForceConnectedNodes();
|
||||
}
|
||||
|
||||
node.addConnectedNode(baseEntity -> property.isEnded(), this.getRootNode());
|
||||
currentNode.addForceConnectedNode(baseEntity -> true, node);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasFinishedPlaying(ModelState modelState) {
|
||||
return !this.isPlaying(StateMachineHandler.this.getDefaultProperty(modelState).getAnimation());
|
||||
}
|
||||
|
||||
public boolean isPlaying(String animation) {
|
||||
return this.isPlaying(StateMachineHandler.this.blueprint, animation);
|
||||
}
|
||||
|
||||
public boolean isPlaying(ModelBlueprint source, String animation) {
|
||||
if (this.currentAnimation != null
|
||||
&& this.currentAnimation.getBlueprintAnimation().getModelBlueprint() == source
|
||||
&& this.currentAnimation.getBlueprintAnimation().getName().equals(animation)
|
||||
&& this.currentAnimation.getPhase() != IAnimationProperty.Phase.LERPOUT) {
|
||||
switch (this.currentAnimation.getLoopMode()) {
|
||||
case ONCE:
|
||||
if (this.currentAnimation.getTime() < this.currentAnimation.getBlueprintAnimation().getLength()) {
|
||||
return true;
|
||||
}
|
||||
break;
|
||||
case LOOP:
|
||||
if (this.currentAnimation.getTime() < this.currentAnimation.getBlueprintAnimation().getLength() + 0.05) {
|
||||
return true;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isQueued(ModelBlueprint source, String animation) {
|
||||
return this.queuedAnimation != null
|
||||
&& this.queuedAnimation.getBlueprintAnimation().getModelBlueprint() == source
|
||||
&& this.queuedAnimation.getBlueprintAnimation().getName().equals(animation);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public IAnimationProperty getEffectiveAnimation() {
|
||||
return this.queuedAnimation != null ? this.queuedAnimation : this.currentAnimation;
|
||||
}
|
||||
|
||||
public boolean isPlayingWithLog(ModelBlueprint source, String animation) {
|
||||
if (this.currentAnimation == null) {
|
||||
TLogger.log("Current Animation is null");
|
||||
return false;
|
||||
} else if (this.currentAnimation.getBlueprintAnimation().getModelBlueprint() != source) {
|
||||
TLogger.log("Current Animation is not from source");
|
||||
return false;
|
||||
} else if (!this.currentAnimation.getBlueprintAnimation().getName().equals(animation)) {
|
||||
TLogger.log("Current Animation name is not equal to animation");
|
||||
return false;
|
||||
} else if (this.currentAnimation.getPhase() == IAnimationProperty.Phase.LERPOUT) {
|
||||
TLogger.log("Current Animation is in LERPOUT phase");
|
||||
return false;
|
||||
} else {
|
||||
return switch (this.currentAnimation.getLoopMode()) {
|
||||
case ONCE -> {
|
||||
TLogger.log("Once: " + (this.currentAnimation.getTime() < this.currentAnimation.getBlueprintAnimation().getLength()));
|
||||
yield this.currentAnimation.getTime() < this.currentAnimation.getBlueprintAnimation().getLength();
|
||||
}
|
||||
case LOOP -> {
|
||||
TLogger.log("Loop: " + (this.currentAnimation.getTime() < this.currentAnimation.getBlueprintAnimation().getLength() + 0.05));
|
||||
yield this.currentAnimation.getTime() < this.currentAnimation.getBlueprintAnimation().getLength() + 0.05;
|
||||
}
|
||||
default -> true;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isPlayingOrEnding(String animation) {
|
||||
return this.isPlayingOrEnding(StateMachineHandler.this.blueprint, animation);
|
||||
}
|
||||
|
||||
public boolean isPlayingOrEnding(ModelBlueprint source, String animation) {
|
||||
return this.currentAnimation != null
|
||||
&& this.currentAnimation.getBlueprintAnimation().getModelBlueprint() == source
|
||||
&& this.currentAnimation.getName().equals(animation)
|
||||
&& !this.currentAnimation.isEnded();
|
||||
}
|
||||
|
||||
public void forceReentry(BaseEntity<?> base) {
|
||||
this.getCurrentNode().acceptEntry(base);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(SavedData data) {
|
||||
if (this.saved) {
|
||||
if (this.lastAnimation != null) {
|
||||
this.lastAnimation.save().ifPresent(data1 -> data.putData("last_animation", data1));
|
||||
}
|
||||
|
||||
if (this.currentAnimation != null) {
|
||||
this.currentAnimation.save().ifPresent(data1 -> data.putData("current_animation", data1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(SavedData data) {
|
||||
AnimationPropertyRegistry registry = ModelEngineAPI.getAnimationPropertyRegistry();
|
||||
data.getData("last_animation").ifPresent(property -> this.lastAnimation = registry.createAnimationProperty(StateMachineHandler.this, property));
|
||||
data.getData("current_animation").ifPresent(property -> this.currentAnimation = registry.createAnimationProperty(StateMachineHandler.this, property));
|
||||
StateNode<BaseEntity<?>> currentNode = this.getCurrentNode();
|
||||
if (this.currentAnimation != null) {
|
||||
StateNode<BaseEntity<?>> node = this.createAnimationNode(() -> this.currentAnimation);
|
||||
node.addConnectedNode(baseEntity -> this.currentAnimation.isEnded(), this.getRootNode());
|
||||
currentNode.addForceConnectedNode(baseEntity -> true, node);
|
||||
}
|
||||
}
|
||||
|
||||
public AnimationStateMachine(boolean saved) {
|
||||
this.saved = saved;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public IAnimationProperty getLastAnimation() {
|
||||
return this.lastAnimation;
|
||||
}
|
||||
|
||||
public void setLastAnimation(@Nullable IAnimationProperty lastAnimation) {
|
||||
this.lastAnimation = lastAnimation;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public IAnimationProperty getCurrentAnimation() {
|
||||
return this.currentAnimation;
|
||||
}
|
||||
|
||||
public void setCurrentAnimation(@Nullable IAnimationProperty currentAnimation) {
|
||||
this.currentAnimation = currentAnimation;
|
||||
}
|
||||
}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
package com.ticxo.modelengine.core.animation.script;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
|
||||
import com.ticxo.modelengine.api.animation.script.ScriptReader;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.type.NameTag;
|
||||
import com.ticxo.modelengine.api.utils.config.ConfigProperty;
|
||||
import com.ticxo.modelengine.api.utils.logger.TLogger;
|
||||
import com.ticxo.modelengine.api.utils.registry.TUnaryRegistry;
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.function.BiConsumer;
|
||||
import org.bukkit.Color;
|
||||
|
||||
public class ModelEngineScriptReader extends TUnaryRegistry<BiConsumer<ActiveModel, Map<String, String>>> implements ScriptReader {
|
||||
private boolean shouldPrintWarning;
|
||||
|
||||
public ModelEngineScriptReader() {
|
||||
ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig);
|
||||
this.register("changeparent", this::changeParent);
|
||||
this.register("partvis", this::partVisibility);
|
||||
this.register("tint", this::tint);
|
||||
this.register("enchant", this::enchant);
|
||||
this.register("tag", this::tag);
|
||||
this.register("changepart", this::changePart);
|
||||
this.register("remap", this::remap);
|
||||
}
|
||||
|
||||
public void updateConfig() {
|
||||
this.shouldPrintWarning = ConfigProperty.SCRIPT_WARNING.getBoolean();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void read(IAnimationProperty property, String script) {
|
||||
String[] scriptSplit = script.split("\\{", 2);
|
||||
String name = scriptSplit[0].toLowerCase(Locale.ENGLISH);
|
||||
BiConsumer<ActiveModel, Map<String, String>> function = this.get(name);
|
||||
if (function == null) {
|
||||
if (this.shouldPrintWarning) {
|
||||
TLogger.warn("Unknown Model Engine script: " + script);
|
||||
}
|
||||
} else if (scriptSplit.length != 2) {
|
||||
if (this.shouldPrintWarning) {
|
||||
TLogger.warn("Invalid Model Engine script: " + script);
|
||||
}
|
||||
} else {
|
||||
ActiveModel model = property.getModel();
|
||||
ModelBlueprint blueprint = model.getBlueprint();
|
||||
HashMap<String, String> map = new HashMap<>();
|
||||
String[] parameters = scriptSplit[1].substring(0, scriptSplit[1].length() - 1).split(";");
|
||||
|
||||
for (String param : parameters) {
|
||||
String[] entry = param.split("=", 2);
|
||||
map.put(entry[0].strip().toLowerCase(Locale.ENGLISH), entry.length == 2 ? this.getAnimationPlaceholder(blueprint, entry[1].strip()) : "");
|
||||
}
|
||||
|
||||
function.accept(model, map);
|
||||
}
|
||||
}
|
||||
|
||||
private String getAnimationPlaceholder(ModelBlueprint blueprint, String placeholder) {
|
||||
if (placeholder.startsWith("<") && placeholder.endsWith(">")) {
|
||||
String key = placeholder.substring(1, placeholder.length() - 1);
|
||||
return blueprint.getAnimationsPlaceholders().getOrDefault(key, placeholder);
|
||||
} else {
|
||||
return placeholder;
|
||||
}
|
||||
}
|
||||
|
||||
private void changeParent(ActiveModel model, Map<String, String> param) {
|
||||
String parentPart = param.get("parent");
|
||||
String childPart = param.get("child");
|
||||
model.getBone(parentPart).ifPresent(parent -> model.getBone(childPart).ifPresent(child -> child.setParent(parent)));
|
||||
}
|
||||
|
||||
private void partVisibility(ActiveModel model, Map<String, String> param) {
|
||||
String part = param.get("part");
|
||||
boolean visible = Boolean.parseBoolean(param.get("visible"));
|
||||
boolean exact = Boolean.parseBoolean(param.get("exact"));
|
||||
if (exact) {
|
||||
model.getBone(part).ifPresent(bonex -> bonex.setVisible(visible));
|
||||
} else {
|
||||
for (Entry<String, ModelBone> bone : model.getBones().entrySet()) {
|
||||
if (bone.getKey().contains(part)) {
|
||||
bone.getValue().setVisible(visible);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void tint(ActiveModel model, Map<String, String> param) {
|
||||
String part = param.get("part");
|
||||
String colorString = param.get("color");
|
||||
if (colorString.startsWith("#")) {
|
||||
colorString = colorString.substring(1);
|
||||
}
|
||||
|
||||
Color color = Color.fromRGB(Integer.parseInt(colorString, 16));
|
||||
boolean exact = Boolean.parseBoolean(param.get("exact"));
|
||||
boolean damage = Boolean.parseBoolean(param.get("damage"));
|
||||
if (part.isBlank()) {
|
||||
if (damage) {
|
||||
model.setDamageTint(color);
|
||||
} else {
|
||||
model.setDefaultTint(color);
|
||||
}
|
||||
} else if (exact) {
|
||||
model.getBone(part).ifPresent(bone -> {
|
||||
if (damage) {
|
||||
bone.setDamageTint(color);
|
||||
} else {
|
||||
bone.setDefaultTint(color);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
for (Entry<String, ModelBone> entry : model.getBones().entrySet()) {
|
||||
if (entry.getKey().contains(part)) {
|
||||
if (damage) {
|
||||
entry.getValue().setDamageTint(color);
|
||||
} else {
|
||||
entry.getValue().setDefaultTint(color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void enchant(ActiveModel model, Map<String, String> param) {
|
||||
String part = param.get("part");
|
||||
boolean enchant = Boolean.parseBoolean(param.get("enchant"));
|
||||
boolean exact = Boolean.parseBoolean(param.get("exact"));
|
||||
if (part != null && !part.isBlank()) {
|
||||
if (exact) {
|
||||
model.getBone(part).ifPresent(bone -> bone.setEnchanted(enchant));
|
||||
} else {
|
||||
for (Entry<String, ModelBone> entry : model.getBones().entrySet()) {
|
||||
if (entry.getKey().contains(part)) {
|
||||
entry.getValue().setEnchanted(enchant);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (ModelBone value : model.getBones().values()) {
|
||||
value.setEnchanted(enchant);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void tag(ActiveModel model, Map<String, String> param) {
|
||||
String part = param.get("part");
|
||||
String tag = param.get("tag");
|
||||
boolean visible = Boolean.parseBoolean(param.getOrDefault("visible", "true"));
|
||||
model.getBone(part).flatMap(modelBone -> modelBone.getBoneBehavior(BoneBehaviorTypes.NAMETAG)).ifPresent(nameTag -> {
|
||||
((NameTag)nameTag).setString(tag);
|
||||
((NameTag)nameTag).setVisible(visible);
|
||||
});
|
||||
}
|
||||
|
||||
private void changePart(ActiveModel model, Map<String, String> param) {
|
||||
String part = param.get("part");
|
||||
String nModel = param.get("nmodel");
|
||||
String nPart = param.get("npart");
|
||||
model.getBone(part).ifPresent(bone -> {
|
||||
if (bone.isRenderer()) {
|
||||
ModelBlueprint blueprint = ModelEngineAPI.getBlueprint(nModel);
|
||||
if (blueprint != null) {
|
||||
BlueprintBone blueprintBone = blueprint.getFlatMap().get(nPart);
|
||||
if (blueprintBone != null && blueprintBone.isRenderer()) {
|
||||
bone.setModelScale(blueprintBone.getScale());
|
||||
bone.setModel(blueprintBone);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void remap(ActiveModel model, Map<String, String> param) {
|
||||
String nModel = param.get("model");
|
||||
String map = param.get("map");
|
||||
ModelBlueprint blueprint = ModelEngineAPI.getBlueprint(nModel);
|
||||
if (blueprint != null) {
|
||||
if (map != null) {
|
||||
ModelBlueprint mapBlueprint = ModelEngineAPI.getBlueprint(map);
|
||||
if (mapBlueprint == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (String bone : mapBlueprint.getFlatMap().keySet()) {
|
||||
BlueprintBone blueprintBone = blueprint.getFlatMap().get(bone);
|
||||
if (blueprintBone != null && blueprintBone.isRenderer()) {
|
||||
model.getBone(bone).ifPresent(replaced -> {
|
||||
if (replaced.isRenderer()) {
|
||||
replaced.setModel(blueprintBone);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (String bonex : blueprint.getFlatMap().size() < model.getBones().size() ? blueprint.getFlatMap().keySet() : model.getBones().keySet()) {
|
||||
BlueprintBone blueprintBone = blueprint.getFlatMap().get(bonex);
|
||||
if (blueprintBone != null && blueprintBone.isRenderer()) {
|
||||
model.getBone(bonex).ifPresent(replaced -> {
|
||||
if (replaced.isRenderer()) {
|
||||
replaced.setModelScale(blueprintBone.getScale());
|
||||
replaced.setModel(blueprintBone);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
TLogger.log(blueprint.getName() + ": " + bonex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.ticxo.modelengine.core.citizens;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.nms.entity.EntityHandler;
|
||||
import net.citizensnpcs.api.trait.Trait;
|
||||
import net.citizensnpcs.api.trait.TraitName;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Particle;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.Particle.DustOptions;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.util.Vector;
|
||||
|
||||
@TraitName("bug")
|
||||
public class BugTrait extends Trait {
|
||||
private int tick;
|
||||
|
||||
public BugTrait() {
|
||||
super("bug");
|
||||
}
|
||||
|
||||
public void run() {
|
||||
Entity entity = this.npc.getEntity();
|
||||
if (entity != null) {
|
||||
EntityHandler handler = ModelEngineAPI.getEntityHandler();
|
||||
Location location = entity.getLocation();
|
||||
World world = location.getWorld();
|
||||
Vector yRot = new Vector(0.0, 0.0, 0.5).rotateAroundY(-handler.getYRot(entity) * (float) (Math.PI / 180.0));
|
||||
Vector yBodyRot = new Vector(0, 0, 1).rotateAroundY(-handler.getYBodyRot(entity) * (float) (Math.PI / 180.0));
|
||||
Vector yHeadRot = new Vector(0.0, 0.0, 1.5).rotateAroundY(-handler.getYHeadRot(entity) * (float) (Math.PI / 180.0));
|
||||
world.spawnParticle(Particle.REDSTONE, location.clone().add(yRot), 1, new DustOptions(Color.RED, 0.25F));
|
||||
world.spawnParticle(Particle.REDSTONE, location.clone().add(yBodyRot), 1, new DustOptions(Color.GREEN, 0.25F));
|
||||
world.spawnParticle(Particle.REDSTONE, location.clone().add(yHeadRot), 1, new DustOptions(Color.BLUE, 0.25F));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
package com.ticxo.modelengine.core.citizens;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
|
||||
import com.ticxo.modelengine.api.command.AbstractCommand;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.core.command.MECommand;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import net.citizensnpcs.api.CitizensAPI;
|
||||
import net.citizensnpcs.api.npc.NPC;
|
||||
import net.citizensnpcs.api.npc.NPCRegistry;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
public class CitizensCommand extends AbstractCommand {
|
||||
public CitizensCommand(AbstractCommand parent) {
|
||||
super(parent);
|
||||
this.addSubCommands(new AbstractCommand[]{new CitizensCommand.ModelCommand(this)});
|
||||
this.addSubCommands(new AbstractCommand[]{new CitizensCommand.StateCommand(this)});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, String[] args) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, String[] args) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermissionNode() {
|
||||
return "modelengine.command.npc";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConsoleFriendly() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "npc";
|
||||
}
|
||||
|
||||
private static void getNPCIdTabComplete(List<String> list) {
|
||||
CitizensAPI.getNPCRegistries().forEach(npcs -> npcs.sorted().forEach(npc -> {
|
||||
if (npc.isSpawned() && npc.hasTrait(ModelTrait.class)) {
|
||||
list.add(npcs.getName() + ":" + npc.getId() + ":[" + npc.getName().replace(" ", "-") + "]");
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
private static String tryGetOrDefault(String[] args, int index, String def) {
|
||||
return args.length <= index ? def : args[index];
|
||||
}
|
||||
|
||||
private static NPC getNPC(String id) {
|
||||
String[] val = id.split(":");
|
||||
if (val.length < 2) {
|
||||
throw new IllegalArgumentException("NPC ID must be formatted as <registry>:<NPC ID>");
|
||||
} else {
|
||||
NPCRegistry reg = CitizensAPI.getNamedNPCRegistry(val[0]);
|
||||
if (reg == null) {
|
||||
throw new IllegalArgumentException("Unknown NPC registry: " + val[0]);
|
||||
} else {
|
||||
NPC npc = reg.getById(Integer.parseInt(val[1]));
|
||||
if (npc == null) {
|
||||
throw new IllegalArgumentException("Unknown NPC ID: " + val[1]);
|
||||
} else {
|
||||
return npc;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class ModelCommand extends AbstractCommand {
|
||||
public ModelCommand(AbstractCommand parent) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, String[] args) {
|
||||
if (args.length < 1) {
|
||||
return false;
|
||||
} else {
|
||||
NPC npc = CitizensCommand.getNPC(args[0]);
|
||||
ModelTrait trait = (ModelTrait)npc.getTraitNullable(ModelTrait.class);
|
||||
if (trait == null) {
|
||||
return false;
|
||||
} else if (!npc.isSpawned()) {
|
||||
sender.sendMessage(ChatColor.RED + "Please spawn the NPC before editing.");
|
||||
return true;
|
||||
} else {
|
||||
ModeledEntity modeledEntity = trait.getOrCreateModeledEntity();
|
||||
if (modeledEntity == null) {
|
||||
sender.sendMessage(ChatColor.RED + "An error occurred while retrieving the model of this NPC.");
|
||||
return true;
|
||||
} else if (args.length >= 2) {
|
||||
if (args.length >= 3) {
|
||||
String modelId = args[2];
|
||||
String var13 = args[1];
|
||||
switch (var13) {
|
||||
case "add":
|
||||
boolean showBase = Boolean.parseBoolean(CitizensCommand.tryGetOrDefault(args, 3, "false"));
|
||||
boolean overrideHitbox = Boolean.parseBoolean(CitizensCommand.tryGetOrDefault(args, 4, "true"));
|
||||
ActiveModel model = ModelEngineAPI.createActiveModel(modelId);
|
||||
if (model == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
modeledEntity.setBaseEntityVisible(showBase);
|
||||
modeledEntity.addModel(model, overrideHitbox).ifPresent(ActiveModel::destroy);
|
||||
sender.sendMessage("Added model " + modelId + " to " + npc.getName());
|
||||
break;
|
||||
case "remove":
|
||||
modeledEntity.removeModel(modelId).ifPresent(ActiveModel::destroy);
|
||||
if (modeledEntity.getModels().isEmpty()) {
|
||||
modeledEntity.setBaseEntityVisible(true);
|
||||
}
|
||||
|
||||
sender.sendMessage("Removed model " + modelId + " from " + npc.getName());
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} else if (modeledEntity.getModels().isEmpty()) {
|
||||
sender.sendMessage("This NPC has no models.");
|
||||
return true;
|
||||
} else {
|
||||
StringBuilder builder = new StringBuilder("Models: ");
|
||||
|
||||
for (String active : modeledEntity.getModels().keySet()) {
|
||||
builder.append(active).append(", ");
|
||||
}
|
||||
|
||||
builder.delete(builder.length() - 2, builder.length());
|
||||
sender.sendMessage(builder.toString());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, String[] args) {
|
||||
List<String> list = new ArrayList<>();
|
||||
String arg = args[args.length - 1];
|
||||
switch (args.length) {
|
||||
case 1:
|
||||
CitizensCommand.getNPCIdTabComplete(list);
|
||||
break;
|
||||
case 2:
|
||||
if ("add".startsWith(arg)) {
|
||||
list.add("add");
|
||||
}
|
||||
|
||||
if ("remove".startsWith(arg)) {
|
||||
list.add("remove");
|
||||
}
|
||||
break;
|
||||
case 3:
|
||||
String var5 = args[1];
|
||||
switch (var5) {
|
||||
case "add":
|
||||
MECommand.getModelIdTabComplete(list, arg);
|
||||
return list;
|
||||
case "remove":
|
||||
ModelTrait trait = (ModelTrait)CitizensCommand.getNPC(args[0]).getTraitNullable(ModelTrait.class);
|
||||
if (trait != null) {
|
||||
MECommand.getModelIdTabComplete(list, arg, trait.getModeledEntity());
|
||||
}
|
||||
|
||||
return list;
|
||||
default:
|
||||
return list;
|
||||
}
|
||||
case 4:
|
||||
if ("add".equals(args[1])) {
|
||||
list.add("[showBaseEntity]");
|
||||
if ("true".startsWith(arg)) {
|
||||
list.add("true");
|
||||
}
|
||||
|
||||
if ("false".startsWith(arg)) {
|
||||
list.add("false");
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 5:
|
||||
if ("add".equals(args[1])) {
|
||||
list.add("[overrideHitbox]");
|
||||
if ("true".startsWith(arg)) {
|
||||
list.add("true");
|
||||
}
|
||||
|
||||
if ("false".startsWith(arg)) {
|
||||
list.add("false");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermissionNode() {
|
||||
return "modelengine.command.npc.model";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConsoleFriendly() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "model";
|
||||
}
|
||||
}
|
||||
|
||||
private static class StateCommand extends AbstractCommand {
|
||||
public StateCommand(AbstractCommand parent) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, String[] args) {
|
||||
if (args.length < 1) {
|
||||
return false;
|
||||
} else {
|
||||
NPC npc = CitizensCommand.getNPC(args[0]);
|
||||
ModelTrait trait = (ModelTrait)npc.getTraitNullable(ModelTrait.class);
|
||||
if (trait == null) {
|
||||
return false;
|
||||
} else if (!npc.isSpawned()) {
|
||||
sender.sendMessage(ChatColor.RED + "Please spawn the NPC before editing.");
|
||||
return true;
|
||||
} else {
|
||||
ModeledEntity modeledEntity = trait.getOrCreateModeledEntity();
|
||||
if (modeledEntity == null) {
|
||||
sender.sendMessage(ChatColor.RED + "An error occurred while retrieving the model of this NPC.");
|
||||
return true;
|
||||
} else {
|
||||
ActiveModel activeModel = modeledEntity.getModel(args[1]).orElse(null);
|
||||
if (activeModel == null) {
|
||||
return false;
|
||||
} else if (args.length >= 3) {
|
||||
if (args.length < 4) {
|
||||
return false;
|
||||
} else {
|
||||
String stateId = args[3];
|
||||
String var15 = args[2];
|
||||
switch (var15) {
|
||||
case "add":
|
||||
if (!activeModel.getBlueprint().getAnimations().containsKey(stateId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int lerpIn = Integer.parseInt(CitizensCommand.tryGetOrDefault(args, 4, "0"));
|
||||
int lerpOut = Integer.parseInt(CitizensCommand.tryGetOrDefault(args, 5, "0"));
|
||||
double speed = Double.parseDouble(CitizensCommand.tryGetOrDefault(args, 6, "1"));
|
||||
activeModel.getAnimationHandler().playAnimation(stateId, lerpIn / 20.0, lerpOut / 20.0, speed, true);
|
||||
sender.sendMessage("Added state " + stateId + " to " + npc.getName());
|
||||
break;
|
||||
case "remove":
|
||||
boolean ignoreLerp = Boolean.parseBoolean(CitizensCommand.tryGetOrDefault(args, 4, "false"));
|
||||
if (ignoreLerp) {
|
||||
activeModel.getAnimationHandler().forceStopAnimation(stateId);
|
||||
} else {
|
||||
activeModel.getAnimationHandler().forceStopAnimation(stateId);
|
||||
}
|
||||
|
||||
sender.sendMessage("Removed state " + stateId + " from " + npc.getName());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append(args[1]).append(": ");
|
||||
|
||||
for (IAnimationProperty animation : activeModel.getAnimationHandler().getAnimations().values()) {
|
||||
builder.append(animation.getName()).append(", ");
|
||||
}
|
||||
|
||||
builder.delete(builder.length() - 2, builder.length());
|
||||
sender.sendMessage(builder.toString());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, String[] args) {
|
||||
List<String> list = new ArrayList<>();
|
||||
String arg = args[args.length - 1];
|
||||
switch (args.length) {
|
||||
case 1:
|
||||
CitizensCommand.getNPCIdTabComplete(list);
|
||||
break;
|
||||
case 2:
|
||||
ModelTrait traitx = (ModelTrait)CitizensCommand.getNPC(args[0]).getTraitNullable(ModelTrait.class);
|
||||
if (traitx != null) {
|
||||
MECommand.getModelIdTabComplete(list, arg, traitx.getModeledEntity());
|
||||
}
|
||||
break;
|
||||
case 3:
|
||||
if ("add".startsWith(arg)) {
|
||||
list.add("add");
|
||||
}
|
||||
|
||||
if ("remove".startsWith(arg)) {
|
||||
list.add("remove");
|
||||
}
|
||||
break;
|
||||
case 4:
|
||||
ModelTrait trait = (ModelTrait)CitizensCommand.getNPC(args[0]).getTraitNullable(ModelTrait.class);
|
||||
if (trait == null) {
|
||||
return list;
|
||||
}
|
||||
|
||||
ModeledEntity model = trait.getModeledEntity();
|
||||
ActiveModel activeModel = model.getModel(args[1]).orElse(null);
|
||||
if (activeModel == null) {
|
||||
return list;
|
||||
}
|
||||
|
||||
String var8 = args[2];
|
||||
switch (var8) {
|
||||
case "add":
|
||||
MECommand.getStateTabComplete(list, arg, activeModel.getBlueprint());
|
||||
return list;
|
||||
case "remove":
|
||||
MECommand.getStateTabComplete(list, arg, activeModel);
|
||||
return list;
|
||||
default:
|
||||
return list;
|
||||
}
|
||||
case 5:
|
||||
String traitAction = args[2];
|
||||
switch (traitAction) {
|
||||
case "add":
|
||||
list.add("[lerpin]");
|
||||
return list;
|
||||
case "remove":
|
||||
list.add("[ignoreLerp]");
|
||||
if ("true".startsWith(arg)) {
|
||||
list.add("true");
|
||||
}
|
||||
|
||||
if ("false".startsWith(arg)) {
|
||||
list.add("false");
|
||||
}
|
||||
|
||||
return list;
|
||||
default:
|
||||
return list;
|
||||
}
|
||||
case 6:
|
||||
if ("add".equals(args[2])) {
|
||||
list.add("[lerpout]");
|
||||
}
|
||||
break;
|
||||
case 7:
|
||||
if ("add".equals(args[2])) {
|
||||
list.add("[speed]");
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermissionNode() {
|
||||
return "modelengine.command.npc.state";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConsoleFriendly() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "state";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.ticxo.modelengine.core.citizens;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.entity.BukkitEntity;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.api.utils.data.io.SavedData;
|
||||
import com.ticxo.modelengine.core.data.DataUpdater;
|
||||
import net.citizensnpcs.api.trait.Trait;
|
||||
import net.citizensnpcs.api.trait.TraitName;
|
||||
import net.citizensnpcs.api.util.DataKey;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Entity;
|
||||
|
||||
@TraitName("meg_model")
|
||||
public class ModelTrait extends Trait {
|
||||
private String modelData;
|
||||
|
||||
public ModelTrait() {
|
||||
super("meg_model");
|
||||
}
|
||||
|
||||
public void load(DataKey key) {
|
||||
this.modelData = key.getString("model_data");
|
||||
}
|
||||
|
||||
public void save(DataKey key) {
|
||||
ModeledEntity modeledEntity = this.getModeledEntity();
|
||||
if (modeledEntity != null) {
|
||||
modeledEntity.save().ifPresent(data -> this.modelData = data.toString());
|
||||
} else {
|
||||
this.modelData = null;
|
||||
}
|
||||
|
||||
key.setString("model_data", this.modelData);
|
||||
}
|
||||
|
||||
public void onDespawn() {
|
||||
ModeledEntity modeledEntity = this.getModeledEntity();
|
||||
if (modeledEntity != null) {
|
||||
modeledEntity.save().ifPresent(data -> this.modelData = data.toString());
|
||||
} else {
|
||||
this.modelData = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void onSpawn() {
|
||||
if (this.modelData != null) {
|
||||
Entity entity = this.getNPC().getEntity();
|
||||
Location location = entity.getLocation();
|
||||
SavedData data = DataUpdater.convertToSavedData(location, this.modelData);
|
||||
if (DataUpdater.tryUpdate(data)) {
|
||||
BukkitEntity base = new BukkitEntity(entity);
|
||||
base.getBodyRotationController().setYBodyRot(location.getYaw());
|
||||
ModeledEntity modeledEntity = ModelEngineAPI.createModeledEntity(base);
|
||||
modeledEntity.setSaved(false);
|
||||
modeledEntity.load(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public ModeledEntity getModeledEntity() {
|
||||
return this.npc.getEntity() != null ? ModelEngineAPI.getModeledEntity(this.npc.getEntity()) : null;
|
||||
}
|
||||
|
||||
public ModeledEntity getOrCreateModeledEntity() {
|
||||
return this.npc.getEntity() != null ? ModelEngineAPI.getOrCreateModeledEntity(this.npc.getEntity()) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.ticxo.modelengine.core.command;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
|
||||
import com.ticxo.modelengine.api.command.AbstractCommand;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.api.utils.logger.TLogger;
|
||||
import com.ticxo.modelengine.core.command.sub.DebugCommand;
|
||||
import com.ticxo.modelengine.core.command.sub.DisguiseCommand;
|
||||
import com.ticxo.modelengine.core.command.sub.MenuCommand;
|
||||
import com.ticxo.modelengine.core.command.sub.PluginHealthCommand;
|
||||
import com.ticxo.modelengine.core.command.sub.ReloadCommand;
|
||||
import com.ticxo.modelengine.core.command.sub.ResyncCommand;
|
||||
import com.ticxo.modelengine.core.command.sub.SummonCommand;
|
||||
import com.ticxo.modelengine.core.command.sub.ToggleLODCommand;
|
||||
import com.ticxo.modelengine.core.command.sub.UndisguiseCommand;
|
||||
import java.util.List;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Entity;
|
||||
|
||||
public class MECommand extends AbstractCommand {
|
||||
public MECommand(ModelEngineAPI plugin) {
|
||||
super(plugin);
|
||||
this.addSubCommands(new AbstractCommand[]{new ReloadCommand(this)});
|
||||
this.addSubCommands(new AbstractCommand[]{new SummonCommand(this)});
|
||||
this.addSubCommands(new AbstractCommand[]{new DisguiseCommand(this)});
|
||||
this.addSubCommands(new AbstractCommand[]{new UndisguiseCommand(this)});
|
||||
this.addSubCommands(new AbstractCommand[]{new DebugCommand(this)});
|
||||
this.addSubCommands(new AbstractCommand[]{new MenuCommand(this)});
|
||||
this.addSubCommands(new AbstractCommand[]{new PluginHealthCommand(this)});
|
||||
this.addSubCommands(new AbstractCommand[]{new ResyncCommand(this)});
|
||||
this.addSubCommands(new AbstractCommand[]{new ToggleLODCommand(this)});
|
||||
}
|
||||
|
||||
public static void getModelIdTabComplete(List<String> list, String arg) {
|
||||
for (String id : ModelEngineAPI.getAPI().getModelRegistry().getKeys()) {
|
||||
if (id.startsWith(arg)) {
|
||||
list.add(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void getModelIdTabComplete(List<String> list, String arg, ModeledEntity modeledEntity) {
|
||||
for (String id : modeledEntity.getModels().keySet()) {
|
||||
if (id.startsWith(arg)) {
|
||||
list.add(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void getStateTabComplete(List<String> list, String arg, ActiveModel model) {
|
||||
for (IAnimationProperty animation : model.getAnimationHandler().getAnimations().values()) {
|
||||
String name = animation.getName();
|
||||
if (name.startsWith(arg)) {
|
||||
list.add(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void getStateTabComplete(List<String> list, String arg, ModelBlueprint blueprint) {
|
||||
for (String animation : blueprint.getAnimations().keySet()) {
|
||||
if (animation.startsWith(arg)) {
|
||||
list.add(animation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void logSender(CommandSender sender, String msg) {
|
||||
logSender(sender, msg, msg);
|
||||
}
|
||||
|
||||
public static void logSender(CommandSender sender, String entityMsg, String consoleMsg) {
|
||||
if (sender instanceof Entity) {
|
||||
sender.sendMessage(entityMsg);
|
||||
} else {
|
||||
TLogger.log(consoleMsg);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, String[] args) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, String[] args) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermissionNode() {
|
||||
return "modelengine.command";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConsoleFriendly() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package com.ticxo.modelengine.core.command;
|
||||
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.bukkit.Color;
|
||||
|
||||
public final class ModelOptionParser {
|
||||
private Boolean doDamageTint;
|
||||
private Boolean lockPitch;
|
||||
private Boolean lockYaw;
|
||||
private Boolean showHitbox;
|
||||
private Boolean showShadow;
|
||||
private Double stepHeight;
|
||||
private Double scale;
|
||||
private Double hitboxScale;
|
||||
private Integer viewRadius;
|
||||
private Color color;
|
||||
public Boolean hideSelf = true;
|
||||
public Boolean hideSelfDisguise = false;
|
||||
public Boolean pivotOverride = true;
|
||||
|
||||
public static ModelOptionParser parse(int offset, String[] argss) {
|
||||
ModelOptionParser options = new ModelOptionParser();
|
||||
if (argss.length <= offset) {
|
||||
return options;
|
||||
} else {
|
||||
String[] args = Arrays.copyOfRange(argss, offset, argss.length);
|
||||
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
String var5 = args[i].toLowerCase();
|
||||
switch (var5) {
|
||||
case "dodamagetint":
|
||||
options.doDamageTint = getNextBoolean(args, ++i);
|
||||
break;
|
||||
case "lockpitch":
|
||||
options.lockPitch = getNextBoolean(args, ++i);
|
||||
break;
|
||||
case "lockyaw":
|
||||
options.lockYaw = getNextBoolean(args, ++i);
|
||||
break;
|
||||
case "showhitbox":
|
||||
options.showHitbox = getNextBoolean(args, ++i);
|
||||
break;
|
||||
case "showshadow":
|
||||
options.showShadow = getNextBoolean(args, ++i);
|
||||
break;
|
||||
case "stepheight":
|
||||
options.stepHeight = getNextDouble(args, ++i);
|
||||
break;
|
||||
case "scale":
|
||||
options.scale = getNextDouble(args, ++i);
|
||||
break;
|
||||
case "hitboxscale":
|
||||
options.hitboxScale = getNextDouble(args, ++i);
|
||||
break;
|
||||
case "viewradius":
|
||||
options.viewRadius = getNextInteger(args, ++i);
|
||||
break;
|
||||
case "hideself":
|
||||
options.hideSelf = getNextBoolean(args, ++i);
|
||||
break;
|
||||
case "hideselfdisguise":
|
||||
options.hideSelfDisguise = getNextBoolean(args, ++i);
|
||||
break;
|
||||
case "color":
|
||||
String colorString = getNextString(args, ++i);
|
||||
if (colorString.startsWith("#")) {
|
||||
colorString = colorString.substring(1);
|
||||
}
|
||||
|
||||
options.color = Color.fromRGB(Integer.parseInt(colorString, 16));
|
||||
break;
|
||||
case "pivotoverride":
|
||||
options.pivotOverride = getNextBoolean(args, ++i);
|
||||
}
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
}
|
||||
|
||||
public static List<String> getTabCompletion(int offset, String[] argss) {
|
||||
String[] args = Arrays.copyOfRange(argss, offset, argss.length);
|
||||
List<String> completions = new ArrayList<>();
|
||||
if (args.length == 1) {
|
||||
completions.addAll(
|
||||
Arrays.asList(
|
||||
"doDamageTint",
|
||||
"lockPitch",
|
||||
"lockYaw",
|
||||
"showHitbox",
|
||||
"showShadow",
|
||||
"stepHeight",
|
||||
"scale",
|
||||
"hitboxScale",
|
||||
"viewRadius",
|
||||
"hideSelfDisguise",
|
||||
"color",
|
||||
"pivotOverride",
|
||||
"hideSelf"
|
||||
)
|
||||
);
|
||||
return completions;
|
||||
} else {
|
||||
String lastArg = args[args.length - 2].toLowerCase();
|
||||
if (!isValueExpected(lastArg)) {
|
||||
completions.addAll(
|
||||
Arrays.asList(
|
||||
"doDamageTint",
|
||||
"lockPitch",
|
||||
"lockYaw",
|
||||
"showHitbox",
|
||||
"showShadow",
|
||||
"stepHeight",
|
||||
"scale",
|
||||
"hitboxScale",
|
||||
"viewRadius",
|
||||
"hideSelfDisguise",
|
||||
"color",
|
||||
"pivotOverride",
|
||||
"hideSelf"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return completions;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isValueExpected(String lastArg) {
|
||||
return lastArg.matches("stepheight|scale|hitboxscale|viewradius|color");
|
||||
}
|
||||
|
||||
public void applyDisguiseOptions(ActiveModel activeModel) {
|
||||
if (this.scale != null) {
|
||||
activeModel.setScale(this.scale);
|
||||
}
|
||||
|
||||
if (this.hitboxScale != null) {
|
||||
activeModel.setHitboxScale(this.hitboxScale);
|
||||
}
|
||||
|
||||
if (this.doDamageTint != null) {
|
||||
activeModel.setCanHurt(this.doDamageTint);
|
||||
}
|
||||
|
||||
if (this.lockPitch != null) {
|
||||
activeModel.setLockPitch(this.lockPitch);
|
||||
}
|
||||
|
||||
if (this.lockYaw != null) {
|
||||
activeModel.setLockYaw(this.lockYaw);
|
||||
}
|
||||
|
||||
if (this.showHitbox != null) {
|
||||
activeModel.setHitboxVisible(this.showHitbox);
|
||||
}
|
||||
|
||||
if (this.showShadow != null) {
|
||||
activeModel.setShadowVisible(this.showShadow);
|
||||
}
|
||||
|
||||
if (this.viewRadius != null) {
|
||||
activeModel.getModeledEntity().getBase().setRenderRadius(this.viewRadius);
|
||||
}
|
||||
|
||||
if (this.stepHeight != null) {
|
||||
activeModel.getModeledEntity().getBase().setMaxStepHeight(this.stepHeight);
|
||||
}
|
||||
|
||||
if (this.color != null) {
|
||||
activeModel.setDefaultTint(this.color);
|
||||
}
|
||||
}
|
||||
|
||||
private static Boolean getNextBoolean(String[] args, int index) {
|
||||
if (index >= args.length) {
|
||||
return true;
|
||||
} else {
|
||||
String nextArg = args[index].toLowerCase();
|
||||
return nextArg.equals("true") || !nextArg.equals("false");
|
||||
}
|
||||
}
|
||||
|
||||
private static Double getNextDouble(String[] args, int index) {
|
||||
try {
|
||||
return index < args.length ? Double.parseDouble(args[index]) : null;
|
||||
} catch (NumberFormatException var3) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Integer getNextInteger(String[] args, int index) {
|
||||
try {
|
||||
return index < args.length ? Integer.parseInt(args[index]) : null;
|
||||
} catch (NumberFormatException var3) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String getNextString(String[] args, int index) {
|
||||
try {
|
||||
return index < args.length ? args[index] : null;
|
||||
} catch (NumberFormatException var3) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.ticxo.modelengine.core.command.sub;
|
||||
|
||||
import com.ticxo.modelengine.api.command.AbstractCommand;
|
||||
import com.ticxo.modelengine.api.utils.config.DebugToggle;
|
||||
import com.ticxo.modelengine.api.utils.logger.LogColor;
|
||||
import com.ticxo.modelengine.core.command.MECommand;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
public class DebugCommand extends AbstractCommand {
|
||||
public DebugCommand(AbstractCommand parent) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, String[] args) {
|
||||
if (args.length == 0) {
|
||||
return false;
|
||||
} else {
|
||||
DebugToggle debugToggle = DebugToggle.get(args[0]);
|
||||
if (debugToggle == null) {
|
||||
MECommand.logSender(sender, ChatColor.RED + "[ModelEngine] Unknown debug: " + args[0] + ".", LogColor.RED + "Unknown debug: " + args[0] + ".");
|
||||
return false;
|
||||
} else if (args.length == 1) {
|
||||
MECommand.logSender(
|
||||
sender,
|
||||
ChatColor.GREEN + "[ModelEngine] " + debugToggle.name() + " is " + (DebugToggle.isDebugging(debugToggle) ? "enabled." : "disabled."),
|
||||
LogColor.BRIGHT_GREEN + debugToggle.name() + " is " + (DebugToggle.isDebugging(debugToggle) ? "enabled." : "disabled.")
|
||||
);
|
||||
return true;
|
||||
} else {
|
||||
boolean flag = Boolean.parseBoolean(args[1]);
|
||||
DebugToggle.setDebug(debugToggle, flag);
|
||||
MECommand.logSender(
|
||||
sender,
|
||||
ChatColor.GREEN + "[ModelEngine] Set " + debugToggle.name() + " to " + flag + ".",
|
||||
LogColor.BRIGHT_GREEN + "Set " + debugToggle.name() + " to " + flag + "."
|
||||
);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, String[] args) {
|
||||
ArrayList<String> list = new ArrayList<>();
|
||||
switch (args.length) {
|
||||
case 1:
|
||||
for (DebugToggle debug : DebugToggle.values()) {
|
||||
list.add(debug.name());
|
||||
}
|
||||
break;
|
||||
case 2:
|
||||
list.add("true");
|
||||
list.add("false");
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermissionNode() {
|
||||
return "modelengine.command.debug";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConsoleFriendly() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "debug";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.ticxo.modelengine.core.command.sub;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.command.AbstractCommand;
|
||||
import com.ticxo.modelengine.api.entity.data.BukkitEntityData;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes;
|
||||
import com.ticxo.modelengine.api.model.bone.type.PlayerLimb;
|
||||
import com.ticxo.modelengine.api.model.bone.type.UserLimb;
|
||||
import com.ticxo.modelengine.core.command.MECommand;
|
||||
import com.ticxo.modelengine.core.command.ModelOptionParser;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class DisguiseCommand extends AbstractCommand {
|
||||
public DisguiseCommand(AbstractCommand parent) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, String[] args) {
|
||||
Player player = (Player)sender;
|
||||
if (args.length < 1) {
|
||||
return false;
|
||||
} else {
|
||||
ModelBlueprint blueprint = ModelEngineAPI.getBlueprint(args[0]);
|
||||
if (blueprint == null) {
|
||||
return false;
|
||||
} else {
|
||||
ModelOptionParser options = ModelOptionParser.parse(1, args);
|
||||
ModeledEntity modeledEntity = ModelEngineAPI.getOrCreateModeledEntity(player);
|
||||
modeledEntity.getBase().getBodyRotationController().setPlayerMode(true);
|
||||
modeledEntity.setBaseEntityVisible(!options.hideSelf);
|
||||
if (modeledEntity.getBase().getData() instanceof BukkitEntityData data && (args.length < 2 || !options.hideSelfDisguise)) {
|
||||
data.getTracked().addForcedPairing(player.getUniqueId());
|
||||
}
|
||||
|
||||
if (options.hideSelf) {
|
||||
ModelEngineAPI.getEntityHandler().setForcedInvisible(player, true);
|
||||
}
|
||||
|
||||
if (modeledEntity.getModel(args[0]).isEmpty()) {
|
||||
ActiveModel activeModel = ModelEngineAPI.createActiveModel(blueprint);
|
||||
options.applyDisguiseOptions(activeModel);
|
||||
modeledEntity.addModel(activeModel, false).ifPresent(ActiveModel::destroy);
|
||||
if (options.pivotOverride) {
|
||||
activeModel.setPivotOverride(ModelEngineAPI.getPivotOverrideRegistry().getOrCreate(player));
|
||||
}
|
||||
|
||||
activeModel.getBones().values().forEach(modelBone -> {
|
||||
modelBone.getBoneBehavior(BoneBehaviorTypes.PLAYER_LIMB).ifPresent(playerLimb -> ((PlayerLimb)playerLimb).setTexture(player));
|
||||
modelBone.getBoneBehavior(BoneBehaviorTypes.USER_LIMB).ifPresent(playerLimb -> ((UserLimb)playerLimb).setTexture(player));
|
||||
});
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, String[] args) {
|
||||
List<String> list = new ArrayList<>();
|
||||
switch (args.length) {
|
||||
case 1:
|
||||
MECommand.getModelIdTabComplete(list, args[0]);
|
||||
break;
|
||||
default:
|
||||
list.addAll(ModelOptionParser.getTabCompletion(1, args));
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermissionNode() {
|
||||
return "modelengine.command.disguise";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConsoleFriendly() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "disguise";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.ticxo.modelengine.core.command.sub;
|
||||
|
||||
import com.ticxo.modelengine.api.command.AbstractCommand;
|
||||
import com.ticxo.modelengine.core.menu.screen.NavigationScreen;
|
||||
import java.util.List;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class MenuCommand extends AbstractCommand {
|
||||
public MenuCommand(AbstractCommand parent) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, String[] args) {
|
||||
if (sender instanceof Player player) {
|
||||
new NavigationScreen(player).openScreen();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, String[] args) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermissionNode() {
|
||||
return "modelengine.command.menu";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConsoleFriendly() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "menu";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.ticxo.modelengine.core.command.sub;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.command.AbstractCommand;
|
||||
import com.ticxo.modelengine.api.entity.EntityDataTrackers;
|
||||
import com.ticxo.modelengine.api.utils.Profiler;
|
||||
import com.ticxo.modelengine.core.command.MECommand;
|
||||
import java.util.List;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
public class PluginHealthCommand extends AbstractCommand {
|
||||
public PluginHealthCommand(AbstractCommand parent) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, String[] args) {
|
||||
Profiler updaterProfiler = ModelEngineAPI.getAPI().getModelUpdaters().getProfiler();
|
||||
MECommand.logSender(
|
||||
sender,
|
||||
String.format(
|
||||
"Model Updaters: Min: %.3f ms, Max: %.3f ms, Avg: %.3f ms",
|
||||
updaterProfiler.getMinTime() / 1000000.0,
|
||||
updaterProfiler.getMaxTime() / 1000000.0,
|
||||
updaterProfiler.getAverageTime() / 1000000.0
|
||||
)
|
||||
);
|
||||
EntityDataTrackers trackers = ModelEngineAPI.getAPI().getDataTrackers();
|
||||
MECommand.logSender(sender, "Entity Data Trackers:");
|
||||
|
||||
for (EntityDataTrackers.Tracker tracker : trackers.getAvailable()) {
|
||||
MECommand.logSender(sender, String.format("- %s: %s (%sms)", tracker.getId(), tracker.getLoad(), tracker.getTimings()));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, String[] args) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermissionNode() {
|
||||
return "modelengine.command.health";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConsoleFriendly() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "health";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.ticxo.modelengine.core.command.sub;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.command.AbstractCommand;
|
||||
import com.ticxo.modelengine.api.generator.ModelGenerator;
|
||||
import com.ticxo.modelengine.api.generator.skin.SkinSplitter;
|
||||
import com.ticxo.modelengine.api.utils.config.ConfigManager;
|
||||
import com.ticxo.modelengine.api.utils.logger.LogColor;
|
||||
import com.ticxo.modelengine.api.utils.logger.TLogger;
|
||||
import com.ticxo.modelengine.core.command.MECommand;
|
||||
import java.util.List;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Entity;
|
||||
|
||||
public class ReloadCommand extends AbstractCommand {
|
||||
public ReloadCommand(AbstractCommand parent) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, String[] args) {
|
||||
if (args.length == 0) {
|
||||
this.reloadConfig(sender);
|
||||
this.reloadModels(sender);
|
||||
this.reloadMappings(sender);
|
||||
return true;
|
||||
} else {
|
||||
String var3 = args[0];
|
||||
switch (var3) {
|
||||
case "models":
|
||||
this.reloadModels(sender);
|
||||
break;
|
||||
case "config":
|
||||
this.reloadConfig(sender);
|
||||
break;
|
||||
case "mappings":
|
||||
this.reloadMappings(sender);
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private void reloadConfig(CommandSender sender) {
|
||||
ConfigManager config = ModelEngineAPI.getAPI().getConfigManager();
|
||||
config.reload();
|
||||
config.updateReferences();
|
||||
MECommand.logSender(sender, ChatColor.GREEN + "[ModelEngine] Config reloaded.", LogColor.BRIGHT_GREEN + "Config reloaded.");
|
||||
}
|
||||
|
||||
private void reloadModels(CommandSender sender) {
|
||||
ModelGenerator generator = ModelEngineAPI.getAPI().getModelGenerator();
|
||||
generator.importModels(false);
|
||||
generator.queueTask(ModelGenerator.Phase.POST_IMPORT, () -> {
|
||||
String msg = ModelEngineAPI.getAPI().getModelRegistry().getKeys().size() + " models loaded.";
|
||||
if (sender instanceof Entity) {
|
||||
sender.sendMessage(ChatColor.GREEN + "[ModelEngine] " + msg);
|
||||
} else {
|
||||
TLogger.log();
|
||||
TLogger.log(LogColor.BRIGHT_GREEN + msg);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void reloadMappings(CommandSender sender) {
|
||||
SkinSplitter generator = ModelEngineAPI.getAPI().getSkinSplitter();
|
||||
generator.reloadMapping();
|
||||
MECommand.logSender(sender, ChatColor.GREEN + "[ModelEngine] Skin mappings reloaded.", LogColor.BRIGHT_GREEN + "Skin mappings reloaded.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, String[] args) {
|
||||
return List.of("models", "config", "mappings");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermissionNode() {
|
||||
return "modelengine.command.reload";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConsoleFriendly() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "reload";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.ticxo.modelengine.core.command.sub;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.command.AbstractCommand;
|
||||
import java.util.List;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class ResyncCommand extends AbstractCommand {
|
||||
public ResyncCommand(AbstractCommand parent) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, String[] args) {
|
||||
if (sender instanceof Player player) {
|
||||
ModelEngineAPI.getNetworkHandler().getPipeline(player.getUniqueId()).ifPresent(wrapper -> {
|
||||
if (args.length >= 1) {
|
||||
wrapper.setDelay(Long.parseLong(args[0]));
|
||||
} else {
|
||||
wrapper.getDesyncMonitor().startTest();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, String[] args) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermissionNode() {
|
||||
return "modelengine.command.resync";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConsoleFriendly() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "resync";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.ticxo.modelengine.core.command.sub;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.command.AbstractCommand;
|
||||
import com.ticxo.modelengine.api.entity.BukkitEntity;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes;
|
||||
import com.ticxo.modelengine.api.model.bone.type.PlayerLimb;
|
||||
import com.ticxo.modelengine.api.model.bone.type.UserLimb;
|
||||
import com.ticxo.modelengine.core.command.MECommand;
|
||||
import com.ticxo.modelengine.core.command.ModelOptionParser;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.EntityType;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class SummonCommand extends AbstractCommand {
|
||||
public SummonCommand(AbstractCommand parent) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, String[] args) {
|
||||
if (args.length < 1) {
|
||||
return false;
|
||||
} else {
|
||||
EntityType type = EntityType.PIG;
|
||||
if (args.length >= 2) {
|
||||
try {
|
||||
type = EntityType.valueOf(args[1].toUpperCase(Locale.ENGLISH));
|
||||
} catch (IllegalArgumentException var9) {
|
||||
}
|
||||
}
|
||||
|
||||
Class<? extends Entity> clazz = type.getEntityClass();
|
||||
if (clazz == null) {
|
||||
return false;
|
||||
} else {
|
||||
ModelBlueprint blueprint = ModelEngineAPI.getBlueprint(args[0]);
|
||||
if (blueprint == null) {
|
||||
return false;
|
||||
} else {
|
||||
ModelOptionParser options = ModelOptionParser.parse(2, args);
|
||||
Player player = (Player)sender;
|
||||
Location location = player.getLocation();
|
||||
player.getWorld().spawn(location, clazz, entity -> {
|
||||
BukkitEntity base = new BukkitEntity(entity);
|
||||
base.getBodyRotationController().setYBodyRot(location.getYaw());
|
||||
ModeledEntity modeledEntity = ModelEngineAPI.createModeledEntity(base);
|
||||
modeledEntity.setBaseEntityVisible(false);
|
||||
ActiveModel activeModel = ModelEngineAPI.createActiveModel(blueprint);
|
||||
activeModel.setAutoRendererInitialization(false);
|
||||
options.applyDisguiseOptions(activeModel);
|
||||
modeledEntity.addModel(activeModel, true).ifPresent(ActiveModel::destroy);
|
||||
activeModel.getBones().values().forEach(modelBone -> {
|
||||
modelBone.getBoneBehavior(BoneBehaviorTypes.PLAYER_LIMB).ifPresent(playerLimb -> ((PlayerLimb)playerLimb).setTexture(player));
|
||||
modelBone.getBoneBehavior(BoneBehaviorTypes.USER_LIMB).ifPresent(userLimb -> ((UserLimb)userLimb).setTexture(player));
|
||||
});
|
||||
activeModel.initializeRenderer();
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, String[] args) {
|
||||
List<String> list = new ArrayList<>();
|
||||
switch (args.length) {
|
||||
case 1:
|
||||
MECommand.getModelIdTabComplete(list, args[0]);
|
||||
break;
|
||||
case 2:
|
||||
String arg = args[1];
|
||||
|
||||
for (EntityType type : EntityType.values()) {
|
||||
String name = type.name();
|
||||
if (name.startsWith(arg.toUpperCase(Locale.ENGLISH))) {
|
||||
list.add(name);
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
list.addAll(ModelOptionParser.getTabCompletion(args.length > 1 ? 2 : 1, args));
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermissionNode() {
|
||||
return "modelengine.command.summon";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConsoleFriendly() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "summon";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.ticxo.modelengine.core.command.sub;
|
||||
|
||||
import com.ticxo.modelengine.api.command.AbstractCommand;
|
||||
import java.util.List;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
public class TestCommand extends AbstractCommand {
|
||||
public TestCommand(AbstractCommand parent) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, String[] args) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, String[] args) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermissionNode() {
|
||||
return "modelengine.command.test";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConsoleFriendly() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "test";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.ticxo.modelengine.core.command.sub;
|
||||
|
||||
import com.ticxo.modelengine.api.command.AbstractCommand;
|
||||
import com.ticxo.modelengine.api.lod.AnimationLODHandler;
|
||||
import com.ticxo.modelengine.api.utils.logger.LogColor;
|
||||
import com.ticxo.modelengine.core.command.MECommand;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
public class ToggleLODCommand extends AbstractCommand {
|
||||
public ToggleLODCommand(AbstractCommand parent) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, String[] args) {
|
||||
if (args.length >= 1) {
|
||||
AnimationLODHandler.setGlobalEnabled(Boolean.parseBoolean(args[0]));
|
||||
} else {
|
||||
MECommand.logSender(
|
||||
sender,
|
||||
ChatColor.GREEN + "[ModelEngine] Animation LOD is " + (AnimationLODHandler.isGlobalEnabled() ? "enabled." : "disabled."),
|
||||
LogColor.BRIGHT_GREEN + "Animation LOD is " + (AnimationLODHandler.isGlobalEnabled() ? "enabled." : "disabled.")
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, String[] args) {
|
||||
if (args.length != 1) {
|
||||
return null;
|
||||
} else {
|
||||
ArrayList<String> list = new ArrayList<>();
|
||||
list.add("true");
|
||||
list.add("false");
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermissionNode() {
|
||||
return "modelengine.command.toggle-lod";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConsoleFriendly() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "toggle-lod";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.ticxo.modelengine.core.command.sub;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.command.AbstractCommand;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.core.command.MECommand;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class UndisguiseCommand extends AbstractCommand {
|
||||
public UndisguiseCommand(AbstractCommand parent) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, String[] args) {
|
||||
Player player = (Player)sender;
|
||||
ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(player.getUniqueId());
|
||||
if (modeledEntity == null) {
|
||||
return true;
|
||||
} else {
|
||||
if (args.length == 0) {
|
||||
modeledEntity.setBaseEntityVisible(true);
|
||||
modeledEntity.markRemoved();
|
||||
ModelEngineAPI.getEntityHandler().setForcedInvisible(player, false);
|
||||
} else {
|
||||
for (String modelId : args) {
|
||||
modeledEntity.removeModel(modelId).ifPresent(ActiveModel::destroy);
|
||||
}
|
||||
|
||||
if (modeledEntity.getModels().isEmpty()) {
|
||||
modeledEntity.setBaseEntityVisible(true);
|
||||
modeledEntity.markRemoved();
|
||||
ModelEngineAPI.getEntityHandler().setForcedInvisible(player, false);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, String[] args) {
|
||||
List<String> list = new ArrayList<>();
|
||||
Player player = (Player)sender;
|
||||
ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(player.getUniqueId());
|
||||
if (modeledEntity == null) {
|
||||
return list;
|
||||
} else {
|
||||
if (args.length > 0) {
|
||||
String arg = args[args.length - 1];
|
||||
MECommand.getModelIdTabComplete(list, arg, modeledEntity);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermissionNode() {
|
||||
return "modelengine.command.undisguise";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConsoleFriendly() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "undisguise";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.ticxo.modelengine.core.data;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.utils.data.io.SavedData;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
import org.bukkit.Location;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class DataUpdater {
|
||||
private static final Map<String, Consumer<SavedData>> VERSION_CHAIN = new HashMap<String, Consumer<SavedData>>() {
|
||||
{
|
||||
this.put("R4.0.0", data -> {
|
||||
data.putString("version", "R4.0.3");
|
||||
List<SavedData> list = data.getList("models", SavedData.class);
|
||||
|
||||
for (SavedData modelData : list) {
|
||||
modelData.putBoolean("hitbox_visible", true);
|
||||
modelData.putBoolean("shadow_visible", true);
|
||||
modelData.putBoolean("main_hitbox", true);
|
||||
}
|
||||
|
||||
data.putList("models", list);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@Nullable
|
||||
public static SavedData convertToSavedData(@Nullable Location location, String json) {
|
||||
if (json != null && !json.isEmpty() && !json.isBlank()) {
|
||||
Gson gson = ModelEngineAPI.getAPI().getGson();
|
||||
SavedData data = (SavedData)gson.fromJson(json, SavedData.class);
|
||||
if (data == null) {
|
||||
return null;
|
||||
} else {
|
||||
if (data.getString("version") == null) {
|
||||
V3Data oldData = (V3Data)gson.fromJson(json, V3Data.class);
|
||||
data = oldData.convert(location);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean tryUpdate(@Nullable SavedData data) {
|
||||
if (data == null) {
|
||||
return false;
|
||||
} else if (data.getString("version") == null) {
|
||||
return false;
|
||||
} else {
|
||||
while (true) {
|
||||
Consumer<SavedData> updater = VERSION_CHAIN.get(data.getString("version"));
|
||||
if (updater == null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
updater.accept(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,752 @@
|
||||
package com.ticxo.modelengine.core.data;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.animation.BlueprintAnimation;
|
||||
import com.ticxo.modelengine.api.animation.ModelState;
|
||||
import com.ticxo.modelengine.api.animation.handler.AnimationHandler;
|
||||
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
|
||||
import com.ticxo.modelengine.api.animation.property.SimpleProperty;
|
||||
import com.ticxo.modelengine.api.entity.BaseEntity;
|
||||
import com.ticxo.modelengine.api.entity.Dummy;
|
||||
import com.ticxo.modelengine.api.entity.Hitbox;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.MountData;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.MountManager;
|
||||
import com.ticxo.modelengine.api.nms.impl.DefaultBodyRotationController;
|
||||
import com.ticxo.modelengine.api.utils.data.io.SavedData;
|
||||
import com.ticxo.modelengine.core.model.ModeledEntityImpl;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
import org.bukkit.Location;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class V3Data {
|
||||
private int renderDistance;
|
||||
private boolean isHeadClampUneven;
|
||||
private boolean isBodyClampUneven;
|
||||
private float maxHeadAngle;
|
||||
private float maxBodyAngle;
|
||||
private float minHeadAngle;
|
||||
private float minBodyAngle;
|
||||
private boolean playerMode;
|
||||
private float stableAngle;
|
||||
private int rotationDelay;
|
||||
private int rotationDuration;
|
||||
private boolean canSteer;
|
||||
private boolean canRide;
|
||||
private String mountModelId;
|
||||
private String mountDriverBone;
|
||||
private boolean isBaseEntityVisible;
|
||||
private boolean modelRotationLock;
|
||||
private Double stepHeight;
|
||||
private Hitbox hitbox;
|
||||
private final Map<String, V3Data.ModelData> models = Maps.newConcurrentMap();
|
||||
|
||||
public SavedData convert(@Nullable Location location) {
|
||||
Dummy<Object> dummy = new Dummy<>();
|
||||
dummy.setRenderRadius(this.renderDistance);
|
||||
dummy.setLocation(location);
|
||||
if (this.stepHeight != null) {
|
||||
dummy.setMaxStepHeight(this.stepHeight);
|
||||
}
|
||||
|
||||
DefaultBodyRotationController bodyController = dummy.getBodyRotationController();
|
||||
bodyController.setHeadClampUneven(this.isHeadClampUneven);
|
||||
bodyController.setBodyClampUneven(this.isBodyClampUneven);
|
||||
bodyController.setMaxHeadAngle(this.maxHeadAngle);
|
||||
bodyController.setMaxBodyAngle(this.maxBodyAngle);
|
||||
bodyController.setMinHeadAngle(this.minHeadAngle);
|
||||
bodyController.setMinBodyAngle(this.minBodyAngle);
|
||||
bodyController.setPlayerMode(this.playerMode);
|
||||
bodyController.setStableAngle(this.stableAngle);
|
||||
bodyController.setRotationDelay(this.rotationDelay);
|
||||
bodyController.setRotationDuration(this.rotationDuration);
|
||||
var modeledEntity = new ModeledEntityImpl(dummy, null) {
|
||||
@Override
|
||||
public void registerSelf() {
|
||||
}
|
||||
};
|
||||
modeledEntity.setBaseEntityVisible(this.isBaseEntityVisible);
|
||||
modeledEntity.setModelRotationLocked(this.modelRotationLock);
|
||||
this.models
|
||||
.forEach(
|
||||
(modelId, modelData) -> {
|
||||
ActiveModel activeModel = ModelEngineAPI.createActiveModel(modelId);
|
||||
if (activeModel != null) {
|
||||
activeModel.setCanHurt(modelData.canHurt);
|
||||
activeModel.setLockPitch(modelData.lockPitch);
|
||||
activeModel.setLockYaw(modelData.lockYaw);
|
||||
modelData.defaultStates
|
||||
.forEach(
|
||||
(modelState, property) -> activeModel.getAnimationHandler()
|
||||
.setDefaultProperty(
|
||||
new AnimationHandler.DefaultProperty(modelState, property.stateId, property.lerpIn, property.lerpOut, property.speed)
|
||||
)
|
||||
);
|
||||
ModelBlueprint blueprint = activeModel.getBlueprint();
|
||||
modelData.states.forEach((state, stateData) -> {
|
||||
BlueprintAnimation animation = blueprint.getAnimations().get(state);
|
||||
if (animation != null) {
|
||||
SimpleProperty property = new SimpleProperty(activeModel, animation, stateData.lerpIn, stateData.lerpOut, stateData.speed);
|
||||
property.setPhase(stateData.phase);
|
||||
property.setForceLoopMode(stateData.forceLoopMode);
|
||||
property.setForceOverride(stateData.forceOverride ? BlueprintAnimation.OverrideMode.OVERRIDE : null);
|
||||
activeModel.getAnimationHandler().playAnimation(property, true);
|
||||
}
|
||||
});
|
||||
modeledEntity.addModel(activeModel, false).ifPresent(ActiveModel::destroy);
|
||||
}
|
||||
}
|
||||
);
|
||||
if (modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData) {
|
||||
BehaviorManager manager = mountData.getMainMountManager();
|
||||
if (manager != null) {
|
||||
((MountManager)manager).setCanDrive(this.canSteer);
|
||||
((MountManager)manager).setCanRide(this.canRide);
|
||||
}
|
||||
}
|
||||
|
||||
SavedData data = modeledEntity.save().orElse(null);
|
||||
modeledEntity.destroy();
|
||||
return data;
|
||||
}
|
||||
|
||||
public int getRenderDistance() {
|
||||
return this.renderDistance;
|
||||
}
|
||||
|
||||
public boolean isHeadClampUneven() {
|
||||
return this.isHeadClampUneven;
|
||||
}
|
||||
|
||||
public boolean isBodyClampUneven() {
|
||||
return this.isBodyClampUneven;
|
||||
}
|
||||
|
||||
public float getMaxHeadAngle() {
|
||||
return this.maxHeadAngle;
|
||||
}
|
||||
|
||||
public float getMaxBodyAngle() {
|
||||
return this.maxBodyAngle;
|
||||
}
|
||||
|
||||
public float getMinHeadAngle() {
|
||||
return this.minHeadAngle;
|
||||
}
|
||||
|
||||
public float getMinBodyAngle() {
|
||||
return this.minBodyAngle;
|
||||
}
|
||||
|
||||
public boolean isPlayerMode() {
|
||||
return this.playerMode;
|
||||
}
|
||||
|
||||
public float getStableAngle() {
|
||||
return this.stableAngle;
|
||||
}
|
||||
|
||||
public int getRotationDelay() {
|
||||
return this.rotationDelay;
|
||||
}
|
||||
|
||||
public int getRotationDuration() {
|
||||
return this.rotationDuration;
|
||||
}
|
||||
|
||||
public boolean isCanSteer() {
|
||||
return this.canSteer;
|
||||
}
|
||||
|
||||
public boolean isCanRide() {
|
||||
return this.canRide;
|
||||
}
|
||||
|
||||
public String getMountModelId() {
|
||||
return this.mountModelId;
|
||||
}
|
||||
|
||||
public String getMountDriverBone() {
|
||||
return this.mountDriverBone;
|
||||
}
|
||||
|
||||
public boolean isBaseEntityVisible() {
|
||||
return this.isBaseEntityVisible;
|
||||
}
|
||||
|
||||
public boolean isModelRotationLock() {
|
||||
return this.modelRotationLock;
|
||||
}
|
||||
|
||||
public Double getStepHeight() {
|
||||
return this.stepHeight;
|
||||
}
|
||||
|
||||
public Hitbox getHitbox() {
|
||||
return this.hitbox;
|
||||
}
|
||||
|
||||
public Map<String, V3Data.ModelData> getModels() {
|
||||
return this.models;
|
||||
}
|
||||
|
||||
public void setRenderDistance(int renderDistance) {
|
||||
this.renderDistance = renderDistance;
|
||||
}
|
||||
|
||||
public void setHeadClampUneven(boolean isHeadClampUneven) {
|
||||
this.isHeadClampUneven = isHeadClampUneven;
|
||||
}
|
||||
|
||||
public void setBodyClampUneven(boolean isBodyClampUneven) {
|
||||
this.isBodyClampUneven = isBodyClampUneven;
|
||||
}
|
||||
|
||||
public void setMaxHeadAngle(float maxHeadAngle) {
|
||||
this.maxHeadAngle = maxHeadAngle;
|
||||
}
|
||||
|
||||
public void setMaxBodyAngle(float maxBodyAngle) {
|
||||
this.maxBodyAngle = maxBodyAngle;
|
||||
}
|
||||
|
||||
public void setMinHeadAngle(float minHeadAngle) {
|
||||
this.minHeadAngle = minHeadAngle;
|
||||
}
|
||||
|
||||
public void setMinBodyAngle(float minBodyAngle) {
|
||||
this.minBodyAngle = minBodyAngle;
|
||||
}
|
||||
|
||||
public void setPlayerMode(boolean playerMode) {
|
||||
this.playerMode = playerMode;
|
||||
}
|
||||
|
||||
public void setStableAngle(float stableAngle) {
|
||||
this.stableAngle = stableAngle;
|
||||
}
|
||||
|
||||
public void setRotationDelay(int rotationDelay) {
|
||||
this.rotationDelay = rotationDelay;
|
||||
}
|
||||
|
||||
public void setRotationDuration(int rotationDuration) {
|
||||
this.rotationDuration = rotationDuration;
|
||||
}
|
||||
|
||||
public void setCanSteer(boolean canSteer) {
|
||||
this.canSteer = canSteer;
|
||||
}
|
||||
|
||||
public void setCanRide(boolean canRide) {
|
||||
this.canRide = canRide;
|
||||
}
|
||||
|
||||
public void setMountModelId(String mountModelId) {
|
||||
this.mountModelId = mountModelId;
|
||||
}
|
||||
|
||||
public void setMountDriverBone(String mountDriverBone) {
|
||||
this.mountDriverBone = mountDriverBone;
|
||||
}
|
||||
|
||||
public void setBaseEntityVisible(boolean isBaseEntityVisible) {
|
||||
this.isBaseEntityVisible = isBaseEntityVisible;
|
||||
}
|
||||
|
||||
public void setModelRotationLock(boolean modelRotationLock) {
|
||||
this.modelRotationLock = modelRotationLock;
|
||||
}
|
||||
|
||||
public void setStepHeight(Double stepHeight) {
|
||||
this.stepHeight = stepHeight;
|
||||
}
|
||||
|
||||
public void setHitbox(Hitbox hitbox) {
|
||||
this.hitbox = hitbox;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o == this) {
|
||||
return true;
|
||||
} else if (!(o instanceof V3Data other)) {
|
||||
return false;
|
||||
} else if (!other.canEqual(this)) {
|
||||
return false;
|
||||
} else if (this.getRenderDistance() != other.getRenderDistance()) {
|
||||
return false;
|
||||
} else if (this.isHeadClampUneven() != other.isHeadClampUneven()) {
|
||||
return false;
|
||||
} else if (this.isBodyClampUneven() != other.isBodyClampUneven()) {
|
||||
return false;
|
||||
} else if (Float.compare(this.getMaxHeadAngle(), other.getMaxHeadAngle()) != 0) {
|
||||
return false;
|
||||
} else if (Float.compare(this.getMaxBodyAngle(), other.getMaxBodyAngle()) != 0) {
|
||||
return false;
|
||||
} else if (Float.compare(this.getMinHeadAngle(), other.getMinHeadAngle()) != 0) {
|
||||
return false;
|
||||
} else if (Float.compare(this.getMinBodyAngle(), other.getMinBodyAngle()) != 0) {
|
||||
return false;
|
||||
} else if (this.isPlayerMode() != other.isPlayerMode()) {
|
||||
return false;
|
||||
} else if (Float.compare(this.getStableAngle(), other.getStableAngle()) != 0) {
|
||||
return false;
|
||||
} else if (this.getRotationDelay() != other.getRotationDelay()) {
|
||||
return false;
|
||||
} else if (this.getRotationDuration() != other.getRotationDuration()) {
|
||||
return false;
|
||||
} else if (this.isCanSteer() != other.isCanSteer()) {
|
||||
return false;
|
||||
} else if (this.isCanRide() != other.isCanRide()) {
|
||||
return false;
|
||||
} else if (this.isBaseEntityVisible() != other.isBaseEntityVisible()) {
|
||||
return false;
|
||||
} else if (this.isModelRotationLock() != other.isModelRotationLock()) {
|
||||
return false;
|
||||
} else {
|
||||
Object this$stepHeight = this.getStepHeight();
|
||||
Object other$stepHeight = other.getStepHeight();
|
||||
if (this$stepHeight == null ? other$stepHeight == null : this$stepHeight.equals(other$stepHeight)) {
|
||||
Object this$mountModelId = this.getMountModelId();
|
||||
Object other$mountModelId = other.getMountModelId();
|
||||
if (this$mountModelId == null ? other$mountModelId == null : this$mountModelId.equals(other$mountModelId)) {
|
||||
Object this$mountDriverBone = this.getMountDriverBone();
|
||||
Object other$mountDriverBone = other.getMountDriverBone();
|
||||
if (this$mountDriverBone == null ? other$mountDriverBone == null : this$mountDriverBone.equals(other$mountDriverBone)) {
|
||||
Object this$hitbox = this.getHitbox();
|
||||
Object other$hitbox = other.getHitbox();
|
||||
if (this$hitbox == null ? other$hitbox == null : this$hitbox.equals(other$hitbox)) {
|
||||
Object this$models = this.getModels();
|
||||
Object other$models = other.getModels();
|
||||
return this$models == null ? other$models == null : this$models.equals(other$models);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected boolean canEqual(Object other) {
|
||||
return other instanceof V3Data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int PRIME = 59;
|
||||
int result = 1;
|
||||
result = result * 59 + this.getRenderDistance();
|
||||
result = result * 59 + (this.isHeadClampUneven() ? 79 : 97);
|
||||
result = result * 59 + (this.isBodyClampUneven() ? 79 : 97);
|
||||
result = result * 59 + Float.floatToIntBits(this.getMaxHeadAngle());
|
||||
result = result * 59 + Float.floatToIntBits(this.getMaxBodyAngle());
|
||||
result = result * 59 + Float.floatToIntBits(this.getMinHeadAngle());
|
||||
result = result * 59 + Float.floatToIntBits(this.getMinBodyAngle());
|
||||
result = result * 59 + (this.isPlayerMode() ? 79 : 97);
|
||||
result = result * 59 + Float.floatToIntBits(this.getStableAngle());
|
||||
result = result * 59 + this.getRotationDelay();
|
||||
result = result * 59 + this.getRotationDuration();
|
||||
result = result * 59 + (this.isCanSteer() ? 79 : 97);
|
||||
result = result * 59 + (this.isCanRide() ? 79 : 97);
|
||||
result = result * 59 + (this.isBaseEntityVisible() ? 79 : 97);
|
||||
result = result * 59 + (this.isModelRotationLock() ? 79 : 97);
|
||||
Object $stepHeight = this.getStepHeight();
|
||||
result = result * 59 + ($stepHeight == null ? 43 : $stepHeight.hashCode());
|
||||
Object $mountModelId = this.getMountModelId();
|
||||
result = result * 59 + ($mountModelId == null ? 43 : $mountModelId.hashCode());
|
||||
Object $mountDriverBone = this.getMountDriverBone();
|
||||
result = result * 59 + ($mountDriverBone == null ? 43 : $mountDriverBone.hashCode());
|
||||
Object $hitbox = this.getHitbox();
|
||||
result = result * 59 + ($hitbox == null ? 43 : $hitbox.hashCode());
|
||||
Object $models = this.getModels();
|
||||
return result * 59 + ($models == null ? 43 : $models.hashCode());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "V3Data(renderDistance="
|
||||
+ this.getRenderDistance()
|
||||
+ ", isHeadClampUneven="
|
||||
+ this.isHeadClampUneven()
|
||||
+ ", isBodyClampUneven="
|
||||
+ this.isBodyClampUneven()
|
||||
+ ", maxHeadAngle="
|
||||
+ this.getMaxHeadAngle()
|
||||
+ ", maxBodyAngle="
|
||||
+ this.getMaxBodyAngle()
|
||||
+ ", minHeadAngle="
|
||||
+ this.getMinHeadAngle()
|
||||
+ ", minBodyAngle="
|
||||
+ this.getMinBodyAngle()
|
||||
+ ", playerMode="
|
||||
+ this.isPlayerMode()
|
||||
+ ", stableAngle="
|
||||
+ this.getStableAngle()
|
||||
+ ", rotationDelay="
|
||||
+ this.getRotationDelay()
|
||||
+ ", rotationDuration="
|
||||
+ this.getRotationDuration()
|
||||
+ ", canSteer="
|
||||
+ this.isCanSteer()
|
||||
+ ", canRide="
|
||||
+ this.isCanRide()
|
||||
+ ", mountModelId="
|
||||
+ this.getMountModelId()
|
||||
+ ", mountDriverBone="
|
||||
+ this.getMountDriverBone()
|
||||
+ ", isBaseEntityVisible="
|
||||
+ this.isBaseEntityVisible()
|
||||
+ ", modelRotationLock="
|
||||
+ this.isModelRotationLock()
|
||||
+ ", stepHeight="
|
||||
+ this.getStepHeight()
|
||||
+ ", hitbox="
|
||||
+ this.getHitbox()
|
||||
+ ", models="
|
||||
+ this.getModels()
|
||||
+ ")";
|
||||
}
|
||||
|
||||
public static class ModelData {
|
||||
private final Map<String, V3Data.StateData> states = Maps.newConcurrentMap();
|
||||
private final Map<ModelState, V3Data.StateProperty> defaultStates = Maps.newConcurrentMap();
|
||||
private boolean canHurt;
|
||||
private boolean lockPitch;
|
||||
private boolean lockYaw;
|
||||
|
||||
public Map<String, V3Data.StateData> getStates() {
|
||||
return this.states;
|
||||
}
|
||||
|
||||
public Map<ModelState, V3Data.StateProperty> getDefaultStates() {
|
||||
return this.defaultStates;
|
||||
}
|
||||
|
||||
public boolean isCanHurt() {
|
||||
return this.canHurt;
|
||||
}
|
||||
|
||||
public boolean isLockPitch() {
|
||||
return this.lockPitch;
|
||||
}
|
||||
|
||||
public boolean isLockYaw() {
|
||||
return this.lockYaw;
|
||||
}
|
||||
|
||||
public void setCanHurt(boolean canHurt) {
|
||||
this.canHurt = canHurt;
|
||||
}
|
||||
|
||||
public void setLockPitch(boolean lockPitch) {
|
||||
this.lockPitch = lockPitch;
|
||||
}
|
||||
|
||||
public void setLockYaw(boolean lockYaw) {
|
||||
this.lockYaw = lockYaw;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o == this) {
|
||||
return true;
|
||||
} else if (!(o instanceof V3Data.ModelData other)) {
|
||||
return false;
|
||||
} else if (!other.canEqual(this)) {
|
||||
return false;
|
||||
} else if (this.isCanHurt() != other.isCanHurt()) {
|
||||
return false;
|
||||
} else if (this.isLockPitch() != other.isLockPitch()) {
|
||||
return false;
|
||||
} else if (this.isLockYaw() != other.isLockYaw()) {
|
||||
return false;
|
||||
} else {
|
||||
Object this$states = this.getStates();
|
||||
Object other$states = other.getStates();
|
||||
if (this$states == null ? other$states == null : this$states.equals(other$states)) {
|
||||
Object this$defaultStates = this.getDefaultStates();
|
||||
Object other$defaultStates = other.getDefaultStates();
|
||||
return this$defaultStates == null ? other$defaultStates == null : this$defaultStates.equals(other$defaultStates);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected boolean canEqual(Object other) {
|
||||
return other instanceof V3Data.ModelData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int PRIME = 59;
|
||||
int result = 1;
|
||||
result = result * 59 + (this.isCanHurt() ? 79 : 97);
|
||||
result = result * 59 + (this.isLockPitch() ? 79 : 97);
|
||||
result = result * 59 + (this.isLockYaw() ? 79 : 97);
|
||||
Object $states = this.getStates();
|
||||
result = result * 59 + ($states == null ? 43 : $states.hashCode());
|
||||
Object $defaultStates = this.getDefaultStates();
|
||||
return result * 59 + ($defaultStates == null ? 43 : $defaultStates.hashCode());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "V3Data.ModelData(states="
|
||||
+ this.getStates()
|
||||
+ ", defaultStates="
|
||||
+ this.getDefaultStates()
|
||||
+ ", canHurt="
|
||||
+ this.isCanHurt()
|
||||
+ ", lockPitch="
|
||||
+ this.isLockPitch()
|
||||
+ ", lockYaw="
|
||||
+ this.isLockYaw()
|
||||
+ ")";
|
||||
}
|
||||
}
|
||||
|
||||
public static class StateData {
|
||||
private double lerpIn;
|
||||
private double lerpOut;
|
||||
private double time;
|
||||
private double speed;
|
||||
private IAnimationProperty.Phase phase;
|
||||
private BlueprintAnimation.LoopMode forceLoopMode;
|
||||
private boolean forceOverride;
|
||||
|
||||
public double getLerpIn() {
|
||||
return this.lerpIn;
|
||||
}
|
||||
|
||||
public double getLerpOut() {
|
||||
return this.lerpOut;
|
||||
}
|
||||
|
||||
public double getTime() {
|
||||
return this.time;
|
||||
}
|
||||
|
||||
public double getSpeed() {
|
||||
return this.speed;
|
||||
}
|
||||
|
||||
public IAnimationProperty.Phase getPhase() {
|
||||
return this.phase;
|
||||
}
|
||||
|
||||
public BlueprintAnimation.LoopMode getForceLoopMode() {
|
||||
return this.forceLoopMode;
|
||||
}
|
||||
|
||||
public boolean isForceOverride() {
|
||||
return this.forceOverride;
|
||||
}
|
||||
|
||||
public void setLerpIn(double lerpIn) {
|
||||
this.lerpIn = lerpIn;
|
||||
}
|
||||
|
||||
public void setLerpOut(double lerpOut) {
|
||||
this.lerpOut = lerpOut;
|
||||
}
|
||||
|
||||
public void setTime(double time) {
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
public void setSpeed(double speed) {
|
||||
this.speed = speed;
|
||||
}
|
||||
|
||||
public void setPhase(IAnimationProperty.Phase phase) {
|
||||
this.phase = phase;
|
||||
}
|
||||
|
||||
public void setForceLoopMode(BlueprintAnimation.LoopMode forceLoopMode) {
|
||||
this.forceLoopMode = forceLoopMode;
|
||||
}
|
||||
|
||||
public void setForceOverride(boolean forceOverride) {
|
||||
this.forceOverride = forceOverride;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o == this) {
|
||||
return true;
|
||||
} else if (!(o instanceof V3Data.StateData other)) {
|
||||
return false;
|
||||
} else if (!other.canEqual(this)) {
|
||||
return false;
|
||||
} else if (Double.compare(this.getLerpIn(), other.getLerpIn()) != 0) {
|
||||
return false;
|
||||
} else if (Double.compare(this.getLerpOut(), other.getLerpOut()) != 0) {
|
||||
return false;
|
||||
} else if (Double.compare(this.getTime(), other.getTime()) != 0) {
|
||||
return false;
|
||||
} else if (Double.compare(this.getSpeed(), other.getSpeed()) != 0) {
|
||||
return false;
|
||||
} else if (this.isForceOverride() != other.isForceOverride()) {
|
||||
return false;
|
||||
} else {
|
||||
Object this$phase = this.getPhase();
|
||||
Object other$phase = other.getPhase();
|
||||
if (this$phase == null ? other$phase == null : this$phase.equals(other$phase)) {
|
||||
Object this$forceLoopMode = this.getForceLoopMode();
|
||||
Object other$forceLoopMode = other.getForceLoopMode();
|
||||
return this$forceLoopMode == null ? other$forceLoopMode == null : this$forceLoopMode.equals(other$forceLoopMode);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected boolean canEqual(Object other) {
|
||||
return other instanceof V3Data.StateData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int PRIME = 59;
|
||||
int result = 1;
|
||||
long $lerpIn = Double.doubleToLongBits(this.getLerpIn());
|
||||
result = result * 59 + (int)($lerpIn >>> 32 ^ $lerpIn);
|
||||
long $lerpOut = Double.doubleToLongBits(this.getLerpOut());
|
||||
result = result * 59 + (int)($lerpOut >>> 32 ^ $lerpOut);
|
||||
long $time = Double.doubleToLongBits(this.getTime());
|
||||
result = result * 59 + (int)($time >>> 32 ^ $time);
|
||||
long $speed = Double.doubleToLongBits(this.getSpeed());
|
||||
result = result * 59 + (int)($speed >>> 32 ^ $speed);
|
||||
result = result * 59 + (this.isForceOverride() ? 79 : 97);
|
||||
Object $phase = this.getPhase();
|
||||
result = result * 59 + ($phase == null ? 43 : $phase.hashCode());
|
||||
Object $forceLoopMode = this.getForceLoopMode();
|
||||
return result * 59 + ($forceLoopMode == null ? 43 : $forceLoopMode.hashCode());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "V3Data.StateData(lerpIn="
|
||||
+ this.getLerpIn()
|
||||
+ ", lerpOut="
|
||||
+ this.getLerpOut()
|
||||
+ ", time="
|
||||
+ this.getTime()
|
||||
+ ", speed="
|
||||
+ this.getSpeed()
|
||||
+ ", phase="
|
||||
+ this.getPhase()
|
||||
+ ", forceLoopMode="
|
||||
+ this.getForceLoopMode()
|
||||
+ ", forceOverride="
|
||||
+ this.isForceOverride()
|
||||
+ ")";
|
||||
}
|
||||
}
|
||||
|
||||
public static class StateProperty {
|
||||
private String stateId;
|
||||
private double lerpIn;
|
||||
private double lerpOut;
|
||||
private double speed;
|
||||
|
||||
public String getStateId() {
|
||||
return this.stateId;
|
||||
}
|
||||
|
||||
public double getLerpIn() {
|
||||
return this.lerpIn;
|
||||
}
|
||||
|
||||
public double getLerpOut() {
|
||||
return this.lerpOut;
|
||||
}
|
||||
|
||||
public double getSpeed() {
|
||||
return this.speed;
|
||||
}
|
||||
|
||||
public void setStateId(String stateId) {
|
||||
this.stateId = stateId;
|
||||
}
|
||||
|
||||
public void setLerpIn(double lerpIn) {
|
||||
this.lerpIn = lerpIn;
|
||||
}
|
||||
|
||||
public void setLerpOut(double lerpOut) {
|
||||
this.lerpOut = lerpOut;
|
||||
}
|
||||
|
||||
public void setSpeed(double speed) {
|
||||
this.speed = speed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o == this) {
|
||||
return true;
|
||||
} else if (!(o instanceof V3Data.StateProperty other)) {
|
||||
return false;
|
||||
} else if (!other.canEqual(this)) {
|
||||
return false;
|
||||
} else if (Double.compare(this.getLerpIn(), other.getLerpIn()) != 0) {
|
||||
return false;
|
||||
} else if (Double.compare(this.getLerpOut(), other.getLerpOut()) != 0) {
|
||||
return false;
|
||||
} else if (Double.compare(this.getSpeed(), other.getSpeed()) != 0) {
|
||||
return false;
|
||||
} else {
|
||||
Object this$stateId = this.getStateId();
|
||||
Object other$stateId = other.getStateId();
|
||||
return this$stateId == null ? other$stateId == null : this$stateId.equals(other$stateId);
|
||||
}
|
||||
}
|
||||
|
||||
protected boolean canEqual(Object other) {
|
||||
return other instanceof V3Data.StateProperty;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int PRIME = 59;
|
||||
int result = 1;
|
||||
long $lerpIn = Double.doubleToLongBits(this.getLerpIn());
|
||||
result = result * 59 + (int)($lerpIn >>> 32 ^ $lerpIn);
|
||||
long $lerpOut = Double.doubleToLongBits(this.getLerpOut());
|
||||
result = result * 59 + (int)($lerpOut >>> 32 ^ $lerpOut);
|
||||
long $speed = Double.doubleToLongBits(this.getSpeed());
|
||||
result = result * 59 + (int)($speed >>> 32 ^ $speed);
|
||||
Object $stateId = this.getStateId();
|
||||
return result * 59 + ($stateId == null ? 43 : $stateId.hashCode());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "V3Data.StateProperty(stateId="
|
||||
+ this.getStateId()
|
||||
+ ", lerpIn="
|
||||
+ this.getLerpIn()
|
||||
+ ", lerpOut="
|
||||
+ this.getLerpOut()
|
||||
+ ", speed="
|
||||
+ this.getSpeed()
|
||||
+ ")";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
package com.ticxo.modelengine.core.generator;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.generator.BaseItemEnum;
|
||||
import com.ticxo.modelengine.api.generator.assets.ItemModel;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone;
|
||||
import com.ticxo.modelengine.api.utils.TFile;
|
||||
import com.ticxo.modelengine.api.utils.config.ConfigProperty;
|
||||
import com.ticxo.modelengine.api.utils.data.GSONUtils;
|
||||
import com.ticxo.modelengine.api.utils.logger.LogColor;
|
||||
import com.ticxo.modelengine.api.utils.logger.TLogger;
|
||||
import com.ticxo.modelengine.core.generator.java.BaseItem;
|
||||
import com.ticxo.modelengine.core.generator.java.BaseItemTransformer;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
public class BaseItemManager {
|
||||
private final ModelEngineAPI plugin;
|
||||
private final Gson gson;
|
||||
private final Map<BaseItemEnum, BaseItemManager.BaseItemCache> baseItems = new HashMap<>();
|
||||
private final Map<String, BlueprintBone> requested = new LinkedHashMap<>();
|
||||
private final File baseItemFolder;
|
||||
private final File itemModelFolder;
|
||||
private final File cachedIDJson;
|
||||
|
||||
public BaseItemManager(ModelGeneratorImpl generator) {
|
||||
this.plugin = generator.getPlugin();
|
||||
this.gson = generator.getGson();
|
||||
this.baseItemFolder = TFile.createDirectory(generator.getAssetsFolder(), "minecraft", "models", "item");
|
||||
this.itemModelFolder = TFile.createDirectory(generator.getAssetsFolder(), "minecraft", "items");
|
||||
this.cachedIDJson = TFile.createFileOrEmpty(this.plugin.getDataFolder(), ".data", "cache.json");
|
||||
}
|
||||
|
||||
public void updateModels() {
|
||||
Set<BaseItemEnum> items = ConfigProperty.ITEM_MODELS.getBaseItems();
|
||||
if (items.isEmpty()) {
|
||||
items.add(ConfigProperty.ITEM_MODEL.getBaseItem());
|
||||
}
|
||||
|
||||
HashMap<BaseItemEnum, BaseItemManager.BaseItemCache> prevItems = new HashMap<>(this.baseItems);
|
||||
this.baseItems.clear();
|
||||
|
||||
for (BaseItemEnum base : items) {
|
||||
String name = base.name().toLowerCase(Locale.ENGLISH);
|
||||
InputStream inputStream = this.plugin.getResource("pack/colorable/" + name + ".json");
|
||||
if (inputStream == null) {
|
||||
TLogger.warn("Unknown colorable item: " + name + ".");
|
||||
} else {
|
||||
InputStreamReader itemTemplateReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
|
||||
BaseItem baseItem = (BaseItem)this.gson.fromJson(itemTemplateReader, BaseItem.class);
|
||||
baseItem.setName(name);
|
||||
baseItem.setBaseItemEnum(base);
|
||||
this.baseItems
|
||||
.computeIfAbsent(
|
||||
base,
|
||||
baseItemEnum -> {
|
||||
BaseItemManager.BaseItemCache baseItemCache = prevItems.get(baseItemEnum);
|
||||
return baseItemCache == null
|
||||
? new BaseItemManager.BaseItemCache(baseItemEnum, baseItem, new ModelIdCache())
|
||||
: baseItemCache.setBaseItem(baseItem);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void requestId(BlueprintBone bone, Set<String> ids) {
|
||||
for (String id : ids) {
|
||||
this.requested.put(id, bone);
|
||||
}
|
||||
}
|
||||
|
||||
public void endSession() {
|
||||
ModelCacheGroup group = new ModelCacheGroup();
|
||||
|
||||
for (Entry<BaseItemEnum, BaseItemManager.BaseItemCache> entry : this.baseItems.entrySet()) {
|
||||
ModelIdCache cache = entry.getValue().getCache();
|
||||
cache.gatherExistingIds(entry.getKey(), this.requested);
|
||||
group.cache.put(entry.getKey().name(), cache);
|
||||
}
|
||||
|
||||
for (Entry<String, BlueprintBone> entry : this.requested.entrySet()) {
|
||||
BaseItemManager.BaseItemCache cache = this.pollOptimalCache();
|
||||
cache.getCache().generateNewIds(cache.getBaseItemEnum(), entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
for (Entry<BaseItemEnum, BaseItemManager.BaseItemCache> entry : this.baseItems.entrySet()) {
|
||||
ModelIdCache cache = entry.getValue().getCache();
|
||||
cache.endSession();
|
||||
}
|
||||
|
||||
try (FileWriter writer = new FileWriter(this.cachedIDJson)) {
|
||||
writer.write(this.gson.toJson(group));
|
||||
} catch (IOException var7) {
|
||||
var7.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void clearOverrides() {
|
||||
this.baseItems.values().forEach(BaseItemManager.BaseItemCache::clearOverrides);
|
||||
}
|
||||
|
||||
public void registerModels(String namespace, Map<String, String> aliases) {
|
||||
for (Entry<BaseItemEnum, BaseItemManager.BaseItemCache> entry : this.baseItems.entrySet()) {
|
||||
BaseItem baseItem = entry.getValue().getBaseItem();
|
||||
baseItem.addModels(namespace, entry.getValue().getCache(), aliases);
|
||||
}
|
||||
}
|
||||
|
||||
public void createModelFiles() {
|
||||
this.baseItems.values().forEach(baseItemCache -> {
|
||||
BaseItem baseItem = baseItemCache.getBaseItem();
|
||||
File baseItemFile = TFile.createFile(this.baseItemFolder, baseItem.getName() + ".json");
|
||||
|
||||
try (FileWriter writer = new FileWriter(baseItemFile)) {
|
||||
writer.write(this.gson.toJson(baseItem));
|
||||
} catch (IOException var14) {
|
||||
var14.printStackTrace();
|
||||
}
|
||||
|
||||
ItemModel ver1214 = BaseItemTransformer.to1214Format(baseItem);
|
||||
File ver1214File = TFile.createFile(this.itemModelFolder, baseItem.getName() + ".json");
|
||||
|
||||
try (FileWriter writer = new FileWriter(ver1214File)) {
|
||||
writer.write(this.gson.toJson(BaseItemTransformer.wrapModel(this.gson, ver1214, true)));
|
||||
} catch (IOException var11) {
|
||||
var11.printStackTrace();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void refreshCache() {
|
||||
TFile.recreateFile(this.cachedIDJson);
|
||||
|
||||
try (FileReader reader = new FileReader(this.cachedIDJson)) {
|
||||
ModelCacheGroup cacheGroup = null;
|
||||
JsonObject generic = (JsonObject)this.gson.fromJson(reader, JsonObject.class);
|
||||
if (generic != null) {
|
||||
String version = GSONUtils.get(generic, "version", JsonElement::getAsString, "R4.0.0");
|
||||
if (!generic.has("version") && !generic.has("cachedId")) {
|
||||
version = "B4.0.8";
|
||||
}
|
||||
|
||||
TLogger.log(LogColor.BRIGHT_GREEN + "Loading cache version: " + version);
|
||||
switch (version) {
|
||||
case "R4.0.0":
|
||||
BaseItemEnum item = ConfigProperty.ITEM_MODEL.getBaseItem();
|
||||
ModelIdCache cache = (ModelIdCache)this.gson.fromJson(generic, ModelIdCache.class);
|
||||
cacheGroup = new ModelCacheGroup();
|
||||
cacheGroup.cache.put(item.name(), cache);
|
||||
break;
|
||||
case "B4.0.8":
|
||||
JsonObject root = new JsonObject();
|
||||
root.addProperty("version", "R4.0.8");
|
||||
root.add("cache", generic);
|
||||
cacheGroup = (ModelCacheGroup)this.gson.fromJson(root, ModelCacheGroup.class);
|
||||
break;
|
||||
case "R4.0.8":
|
||||
cacheGroup = (ModelCacheGroup)this.gson.fromJson(generic, ModelCacheGroup.class);
|
||||
}
|
||||
}
|
||||
|
||||
if (cacheGroup == null) {
|
||||
TLogger.warn("Unable to read the model ID cache file. If the file is missing, ignore this warning.");
|
||||
cacheGroup = new ModelCacheGroup();
|
||||
|
||||
for (BaseItemEnum baseItem : ConfigProperty.ITEM_MODELS.getBaseItems()) {
|
||||
cacheGroup.cache.put(baseItem.name(), new ModelIdCache());
|
||||
}
|
||||
}
|
||||
|
||||
Set<BaseItemEnum> items = ConfigProperty.ITEM_MODELS.getBaseItems();
|
||||
if (items.isEmpty()) {
|
||||
items.add(ConfigProperty.ITEM_MODEL.getBaseItem());
|
||||
}
|
||||
|
||||
for (Entry<String, ModelIdCache> entry : cacheGroup.cache.entrySet()) {
|
||||
BaseItemEnum item = BaseItemEnum.get(entry.getKey());
|
||||
if (item != null && items.contains(item)) {
|
||||
this.baseItems
|
||||
.compute(
|
||||
item,
|
||||
(baseItemEnum, baseItemCache) -> baseItemCache == null
|
||||
? new BaseItemManager.BaseItemCache(baseItemEnum, new BaseItem(), entry.getValue())
|
||||
: baseItemCache.setCache(entry.getValue())
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (IOException var11) {
|
||||
TLogger.error("Unable to read the model ID cache file. Is it corrupted?");
|
||||
var11.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void cleanUp() {
|
||||
this.baseItems.values().forEach(baseItemCache -> baseItemCache.getCache().cleanUp());
|
||||
}
|
||||
|
||||
private BaseItemManager.BaseItemCache pollOptimalCache() {
|
||||
int load = Integer.MAX_VALUE;
|
||||
BaseItemManager.BaseItemCache cache = null;
|
||||
|
||||
for (BaseItemManager.BaseItemCache baseItemCache : this.baseItems.values()) {
|
||||
int l = baseItemCache.getCache().getCacheLoad();
|
||||
if (l < load) {
|
||||
load = l;
|
||||
cache = baseItemCache;
|
||||
}
|
||||
}
|
||||
|
||||
if (cache == null) {
|
||||
throw new RuntimeException("No cache is available!");
|
||||
} else {
|
||||
return cache;
|
||||
}
|
||||
}
|
||||
|
||||
private static class BaseItemCache {
|
||||
private BaseItemEnum baseItemEnum;
|
||||
private BaseItem baseItem;
|
||||
private ModelIdCache cache;
|
||||
|
||||
public BaseItem getBaseItem() {
|
||||
return this.baseItem;
|
||||
}
|
||||
|
||||
public BaseItemManager.BaseItemCache setBaseItem(BaseItem baseItem) {
|
||||
this.baseItem = baseItem;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ModelIdCache getCache() {
|
||||
return this.cache;
|
||||
}
|
||||
|
||||
public BaseItemManager.BaseItemCache setCache(ModelIdCache cache) {
|
||||
this.cache = cache;
|
||||
return this;
|
||||
}
|
||||
|
||||
public void clearOverrides() {
|
||||
if (this.baseItem != null) {
|
||||
this.baseItem.clearOverrides();
|
||||
}
|
||||
}
|
||||
|
||||
public BaseItemCache(BaseItemEnum baseItemEnum, BaseItem baseItem, ModelIdCache cache) {
|
||||
this.baseItemEnum = baseItemEnum;
|
||||
this.baseItem = baseItem;
|
||||
this.cache = cache;
|
||||
}
|
||||
|
||||
public BaseItemEnum getBaseItemEnum() {
|
||||
return this.baseItemEnum;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.ticxo.modelengine.core.generator;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class ModelCacheGroup {
|
||||
protected final String version = "R4.0.8";
|
||||
protected final Map<String, ModelIdCache> cache = new HashMap<>();
|
||||
}
|
||||
@@ -0,0 +1,820 @@
|
||||
package com.ticxo.modelengine.core.generator;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.common.collect.Ordering;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.error.ErrorCollector;
|
||||
import com.ticxo.modelengine.api.error.IError;
|
||||
import com.ticxo.modelengine.api.events.ModelRegistrationEvent;
|
||||
import com.ticxo.modelengine.api.events.RegisterParserEvent;
|
||||
import com.ticxo.modelengine.api.generator.ModelGenerator;
|
||||
import com.ticxo.modelengine.api.generator.assets.BlueprintTexture;
|
||||
import com.ticxo.modelengine.api.generator.assets.ItemModel;
|
||||
import com.ticxo.modelengine.api.generator.assets.ItemModelData;
|
||||
import com.ticxo.modelengine.api.generator.assets.JavaItemModel;
|
||||
import com.ticxo.modelengine.api.generator.assets.ModelAssets;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.generator.parser.ModelParser;
|
||||
import com.ticxo.modelengine.api.model.ModelRegistry;
|
||||
import com.ticxo.modelengine.api.utils.MiscUtils;
|
||||
import com.ticxo.modelengine.api.utils.TFile;
|
||||
import com.ticxo.modelengine.api.utils.config.ConfigProperty;
|
||||
import com.ticxo.modelengine.api.utils.data.ResourceLocation;
|
||||
import com.ticxo.modelengine.api.utils.logger.LogColor;
|
||||
import com.ticxo.modelengine.api.utils.logger.TLogger;
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import com.ticxo.modelengine.api.utils.ticker.DualTicker;
|
||||
import com.ticxo.modelengine.core.generator.atlas.AtlasManager;
|
||||
import com.ticxo.modelengine.core.generator.java.BaseItemTransformer;
|
||||
import com.ticxo.modelengine.core.generator.parser.blockbench.BlockbenchParser;
|
||||
import com.ticxo.modelengine.core.javasupport.Java21Access;
|
||||
import it.unimi.dsi.fastutil.Pair;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
import java.util.Set;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
import javax.imageio.ImageIO;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.NamespacedKey;
|
||||
|
||||
public class ModelGeneratorImpl implements ModelGenerator {
|
||||
private static final List<String> OVERLAYS = List.of("1_19_4", "1_21_2", "1_21_4", "1_21_5", "1_21_6", "26_1", "26_2");
|
||||
private final ModelEngineAPI plugin;
|
||||
private final Gson gson;
|
||||
private final List<ModelParser> parsers = new ArrayList<>();
|
||||
private final List<ModelAssets> assets = new ArrayList<>();
|
||||
private final AtlasManager atlasManager;
|
||||
private final BaseItemManager baseItemManager;
|
||||
private final ExecutorService generatorService = Executors.newFixedThreadPool(
|
||||
ConfigProperty.MAX_GENERATOR_THREADS.getIntOrIfNeg(() -> Runtime.getRuntime().availableProcessors())
|
||||
);
|
||||
private final File blueprintFolder;
|
||||
private final File internalFolder;
|
||||
private final File internalExampleFolder;
|
||||
private final File internalBlueprintFolder;
|
||||
private final File packFolder;
|
||||
private final File assetsFolder;
|
||||
private final File zippedResourcePack;
|
||||
private final Map<ModelGenerator.Phase, Set<Runnable>> tasks = Maps.newConcurrentMap();
|
||||
private final Set<ModelGenerator.Phase> executed = new HashSet<>();
|
||||
private String namespace;
|
||||
private String texturePath;
|
||||
private File modelFolder;
|
||||
private File itemsFolder;
|
||||
private boolean generateMeta;
|
||||
private boolean deleteOld;
|
||||
private boolean mergeItemModels;
|
||||
private Set<String> disabledOverlays = Set.of();
|
||||
private boolean initialized;
|
||||
private final long[] timer = new long[3];
|
||||
private final Map<String, String> textureNameCache = new HashMap<>();
|
||||
private final Set<ResourceLocation> writtenTextures = ConcurrentHashMap.newKeySet();
|
||||
private final Map<String, String> modelAliases = new ConcurrentHashMap<>();
|
||||
|
||||
public ModelGeneratorImpl(ModelEngineAPI plugin) {
|
||||
this.plugin = plugin;
|
||||
this.gson = plugin.getGson();
|
||||
this.blueprintFolder = TFile.createDirectory(plugin.getDataFolder(), "blueprints");
|
||||
this.internalFolder = TFile.createDirectory(plugin.getDataFolder(), "internals");
|
||||
this.internalExampleFolder = TFile.createDirectory(this.internalFolder, "examples");
|
||||
this.internalBlueprintFolder = TFile.createDirectory(this.internalFolder, "blueprints");
|
||||
this.packFolder = TFile.createDirectory(plugin.getDataFolder(), "resource pack");
|
||||
this.assetsFolder = TFile.createDirectory(this.packFolder, "assets");
|
||||
this.zippedResourcePack = TFile.createFile(plugin.getDataFolder(), "resource pack.zip");
|
||||
this.atlasManager = new AtlasManager(this);
|
||||
this.baseItemManager = new BaseItemManager(this);
|
||||
this.baseItemManager.refreshCache();
|
||||
plugin.getConfigManager().registerReferenceUpdate(this::updateConfig);
|
||||
this.parsers.add(new BlockbenchParser(this));
|
||||
ModelEngineAPI.callEvent(new RegisterParserEvent(this.parsers));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void importModels(boolean isStartup) {
|
||||
this.executed.clear();
|
||||
this.queueTask(ModelGenerator.Phase.PRE_IMPORT, () -> this.timer[0] = System.nanoTime());
|
||||
this.queueTask(ModelGenerator.Phase.POST_IMPORT, () -> this.timer[0] = System.nanoTime() - this.timer[0]);
|
||||
this.queueTask(ModelGenerator.Phase.PRE_ASSETS, () -> this.timer[1] = System.nanoTime());
|
||||
this.queueTask(ModelGenerator.Phase.POST_ASSETS, () -> this.timer[1] = System.nanoTime() - this.timer[1]);
|
||||
this.queueTask(ModelGenerator.Phase.PRE_ZIPPING, () -> this.timer[2] = System.nanoTime());
|
||||
this.queueTask(ModelGenerator.Phase.POST_ZIPPING, () -> this.timer[2] = System.nanoTime() - this.timer[2]);
|
||||
this.queueTask(ModelGenerator.Phase.FINISHED, () -> {
|
||||
TLogger.log(LogColor.BRIGHT_GREEN + "Generator Profiled:");
|
||||
TLogger.log(LogColor.BRIGHT_GREEN + " - Import Phase: " + MiscUtils.FORMATTER.format(this.timer[0] / 1000000.0) + "ms");
|
||||
TLogger.log(LogColor.BRIGHT_GREEN + " - Assets Phase: " + MiscUtils.FORMATTER.format(this.timer[1] / 1000000.0) + "ms");
|
||||
TLogger.log(LogColor.BRIGHT_GREEN + " - Zipping Phase: " + MiscUtils.FORMATTER.format(this.timer[2] / 1000000.0) + "ms");
|
||||
});
|
||||
if (isStartup && !ConfigProperty.LATE_REGISTER.getBoolean()) {
|
||||
this.importModelsInternal(true);
|
||||
} else {
|
||||
DualTicker.queueAsyncTask(() -> CompletableFuture.runAsync(() -> this.importModelsInternal(isStartup)));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void generateAssets(boolean isStartup) {
|
||||
if (!ConfigProperty.LATE_REGISTER.getBoolean() && ConfigProperty.LATE_ASSETS.getBoolean()) {
|
||||
DualTicker.queueAsyncTask(() -> CompletableFuture.runAsync(() -> this.generateAssetsInternal(isStartup)));
|
||||
} else {
|
||||
this.generateAssetsInternal(true);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void zipResourcePack(boolean isStartup) {
|
||||
if (!ConfigProperty.ZIP.getBoolean()) {
|
||||
this.executeQueuedTask(ModelGenerator.Phase.FINISHED);
|
||||
} else {
|
||||
if (!ConfigProperty.LATE_ASSETS.getBoolean() && ConfigProperty.LATE_ZIPPING.getBoolean()) {
|
||||
DualTicker.queueAsyncTask(() -> CompletableFuture.runAsync(this::zipResourcePackInternal));
|
||||
} else {
|
||||
this.zipResourcePackInternal();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateConfig() {
|
||||
this.namespace = ConfigProperty.NAMESPACE.getString().toLowerCase(Locale.ENGLISH);
|
||||
this.texturePath = ConfigProperty.TEXTURE_PATH.getString().toLowerCase(Locale.ENGLISH);
|
||||
this.modelFolder = TFile.createDirectory(this.assetsFolder, this.namespace, "models");
|
||||
this.itemsFolder = TFile.createDirectory(this.assetsFolder, this.namespace, "items");
|
||||
this.baseItemManager.updateModels();
|
||||
this.generateMeta = ConfigProperty.MCMETA.getBoolean();
|
||||
this.deleteOld = ConfigProperty.DELETE_OLD.getBoolean();
|
||||
this.mergeItemModels = ConfigProperty.MERGE_ITEM_MODELS.getBoolean();
|
||||
this.disabledOverlays = new HashSet<>();
|
||||
List<?> raw = ConfigProperty.DISABLED_OVERLAYS.getStringList();
|
||||
ArrayList<String> resolved = new ArrayList<>();
|
||||
|
||||
for (Object entry : raw) {
|
||||
String text = String.valueOf(entry).trim();
|
||||
String version = OVERLAYS.stream().filter(overlay -> overlay.equals(text) || digitsOf(overlay).equals(digitsOf(text))).findFirst().orElse(null);
|
||||
if (version == null) {
|
||||
TLogger.warn("Unknown entry in Disabled-Overlays: " + text + ". Valid overlays: " + OVERLAYS);
|
||||
} else {
|
||||
this.disabledOverlays.add(version);
|
||||
resolved.add(version);
|
||||
}
|
||||
}
|
||||
|
||||
if (!raw.equals(resolved)) {
|
||||
this.plugin.getConfigManager().set(ConfigProperty.DISABLED_OVERLAYS, resolved);
|
||||
this.plugin.getConfigManager().save();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void queueTask(ModelGenerator.Phase post, Runnable task) {
|
||||
if (!this.executed.contains(ModelGenerator.Phase.FINISHED) && !this.executed.contains(post)) {
|
||||
this.tasks.computeIfAbsent(post, phase -> new LinkedHashSet<>()).add(task);
|
||||
} else {
|
||||
task.run();
|
||||
}
|
||||
}
|
||||
|
||||
private void executeQueuedTask(ModelGenerator.Phase phase) {
|
||||
this.executed.add(phase);
|
||||
if (phase == ModelGenerator.Phase.FINISHED) {
|
||||
this.tasks.values().forEach(runnables -> runnables.forEach(Runnable::run));
|
||||
this.tasks.clear();
|
||||
} else {
|
||||
this.tasks.computeIfPresent(phase, (p, runnables) -> {
|
||||
runnables.forEach(Runnable::run);
|
||||
runnables.clear();
|
||||
return runnables;
|
||||
});
|
||||
}
|
||||
|
||||
ModelEngineAPI.callEvent(new ModelRegistrationEvent(phase));
|
||||
}
|
||||
|
||||
private void importModelsInternal(boolean isStartup) {
|
||||
TLogger.log();
|
||||
TLogger.log(LogColor.BOLD + LogColor.CYAN.toString() + "[Importing models]");
|
||||
this.initialized = false;
|
||||
this.executeQueuedTask(ModelGenerator.Phase.PRE_IMPORT);
|
||||
this.baseItemManager.refreshCache();
|
||||
this.textureNameCache.clear();
|
||||
ModelRegistry registry = this.plugin.getModelRegistry();
|
||||
registry.clearRegistry();
|
||||
this.copyInternalFiles();
|
||||
List<File> files = Lists.newArrayList();
|
||||
File[] fa = this.blueprintFolder.listFiles();
|
||||
if (fa != null) {
|
||||
files.addAll(Arrays.asList(fa));
|
||||
}
|
||||
|
||||
fa = this.internalBlueprintFolder.listFiles();
|
||||
if (fa != null) {
|
||||
files.addAll(Arrays.asList(fa));
|
||||
}
|
||||
|
||||
if (Bukkit.getPluginManager().getPlugin("MythicMobs") != null) {
|
||||
try {
|
||||
files.addAll(Java21Access.getMythicPackModelFiles.call());
|
||||
} catch (Throwable var9) {
|
||||
var9.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
if (files.isEmpty()) {
|
||||
this.initialized = true;
|
||||
this.executeQueuedTask(ModelGenerator.Phase.FINISHED);
|
||||
} else {
|
||||
Queue<File> compartment = new LinkedList<>();
|
||||
files.sort(Ordering.natural());
|
||||
ArrayList<CompletableFuture<Void>> importTasks = new ArrayList<>();
|
||||
|
||||
label54:
|
||||
while (true) {
|
||||
for (File file : files) {
|
||||
if (!file.isFile()) {
|
||||
if (file.isDirectory()) {
|
||||
compartment.add(file);
|
||||
}
|
||||
} else {
|
||||
importTasks.add(
|
||||
CompletableFuture.runAsync(
|
||||
() -> {
|
||||
boolean fileParsed = false;
|
||||
ErrorCollector collector = new ErrorCollector(file.getName());
|
||||
|
||||
for (ModelParser parser : this.parsers) {
|
||||
if (parser.validateFile(file)) {
|
||||
try {
|
||||
Pair<ModelBlueprint, ModelAssets> modelData = parser.generate(file, collector);
|
||||
if (modelData != null) {
|
||||
ModelBlueprint blueprint = (ModelBlueprint)modelData.left();
|
||||
ModelAssets asset = (ModelAssets)modelData.right();
|
||||
blueprint.finalizeModel(collector);
|
||||
|
||||
for (Entry<String, BlueprintBone> boneEntry : blueprint.getFlatMap().entrySet()) {
|
||||
BlueprintBone bone = boneEntry.getValue();
|
||||
if (bone.isRenderer()) {
|
||||
synchronized (this.baseItemManager) {
|
||||
this.baseItemManager.requestId(bone, bone.getModelData().getMultiModels().getKeys());
|
||||
}
|
||||
|
||||
if (this.mergeItemModels) {
|
||||
bone.getModelData()
|
||||
.setSingleComposite(
|
||||
new ItemModelData.SingleComposite(new NamespacedKey(this.namespace, blueprint.getName()))
|
||||
);
|
||||
bone.getModelData().setVariant(bone.getName());
|
||||
} else {
|
||||
bone.getModelData()
|
||||
.setSingleComposite(
|
||||
new ItemModelData.SingleComposite(
|
||||
new NamespacedKey(this.namespace, blueprint.getName() + "/" + bone.getName())
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
synchronized (registry) {
|
||||
registry.registerBlueprint(blueprint);
|
||||
}
|
||||
|
||||
synchronized (this.assets) {
|
||||
this.assets.add(asset);
|
||||
}
|
||||
|
||||
fileParsed = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (collector.hasError()) {
|
||||
collector.logAll();
|
||||
}
|
||||
} catch (Exception var22) {
|
||||
var22.printStackTrace();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!fileParsed) {
|
||||
IError.UNKNOWN_FORMAT.log(collector);
|
||||
}
|
||||
|
||||
synchronized (this.timer) {
|
||||
collector.logAll();
|
||||
}
|
||||
},
|
||||
this.generatorService
|
||||
)
|
||||
.handle((res, ex) -> {
|
||||
if (ex != null) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
while (!compartment.isEmpty()) {
|
||||
File[] ca = compartment.poll().listFiles();
|
||||
if (ca != null && ca.length != 0) {
|
||||
files = Arrays.asList(ca);
|
||||
continue label54;
|
||||
}
|
||||
}
|
||||
|
||||
CompletableFuture.allOf(importTasks.toArray(CompletableFuture[]::new)).thenRunAsync(() -> {
|
||||
this.initialized = true;
|
||||
this.baseItemManager.endSession();
|
||||
this.executeQueuedTask(ModelGenerator.Phase.POST_IMPORT);
|
||||
this.generateAssets(isStartup);
|
||||
}).handle((res, ex) -> {
|
||||
if (ex != null) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void generateAssetsInternal(boolean isStartup) {
|
||||
this.executeQueuedTask(ModelGenerator.Phase.PRE_ASSETS);
|
||||
this.baseItemManager.clearOverrides();
|
||||
this.atlasManager.reset();
|
||||
this.writtenTextures.clear();
|
||||
this.modelAliases.clear();
|
||||
if (this.deleteOld && !TFile.delete(this.packFolder)) {
|
||||
TLogger.error("Failed to clear old resource pack folder.");
|
||||
}
|
||||
|
||||
ArrayList<CompletableFuture<Void>> assetTasks = new ArrayList<>();
|
||||
|
||||
for (ModelAssets asset : this.assets) {
|
||||
assetTasks.add(
|
||||
CompletableFuture.runAsync(
|
||||
() -> {
|
||||
for (BlueprintTexture texture : asset.getTextures()) {
|
||||
if (!"minecraft".equals(texture.getPath().getNamespace())) {
|
||||
this.atlasManager.addSingle(texture.getPath());
|
||||
if (this.writtenTextures.add(texture.getPath())) {
|
||||
File png = TFile.createFile(this.assetsFolder, "textures", texture.getPath(), "png");
|
||||
BufferedImage image = TFile.toImage(texture.getSource());
|
||||
|
||||
try {
|
||||
byte[] palette = PaletteImageWriter.encode(image);
|
||||
if (palette != null) {
|
||||
Files.write(png.toPath(), palette);
|
||||
} else {
|
||||
ImageIO.write(image, "png", png);
|
||||
}
|
||||
} catch (IOException var24) {
|
||||
var24.printStackTrace();
|
||||
}
|
||||
|
||||
if (texture.getMcMeta() != null && this.shouldGenerateMCMeta(image, texture)) {
|
||||
HashMap<String, BlueprintTexture.MCMeta> lazyMCMeta = new HashMap<>();
|
||||
File mcmeta = TFile.createFile(this.assetsFolder, "textures", texture.getPath(), "png.mcmeta");
|
||||
|
||||
try (FileWriter writer = new FileWriter(mcmeta)) {
|
||||
lazyMCMeta.put("animation", texture.getMcMeta());
|
||||
writer.write(this.gson.toJson(lazyMCMeta));
|
||||
} catch (IOException var23) {
|
||||
var23.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ItemModel.Select select = this.mergeItemModels ? new ItemModel.Select() : null;
|
||||
HashMap<String, String> writtenModels = new HashMap<>();
|
||||
|
||||
for (Collection<JavaItemModel> models : asset.getModels().values()) {
|
||||
if (models.size() == 1) {
|
||||
JavaItemModel model = models.iterator().next();
|
||||
String json = this.gson.toJson(model);
|
||||
String canonical = writtenModels.putIfAbsent(json, model.getName());
|
||||
if (canonical == null) {
|
||||
canonical = model.getName();
|
||||
File modelJson = TFile.createFile(this.modelFolder, asset.getName(), model.getName() + ".json");
|
||||
|
||||
try (FileWriter writer = new FileWriter(modelJson)) {
|
||||
writer.write(json);
|
||||
} catch (IOException var20) {
|
||||
var20.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
this.modelAliases.put(asset.getName() + "/" + model.getName(), asset.getName() + "/" + canonical);
|
||||
}
|
||||
|
||||
this.writeItemModel(
|
||||
asset, model.getName(), new ItemModel.Model(new NamespacedKey(this.namespace, asset.getName() + "/" + canonical)), select
|
||||
);
|
||||
} else {
|
||||
int id = 0;
|
||||
String modelName = "";
|
||||
ItemModel.Composite composite = new ItemModel.Composite();
|
||||
|
||||
for (JavaItemModel model : models) {
|
||||
model.finalizeModel();
|
||||
File modelJson;
|
||||
if (id == 0) {
|
||||
modelName = model.getName();
|
||||
modelJson = TFile.createFile(this.modelFolder, asset.getName(), model.getName() + ".json");
|
||||
composite.getModels().add(new ItemModel.Model(new NamespacedKey(this.namespace, asset.getName() + "/" + model.getName())));
|
||||
} else {
|
||||
modelJson = TFile.createFile(this.modelFolder, asset.getName(), model.getName(), id + ".json");
|
||||
composite.getModels()
|
||||
.add(new ItemModel.Model(new NamespacedKey(this.namespace, asset.getName() + "/" + model.getName() + "/" + id)));
|
||||
}
|
||||
|
||||
id++;
|
||||
|
||||
try (FileWriter writer = new FileWriter(modelJson)) {
|
||||
writer.write(this.gson.toJson(model));
|
||||
} catch (IOException var17) {
|
||||
var17.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
this.writeItemModel(asset, modelName, composite, select);
|
||||
}
|
||||
}
|
||||
|
||||
if (select != null && !select.getCases().isEmpty()) {
|
||||
select.setFallback(select.getCases().get(0).model());
|
||||
this.writeItemJson(TFile.createFile(this.itemsFolder, asset.getName() + ".json"), select, asset);
|
||||
}
|
||||
},
|
||||
this.generatorService
|
||||
)
|
||||
.handleAsync((res, ex) -> {
|
||||
if (ex != null) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}, this.generatorService)
|
||||
);
|
||||
}
|
||||
|
||||
CompletableFuture.allOf(assetTasks.toArray(CompletableFuture[]::new)).thenRunAsync(() -> {
|
||||
this.assets.clear();
|
||||
this.baseItemManager.registerModels(this.namespace, this.modelAliases);
|
||||
this.baseItemManager.createModelFiles();
|
||||
this.baseItemManager.cleanUp();
|
||||
if (ConfigProperty.ATLAS.getBoolean()) {
|
||||
this.atlasManager.generateFile();
|
||||
}
|
||||
|
||||
this.copyResources();
|
||||
this.executeQueuedTask(ModelGenerator.Phase.POST_ASSETS);
|
||||
this.zipResourcePack(isStartup);
|
||||
}, this.generatorService).handleAsync((res, ex) -> {
|
||||
if (ex != null) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}, this.generatorService);
|
||||
}
|
||||
|
||||
private void writeItemModel(ModelAssets asset, String boneName, ItemModel itemModel, ItemModel.Select select) {
|
||||
if (select != null) {
|
||||
select.getCases().add(new ItemModel.Select.Case(itemModel, boneName));
|
||||
} else {
|
||||
this.writeItemJson(TFile.createFile(this.itemsFolder, asset.getName(), boneName + ".json"), itemModel, asset);
|
||||
}
|
||||
}
|
||||
|
||||
private void writeItemJson(File itemJson, ItemModel itemModel, ModelAssets asset) {
|
||||
try (FileWriter writer = new FileWriter(itemJson)) {
|
||||
writer.write(this.gson.toJson(BaseItemTransformer.wrapModel(this.gson, itemModel, asset.getName().equals("head"))));
|
||||
} catch (IOException var9) {
|
||||
var9.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private void copyInternalFiles() {
|
||||
TFile.copyResource(this.plugin, TFile.createFile(this.internalExampleFolder, "player_model.bbmodel"), "internal/player_model.bbmodel");
|
||||
TFile.copyResource(this.plugin, TFile.createFile(this.internalBlueprintFolder, "internal_fire.bbmodel"), "internal/internal_fire.bbmodel");
|
||||
}
|
||||
|
||||
private void copyResources() {
|
||||
TFile.copyResource(this.plugin, this.packFolder, "pack", "pack.png");
|
||||
if (this.disabledOverlays.isEmpty()) {
|
||||
HashMap<String, String> overlayReplacements = new HashMap<>();
|
||||
|
||||
for (String version : OVERLAYS) {
|
||||
overlayReplacements.put("modelengine_" + version, this.namespace + "_" + version);
|
||||
}
|
||||
|
||||
TFile.copyResourceTemplated(this.plugin, this.packFolder, "pack", "pack.mcmeta", "pack.mcmeta", overlayReplacements);
|
||||
} else {
|
||||
this.copyFilteredPackMeta();
|
||||
}
|
||||
|
||||
if (ConfigProperty.SHADER.getBoolean()) {
|
||||
Map<String, String> namespaceReplacements = Map.of("modelengine:", this.namespace + ":");
|
||||
TFile.copyResourceTemplated(
|
||||
this.plugin,
|
||||
this.packFolder,
|
||||
"pack",
|
||||
"assets/modelengine/items/player_head.json",
|
||||
"assets/" + this.namespace + "/items/player_head.json",
|
||||
namespaceReplacements
|
||||
);
|
||||
if (this.isOverlayEnabled("1_21_4")) {
|
||||
TFile.copyResourceTemplated(
|
||||
this.plugin,
|
||||
this.packFolder,
|
||||
"pack",
|
||||
"modelengine_1_21_4/assets/modelengine/items/player_head.json",
|
||||
this.namespace + "_1_21_4/assets/" + this.namespace + "/items/player_head.json",
|
||||
namespaceReplacements
|
||||
);
|
||||
}
|
||||
|
||||
for (String limb : List.of("head", "left_arm", "left_leg", "right_arm", "right_leg", "slim_left", "slim_right", "torso")) {
|
||||
TFile.copyResource(
|
||||
this.plugin,
|
||||
this.packFolder,
|
||||
"pack",
|
||||
"assets/modelengine/models/custom/entities/player/" + limb + ".json",
|
||||
"assets/" + this.namespace + "/models/custom/entities/player/" + limb + ".json"
|
||||
);
|
||||
}
|
||||
|
||||
if (this.isOverlayEnabled("1_19_4")) {
|
||||
TFile.copyResourceTemplated(
|
||||
this.plugin,
|
||||
this.packFolder,
|
||||
"pack",
|
||||
"modelengine_1_19_4/assets/minecraft/models/item/player_head.json",
|
||||
this.namespace + "_1_19_4/assets/minecraft/models/item/player_head.json",
|
||||
namespaceReplacements
|
||||
);
|
||||
}
|
||||
|
||||
this.copyOverlayResource("1_21_2", "assets/minecraft/shaders/core/rendertype_entity_translucent.fsh");
|
||||
this.copyOverlayResource("1_21_2", "assets/minecraft/shaders/core/rendertype_entity_translucent.json");
|
||||
this.copyOverlayResource("1_21_2", "assets/minecraft/shaders/core/rendertype_entity_translucent.vsh");
|
||||
this.copyOverlayResource("1_21_2", "assets/minecraft/shaders/core/entity.fsh");
|
||||
this.copyOverlayResource("1_21_2", "assets/minecraft/shaders/core/entity.vsh");
|
||||
this.copyOverlayResource("1_21_5", "assets/minecraft/shaders/core/entity.fsh");
|
||||
this.copyOverlayResource("1_21_5", "assets/minecraft/shaders/core/entity.vsh");
|
||||
this.copyOverlayResource("1_21_6", "assets/minecraft/shaders/core/entity.fsh");
|
||||
this.copyOverlayResource("1_21_6", "assets/minecraft/shaders/core/entity.vsh");
|
||||
this.copyOverlayResource("26_1", "assets/minecraft/shaders/core/entity.fsh");
|
||||
this.copyOverlayResource("26_1", "assets/minecraft/shaders/core/entity.vsh");
|
||||
this.copyOverlayResource("26_2", "assets/minecraft/shaders/core/entity.fsh");
|
||||
this.copyOverlayResource("26_2", "assets/minecraft/shaders/core/entity.vsh");
|
||||
TFile.copyResource(this.plugin, this.packFolder, "pack", "assets/minecraft/shaders/core/entity.fsh");
|
||||
TFile.copyResource(this.plugin, this.packFolder, "pack", "assets/minecraft/shaders/core/entity.vsh");
|
||||
TFile.copyResource(this.plugin, this.packFolder, "pack", "assets/minecraft/shaders/core/rendertype_entity_translucent.fsh");
|
||||
TFile.copyResource(this.plugin, this.packFolder, "pack", "assets/minecraft/shaders/core/rendertype_entity_translucent.json");
|
||||
TFile.copyResource(this.plugin, this.packFolder, "pack", "assets/minecraft/shaders/core/rendertype_entity_translucent.vsh");
|
||||
TFile.copyResource(this.plugin, this.packFolder, "pack", "assets/minecraft/shaders/include/player_shader.glsl");
|
||||
}
|
||||
}
|
||||
|
||||
private void copyOverlayResource(String version, String relativePath) {
|
||||
if (this.isOverlayEnabled(version)) {
|
||||
TFile.copyResource(
|
||||
this.plugin, this.packFolder, "pack", "modelengine_" + version + "/" + relativePath, this.namespace + "_" + version + "/" + relativePath
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static String digitsOf(String value) {
|
||||
return value.replaceAll("[^0-9]", "");
|
||||
}
|
||||
|
||||
private boolean isOverlayEnabled(String version) {
|
||||
return !this.disabledOverlays.contains(version);
|
||||
}
|
||||
|
||||
private void copyFilteredPackMeta() {
|
||||
File file = TFile.createFile(this.packFolder, "pack.mcmeta");
|
||||
if (!file.exists()) {
|
||||
try {
|
||||
try (InputStream reader = this.plugin.getResource("pack/pack.mcmeta")) {
|
||||
if (reader != null) {
|
||||
JsonObject root = (JsonObject)this.gson.fromJson(new String(reader.readAllBytes(), StandardCharsets.UTF_8), JsonObject.class);
|
||||
JsonObject overlays = root.getAsJsonObject("overlays");
|
||||
if (overlays != null) {
|
||||
JsonArray kept = new JsonArray();
|
||||
|
||||
for (JsonElement element : overlays.getAsJsonArray("entries")) {
|
||||
JsonObject entry = element.getAsJsonObject();
|
||||
String version = entry.get("directory").getAsString().substring("modelengine_".length());
|
||||
if (this.isOverlayEnabled(version)) {
|
||||
entry.addProperty("directory", this.namespace + "_" + version);
|
||||
kept.add(entry);
|
||||
}
|
||||
}
|
||||
|
||||
overlays.add("entries", kept);
|
||||
}
|
||||
|
||||
Files.writeString(file.toPath(), this.gson.toJson(root), StandardCharsets.UTF_8);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch (IOException var12) {
|
||||
var12.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void zipResourcePackInternal() {
|
||||
this.executeQueuedTask(ModelGenerator.Phase.PRE_ZIPPING);
|
||||
|
||||
try {
|
||||
ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(this.zippedResourcePack), 65536));
|
||||
File[] files = this.packFolder.listFiles();
|
||||
if (files == null) {
|
||||
zipOut.close();
|
||||
this.executeQueuedTask(ModelGenerator.Phase.FINISHED);
|
||||
return;
|
||||
}
|
||||
|
||||
Arrays.sort((Object[])files);
|
||||
|
||||
for (File file : files) {
|
||||
TFile.zipFile(file, file.getName(), zipOut, false);
|
||||
}
|
||||
|
||||
zipOut.close();
|
||||
TLogger.log();
|
||||
TLogger.log(LogColor.BRIGHT_GREEN + "Resource pack zipped.");
|
||||
} catch (IOException var7) {
|
||||
var7.printStackTrace();
|
||||
}
|
||||
|
||||
this.executeQueuedTask(ModelGenerator.Phase.POST_ZIPPING);
|
||||
this.executeQueuedTask(ModelGenerator.Phase.FINISHED);
|
||||
}
|
||||
|
||||
private boolean shouldGenerateMCMeta(BufferedImage image, BlueprintTexture texture) {
|
||||
if (texture.getMcMeta().isMustGenerate()) {
|
||||
return true;
|
||||
} else if (!this.generateMeta) {
|
||||
return false;
|
||||
} else {
|
||||
float textureRatio = (float)image.getHeight() / image.getWidth();
|
||||
float uvRatio = (float)texture.getFrameHeight() / texture.getFrameWidth();
|
||||
return TMath.isSimilar(textureRatio, uvRatio) ? false : textureRatio / uvRatio > 1.0F;
|
||||
}
|
||||
}
|
||||
|
||||
public ModelEngineAPI getPlugin() {
|
||||
return this.plugin;
|
||||
}
|
||||
|
||||
public Gson getGson() {
|
||||
return this.gson;
|
||||
}
|
||||
|
||||
public List<ModelParser> getParsers() {
|
||||
return this.parsers;
|
||||
}
|
||||
|
||||
public List<ModelAssets> getAssets() {
|
||||
return this.assets;
|
||||
}
|
||||
|
||||
public AtlasManager getAtlasManager() {
|
||||
return this.atlasManager;
|
||||
}
|
||||
|
||||
public BaseItemManager getBaseItemManager() {
|
||||
return this.baseItemManager;
|
||||
}
|
||||
|
||||
public ExecutorService getGeneratorService() {
|
||||
return this.generatorService;
|
||||
}
|
||||
|
||||
public File getBlueprintFolder() {
|
||||
return this.blueprintFolder;
|
||||
}
|
||||
|
||||
public File getInternalFolder() {
|
||||
return this.internalFolder;
|
||||
}
|
||||
|
||||
public File getInternalExampleFolder() {
|
||||
return this.internalExampleFolder;
|
||||
}
|
||||
|
||||
public File getInternalBlueprintFolder() {
|
||||
return this.internalBlueprintFolder;
|
||||
}
|
||||
|
||||
public File getPackFolder() {
|
||||
return this.packFolder;
|
||||
}
|
||||
|
||||
public File getAssetsFolder() {
|
||||
return this.assetsFolder;
|
||||
}
|
||||
|
||||
public File getZippedResourcePack() {
|
||||
return this.zippedResourcePack;
|
||||
}
|
||||
|
||||
public Map<ModelGenerator.Phase, Set<Runnable>> getTasks() {
|
||||
return this.tasks;
|
||||
}
|
||||
|
||||
public Set<ModelGenerator.Phase> getExecuted() {
|
||||
return this.executed;
|
||||
}
|
||||
|
||||
public String getNamespace() {
|
||||
return this.namespace;
|
||||
}
|
||||
|
||||
public String getTexturePath() {
|
||||
return this.texturePath;
|
||||
}
|
||||
|
||||
public File getModelFolder() {
|
||||
return this.modelFolder;
|
||||
}
|
||||
|
||||
public File getItemsFolder() {
|
||||
return this.itemsFolder;
|
||||
}
|
||||
|
||||
public boolean isGenerateMeta() {
|
||||
return this.generateMeta;
|
||||
}
|
||||
|
||||
public boolean isDeleteOld() {
|
||||
return this.deleteOld;
|
||||
}
|
||||
|
||||
public boolean isMergeItemModels() {
|
||||
return this.mergeItemModels;
|
||||
}
|
||||
|
||||
public Set<String> getDisabledOverlays() {
|
||||
return this.disabledOverlays;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInitialized() {
|
||||
return this.initialized;
|
||||
}
|
||||
|
||||
public long[] getTimer() {
|
||||
return this.timer;
|
||||
}
|
||||
|
||||
public Map<String, String> getTextureNameCache() {
|
||||
return this.textureNameCache;
|
||||
}
|
||||
|
||||
public Set<ResourceLocation> getWrittenTextures() {
|
||||
return this.writtenTextures;
|
||||
}
|
||||
|
||||
public Map<String, String> getModelAliases() {
|
||||
return this.modelAliases;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.ticxo.modelengine.core.generator;
|
||||
|
||||
import com.ticxo.modelengine.api.generator.BaseItemEnum;
|
||||
import com.ticxo.modelengine.api.generator.assets.ItemModelData;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
import java.util.Set;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
public class ModelIdCache {
|
||||
protected final Map<String, Integer> cachedId = new HashMap<>();
|
||||
protected final Queue<Integer> unused = new LinkedList<>();
|
||||
private final transient Map<Integer, String> dataToModel = new HashMap<>();
|
||||
private final transient Set<String> pendingRemove = new HashSet<>();
|
||||
protected int nextId = 1;
|
||||
private transient int maxId;
|
||||
|
||||
public void gatherExistingIds(BaseItemEnum baseItem, Map<String, BlueprintBone> requested) {
|
||||
this.maxId = 0;
|
||||
this.dataToModel.clear();
|
||||
|
||||
for (Entry<String, Integer> entry : this.cachedId.entrySet()) {
|
||||
String modelId = entry.getKey();
|
||||
Integer dataId = entry.getValue();
|
||||
if (requested.containsKey(modelId)) {
|
||||
BlueprintBone bone = requested.remove(modelId);
|
||||
bone.setDataId(dataId);
|
||||
bone.setBaseItem(baseItem);
|
||||
ItemModelData.SubModel submodel = bone.getModelData().getMultiModels().getSubModel(modelId);
|
||||
submodel.setData(dataId);
|
||||
submodel.setItem(baseItem);
|
||||
this.dataToModel.put(dataId, modelId);
|
||||
this.maxId = Math.max(dataId, this.maxId);
|
||||
} else {
|
||||
this.pendingRemove.add(modelId);
|
||||
this.unused.add(this.cachedId.get(modelId));
|
||||
}
|
||||
}
|
||||
|
||||
this.pendingRemove.forEach(this.cachedId::remove);
|
||||
this.pendingRemove.clear();
|
||||
}
|
||||
|
||||
public void generateNewIds(BaseItemEnum baseItem, String modelId, BlueprintBone bone) {
|
||||
int id = this.unused.isEmpty() ? this.nextId++ : this.unused.poll();
|
||||
bone.setDataId(id);
|
||||
bone.setBaseItem(baseItem);
|
||||
ItemModelData.SubModel submodel = bone.getModelData().getMultiModels().getSubModel(modelId);
|
||||
submodel.setData(id);
|
||||
submodel.setItem(baseItem);
|
||||
this.maxId = Math.max(id, this.maxId);
|
||||
this.dataToModel.put(id, modelId);
|
||||
this.cachedId.put(modelId, id);
|
||||
}
|
||||
|
||||
public void endSession() {
|
||||
for (int id : this.unused) {
|
||||
this.maxId = Math.max(this.maxId, id);
|
||||
}
|
||||
|
||||
this.nextId = this.maxId + 1;
|
||||
}
|
||||
|
||||
public void sortedIterate(BiConsumer<String, Integer> consumer) {
|
||||
for (int i = 1; i < this.nextId; i++) {
|
||||
String id = this.dataToModel.get(i);
|
||||
if (id != null) {
|
||||
consumer.accept(id.replace(":", "/"), i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void cleanUp() {
|
||||
this.dataToModel.clear();
|
||||
this.pendingRemove.clear();
|
||||
}
|
||||
|
||||
public int getCacheLoad() {
|
||||
return this.cachedId.size();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package com.ticxo.modelengine.core.generator;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.zip.CRC32;
|
||||
import java.util.zip.Deflater;
|
||||
|
||||
final class PaletteImageWriter {
|
||||
private static final byte[] SIGNATURE = new byte[]{-119, 80, 78, 71, 13, 10, 26, 10};
|
||||
private static final int MAX_PALETTE = 256;
|
||||
private static final byte COLOR_TYPE_INDEXED = 3;
|
||||
private static final byte FILTER_NONE = 0;
|
||||
|
||||
private PaletteImageWriter() {
|
||||
}
|
||||
|
||||
static byte[] encode(BufferedImage image) throws IOException {
|
||||
if (image == null) {
|
||||
return null;
|
||||
} else {
|
||||
int width = image.getWidth();
|
||||
int height = image.getHeight();
|
||||
if (width > 0 && height > 0) {
|
||||
int[] pixels = image.getRGB(0, 0, width, height, null, 0, width);
|
||||
HashMap<Integer, Integer> distinct = new HashMap<>();
|
||||
|
||||
for (int pixel : pixels) {
|
||||
if (distinct.size() > 256) {
|
||||
return null;
|
||||
}
|
||||
|
||||
distinct.putIfAbsent(pixel, 0);
|
||||
}
|
||||
|
||||
if (distinct.size() > 256) {
|
||||
return null;
|
||||
} else {
|
||||
int[] palette = distinct.keySet().stream().sorted((a, b) -> {
|
||||
int alpha = Integer.compare(a >>> 24, b >>> 24);
|
||||
return alpha != 0 ? alpha : Integer.compare(a & 16777215, b & 16777215);
|
||||
}).mapToInt(Integer::intValue).toArray();
|
||||
|
||||
for (int i = 0; i < palette.length; i++) {
|
||||
distinct.put(palette[i], i);
|
||||
}
|
||||
|
||||
int bitDepth = bitDepth(palette.length);
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
out.write(SIGNATURE);
|
||||
writeChunk(out, "IHDR", header(width, height, bitDepth));
|
||||
writeChunk(out, "PLTE", palette(palette));
|
||||
int translucent = countTranslucent(palette);
|
||||
if (translucent > 0) {
|
||||
writeChunk(out, "tRNS", transparency(palette, translucent));
|
||||
}
|
||||
|
||||
writeChunk(out, "IDAT", deflate(scanlines(pixels, distinct, width, height, bitDepth)));
|
||||
writeChunk(out, "IEND", new byte[0]);
|
||||
return out.toByteArray();
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int bitDepth(int colors) {
|
||||
if (colors <= 2) {
|
||||
return 1;
|
||||
} else if (colors <= 4) {
|
||||
return 2;
|
||||
} else {
|
||||
return colors <= 16 ? 4 : 8;
|
||||
}
|
||||
}
|
||||
|
||||
private static int countTranslucent(int[] palette) {
|
||||
int count = 0;
|
||||
|
||||
for (int i = 0; i < palette.length; i++) {
|
||||
if (palette[i] >>> 24 != 255) {
|
||||
count = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
private static byte[] header(int width, int height, int bitDepth) {
|
||||
byte[] data = new byte[13];
|
||||
writeInt(data, 0, width);
|
||||
writeInt(data, 4, height);
|
||||
data[8] = (byte)bitDepth;
|
||||
data[9] = 3;
|
||||
return data;
|
||||
}
|
||||
|
||||
private static byte[] palette(int[] palette) {
|
||||
byte[] data = new byte[palette.length * 3];
|
||||
|
||||
for (int i = 0; i < palette.length; i++) {
|
||||
data[i * 3] = (byte)(palette[i] >>> 16);
|
||||
data[i * 3 + 1] = (byte)(palette[i] >>> 8);
|
||||
data[i * 3 + 2] = (byte)palette[i];
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
private static byte[] transparency(int[] palette, int count) {
|
||||
byte[] data = new byte[count];
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
data[i] = (byte)(palette[i] >>> 24);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
private static byte[] scanlines(int[] pixels, Map<Integer, Integer> indices, int width, int height, int bitDepth) {
|
||||
int perByte = 8 / bitDepth;
|
||||
int rowBytes = (width + perByte - 1) / perByte;
|
||||
byte[] raw = new byte[(rowBytes + 1) * height];
|
||||
int at = 0;
|
||||
|
||||
for (int y = 0; y < height; y++) {
|
||||
raw[at++] = 0;
|
||||
int row = y * width;
|
||||
|
||||
for (int x = 0; x < width; x++) {
|
||||
int index = indices.get(pixels[row + x]);
|
||||
if (bitDepth == 8) {
|
||||
raw[at + x] = (byte)index;
|
||||
} else {
|
||||
int shift = 8 - bitDepth * (x % perByte + 1);
|
||||
raw[at + x / perByte] = (byte)(raw[at + x / perByte] | (byte)(index << shift));
|
||||
}
|
||||
}
|
||||
|
||||
at += rowBytes;
|
||||
}
|
||||
|
||||
return raw;
|
||||
}
|
||||
|
||||
private static byte[] deflate(byte[] raw) {
|
||||
Deflater deflater = new Deflater(9);
|
||||
|
||||
byte[] var8;
|
||||
try {
|
||||
deflater.setInput(raw);
|
||||
deflater.finish();
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(raw.length / 2 + 64);
|
||||
byte[] buffer = new byte[8192];
|
||||
|
||||
while (!deflater.finished()) {
|
||||
int read = deflater.deflate(buffer);
|
||||
out.write(buffer, 0, read);
|
||||
}
|
||||
|
||||
var8 = out.toByteArray();
|
||||
} finally {
|
||||
deflater.end();
|
||||
}
|
||||
|
||||
return var8;
|
||||
}
|
||||
|
||||
private static void writeChunk(ByteArrayOutputStream out, String type, byte[] data) throws IOException {
|
||||
byte[] header = new byte[4];
|
||||
writeInt(header, 0, data.length);
|
||||
out.write(header);
|
||||
byte[] name = type.getBytes(StandardCharsets.US_ASCII);
|
||||
out.write(name);
|
||||
out.write(data);
|
||||
CRC32 crc = new CRC32();
|
||||
crc.update(name);
|
||||
crc.update(data);
|
||||
byte[] trailer = new byte[4];
|
||||
writeInt(trailer, 0, (int)crc.getValue());
|
||||
out.write(trailer);
|
||||
}
|
||||
|
||||
private static void writeInt(byte[] target, int offset, int value) {
|
||||
target[offset] = (byte)(value >>> 24);
|
||||
target[offset + 1] = (byte)(value >>> 16);
|
||||
target[offset + 2] = (byte)(value >>> 8);
|
||||
target[offset + 3] = (byte)value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.ticxo.modelengine.core.generator.atlas;
|
||||
|
||||
import com.ticxo.modelengine.api.utils.data.ResourceLocation;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Atlas {
|
||||
private final List<Atlas.Source> sources = new ArrayList<>();
|
||||
|
||||
public List<Atlas.Source> getSources() {
|
||||
return this.sources;
|
||||
}
|
||||
|
||||
public static class Directory extends Atlas.Source {
|
||||
public final String source;
|
||||
public final String prefix;
|
||||
|
||||
public Directory(String location) {
|
||||
super("directory");
|
||||
this.source = location;
|
||||
this.prefix = location + "/";
|
||||
}
|
||||
}
|
||||
|
||||
public static class Filter extends Atlas.Source {
|
||||
public final ResourceLocation pattern;
|
||||
|
||||
public Filter(ResourceLocation pattern) {
|
||||
super("filter");
|
||||
this.pattern = pattern;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Single extends Atlas.Source {
|
||||
public final String resource;
|
||||
public final String sprite;
|
||||
|
||||
public Single(String location) {
|
||||
super("single");
|
||||
this.resource = location;
|
||||
this.sprite = location;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Source {
|
||||
public final String type;
|
||||
|
||||
public Source(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.ticxo.modelengine.core.generator.atlas;
|
||||
|
||||
import com.ticxo.modelengine.api.utils.TFile;
|
||||
import com.ticxo.modelengine.api.utils.data.ResourceLocation;
|
||||
import com.ticxo.modelengine.core.generator.ModelGeneratorImpl;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class AtlasManager {
|
||||
private final ModelGeneratorImpl generator;
|
||||
private final File atlases;
|
||||
private final Set<ResourceLocation> registeredPaths = new HashSet<>();
|
||||
private final Atlas atlas;
|
||||
|
||||
public AtlasManager(ModelGeneratorImpl generator) {
|
||||
this.generator = generator;
|
||||
this.atlases = TFile.createDirectory(generator.getPackFolder(), "assets", "minecraft", "atlases");
|
||||
this.atlas = new Atlas();
|
||||
this.reset();
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
this.registeredPaths.clear();
|
||||
this.atlas.getSources().clear();
|
||||
this.atlas.getSources().add(new Atlas.Directory(this.generator.getTexturePath()));
|
||||
this.atlas.getSources().add(new Atlas.Filter(new ResourceLocation("minecraft", "entity/fishing_hook")));
|
||||
}
|
||||
|
||||
public synchronized int addSingle(ResourceLocation location) {
|
||||
String path = location.getPath();
|
||||
if (path.startsWith("entity") || path.startsWith("item") || path.startsWith("block")) {
|
||||
return 2;
|
||||
} else if (!this.registeredPaths.add(location)) {
|
||||
return 1;
|
||||
} else {
|
||||
this.atlas.getSources().add(new Atlas.Single(location.toString()));
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public void generateFile() {
|
||||
this.atlas
|
||||
.getSources()
|
||||
.sort(
|
||||
Comparator.<Atlas.Source>comparingInt(s -> s instanceof Atlas.Single ? 1 : 0)
|
||||
.thenComparing(s -> s instanceof Atlas.Single ? ((Atlas.Single)s).resource : "")
|
||||
);
|
||||
|
||||
try {
|
||||
File file = TFile.createFile(this.atlases, "blocks.json");
|
||||
FileWriter writer = new FileWriter(file);
|
||||
writer.write(this.generator.getGson().toJson(this.atlas));
|
||||
writer.close();
|
||||
} catch (IOException var3) {
|
||||
var3.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public Atlas getAtlas() {
|
||||
return this.atlas;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.ticxo.modelengine.core.generator.java;
|
||||
|
||||
import com.ticxo.modelengine.api.generator.BaseItemEnum;
|
||||
import com.ticxo.modelengine.core.generator.ModelIdCache;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class BaseItem {
|
||||
private final List<BaseItem.JavaOverride> overrides = new ArrayList<>();
|
||||
private transient String name;
|
||||
private transient BaseItemEnum baseItemEnum;
|
||||
private String parent;
|
||||
private Map<String, String> textures;
|
||||
|
||||
public void clearOverrides() {
|
||||
this.overrides.clear();
|
||||
}
|
||||
|
||||
public void addModels(String namespace, ModelIdCache cache, Map<String, String> aliases) {
|
||||
cache.sortedIterate((model, id) -> this.overrides.add(new BaseItem.JavaOverride(namespace + ":" + aliases.getOrDefault(model, model), id)));
|
||||
}
|
||||
|
||||
public List<BaseItem.JavaOverride> getOverrides() {
|
||||
return this.overrides;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public BaseItemEnum getBaseItemEnum() {
|
||||
return this.baseItemEnum;
|
||||
}
|
||||
|
||||
public void setBaseItemEnum(BaseItemEnum baseItemEnum) {
|
||||
this.baseItemEnum = baseItemEnum;
|
||||
}
|
||||
|
||||
static class JavaOverride {
|
||||
private final BaseItem.JavaPredicate predicate;
|
||||
private final String model;
|
||||
|
||||
public JavaOverride(String model, int id) {
|
||||
this.model = model;
|
||||
this.predicate = new BaseItem.JavaPredicate(id);
|
||||
}
|
||||
|
||||
public BaseItem.JavaPredicate getPredicate() {
|
||||
return this.predicate;
|
||||
}
|
||||
|
||||
public String getModel() {
|
||||
return this.model;
|
||||
}
|
||||
}
|
||||
|
||||
record JavaPredicate(int custom_model_data) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.ticxo.modelengine.core.generator.java;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import com.ticxo.modelengine.api.generator.assets.ItemModel;
|
||||
import com.ticxo.modelengine.api.generator.assets.TintSource;
|
||||
|
||||
public class BaseItemTransformer {
|
||||
public static ItemModel to1214Format(BaseItem item) {
|
||||
ItemModel.RangeDispatch model = new ItemModel.RangeDispatch();
|
||||
|
||||
TintSource tint = (TintSource)(switch (item.getBaseItemEnum()) {
|
||||
case FILLED_MAP -> new TintSource.MapColor(-1);
|
||||
case LEATHER_BOOTS, LEATHER_CHESTPLATE, LEATHER_HORSE_ARMOR, LEATHER_LEGGINGS -> new TintSource.Dye(-1);
|
||||
case LINGERING_POTION, POTION, SPLASH_POTION, TIPPED_ARROW -> new TintSource.Potion(-1);
|
||||
});
|
||||
|
||||
for (BaseItem.JavaOverride overrides : item.getOverrides()) {
|
||||
int id = overrides.getPredicate().custom_model_data();
|
||||
ItemModel.Model idModel = new ItemModel.Model(overrides.getModel());
|
||||
idModel.getTints().add(tint);
|
||||
model.getEntries().add(new ItemModel.RangeDispatch.Entry(idModel, id));
|
||||
}
|
||||
|
||||
ItemModel.Model fallback = new ItemModel.Model("minecraft:item/" + item.getName());
|
||||
switch (item.getBaseItemEnum()) {
|
||||
case FILLED_MAP:
|
||||
fallback.getTints().add(new TintSource.Constant(-1));
|
||||
fallback.getTints().add(new TintSource.MapColor());
|
||||
break;
|
||||
case LEATHER_BOOTS:
|
||||
case LEATHER_CHESTPLATE:
|
||||
case LEATHER_HORSE_ARMOR:
|
||||
case LEATHER_LEGGINGS:
|
||||
fallback.getTints().add(new TintSource.Dye());
|
||||
break;
|
||||
case LINGERING_POTION:
|
||||
case POTION:
|
||||
case SPLASH_POTION:
|
||||
case TIPPED_ARROW:
|
||||
fallback.getTints().add(new TintSource.Potion());
|
||||
}
|
||||
|
||||
model.setFallback(fallback);
|
||||
return model;
|
||||
}
|
||||
|
||||
public static JsonElement wrapModel(Gson gson, ItemModel model, boolean oversized) {
|
||||
JsonObject obj = new JsonObject();
|
||||
obj.add("model", gson.toJsonTree(model));
|
||||
if (oversized) {
|
||||
obj.add("oversized_in_gui", new JsonPrimitive(true));
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
+583
@@ -0,0 +1,583 @@
|
||||
package com.ticxo.modelengine.core.generator.parser.blockbench;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.animation.BlueprintAnimation;
|
||||
import com.ticxo.modelengine.api.animation.Timeline;
|
||||
import com.ticxo.modelengine.api.animation.keyframe.KeyframeType;
|
||||
import com.ticxo.modelengine.api.animation.keyframe.KeyframeTypes;
|
||||
import com.ticxo.modelengine.api.animation.keyframe.data.KeyframeReaderRegistry;
|
||||
import com.ticxo.modelengine.api.animation.keyframe.type.ScriptKeyframe;
|
||||
import com.ticxo.modelengine.api.animation.keyframe.type.VectorKeyframe;
|
||||
import com.ticxo.modelengine.api.error.ErrorCollector;
|
||||
import com.ticxo.modelengine.api.error.IError;
|
||||
import com.ticxo.modelengine.api.error.WarnBadTexture;
|
||||
import com.ticxo.modelengine.api.error.WarnDuplicateTexture;
|
||||
import com.ticxo.modelengine.api.error.WarningDuplicateBoneName;
|
||||
import com.ticxo.modelengine.api.events.RegisterBehaviorParserEvent;
|
||||
import com.ticxo.modelengine.api.generator.assets.BlueprintTexture;
|
||||
import com.ticxo.modelengine.api.generator.assets.ItemModelData;
|
||||
import com.ticxo.modelengine.api.generator.assets.JavaItemModel;
|
||||
import com.ticxo.modelengine.api.generator.assets.ModelAssets;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.generator.parser.ModelParser;
|
||||
import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchBehaviorParser;
|
||||
import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchDeserializer;
|
||||
import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchModel;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.utils.MiscUtils;
|
||||
import com.ticxo.modelengine.api.utils.TFile;
|
||||
import com.ticxo.modelengine.api.utils.data.ResourceLocation;
|
||||
import com.ticxo.modelengine.api.utils.math.Direction;
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import com.ticxo.modelengine.core.generator.ModelGeneratorImpl;
|
||||
import com.ticxo.modelengine.core.generator.parser.blockbench.json.DefaultBehaviorParser;
|
||||
import com.ticxo.modelengine.core.generator.parser.blockbench.json.MCMetaDeserializer;
|
||||
import com.ticxo.modelengine.core.generator.processed.ProcessedBone;
|
||||
import it.unimi.dsi.fastutil.Pair;
|
||||
import java.io.File;
|
||||
import java.nio.file.Files;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.zip.CRC32;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3d;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class BlockbenchParser implements ModelParser {
|
||||
private final Gson gson = new GsonBuilder()
|
||||
.registerTypeAdapter(BlockbenchModel.class, new BlockbenchDeserializer())
|
||||
.registerTypeAdapter(BlueprintTexture.MCMeta.class, new MCMetaDeserializer())
|
||||
.create();
|
||||
private final Set<BlockbenchBehaviorParser> behaviorParsers = new LinkedHashSet<>();
|
||||
private final ModelGeneratorImpl generator;
|
||||
private final ConcurrentHashMap<String, BlockbenchParser.CachedBBFile> bbmodelCache = new ConcurrentHashMap<>();
|
||||
|
||||
public BlockbenchParser(ModelGeneratorImpl generator) {
|
||||
this.generator = generator;
|
||||
this.behaviorParsers.add(new DefaultBehaviorParser());
|
||||
ModelEngineAPI.callEvent(new RegisterBehaviorParserEvent(this.behaviorParsers));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean validateFile(File file) {
|
||||
return TFile.isExtension(file.getName(), "bbmodel");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Pair<ModelBlueprint, ModelAssets> generate(File file, ErrorCollector collector) throws Exception {
|
||||
String modelName = TFile.removeExtension(file.getName()).toLowerCase(Locale.ENGLISH);
|
||||
|
||||
try {
|
||||
String cacheKey = file.getAbsolutePath();
|
||||
long lastModified = file.lastModified();
|
||||
long size = file.length();
|
||||
BlockbenchParser.CachedBBFile cached = this.bbmodelCache.get(cacheKey);
|
||||
String json;
|
||||
if (cached != null && cached.lastModified == lastModified && cached.size == size) {
|
||||
json = cached.json;
|
||||
} else {
|
||||
byte[] bytes = Files.readAllBytes(file.toPath());
|
||||
CRC32 crc = new CRC32();
|
||||
crc.update(bytes);
|
||||
long hash = crc.getValue();
|
||||
json = new String(bytes);
|
||||
if (cached != null && cached.hash == hash) {
|
||||
this.bbmodelCache.put(cacheKey, new BlockbenchParser.CachedBBFile(lastModified, size, cached.hash, cached.json));
|
||||
} else {
|
||||
this.bbmodelCache.put(cacheKey, new BlockbenchParser.CachedBBFile(lastModified, size, hash, json));
|
||||
}
|
||||
}
|
||||
|
||||
BlockbenchModel blockbenchModel = (BlockbenchModel)this.gson.fromJson(json, BlockbenchModel.class);
|
||||
ModelBlueprint blueprint = new ModelBlueprint();
|
||||
blueprint.setName(modelName);
|
||||
this.populateBlueprint(blockbenchModel, blueprint, collector);
|
||||
blueprint.constructFlatBoneMap(collector);
|
||||
blueprint.cacheBoneBehaviors(collector);
|
||||
ModelAssets assets = new ModelAssets();
|
||||
assets.setName(modelName);
|
||||
this.populateAssets(blockbenchModel, blueprint, assets, collector);
|
||||
return Pair.of(blueprint, assets);
|
||||
} catch (Exception var15) {
|
||||
final Exception e = var15;
|
||||
collector.collect(new IError() {
|
||||
@Override
|
||||
public String getErrorMessage() {
|
||||
return "Error: " + e.getMessage();
|
||||
}
|
||||
|
||||
@Override
|
||||
public IError.Severity getSeverity() {
|
||||
return IError.Severity.ERROR;
|
||||
}
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void populateBlueprint(BlockbenchModel bbmodel, ModelBlueprint blueprint, ErrorCollector collector) {
|
||||
this.behaviorParsers.forEach(parser -> parser.processModel(collector, bbmodel, blueprint));
|
||||
HashMap<UUID, BlueprintBone> uuidToBone = new HashMap<>();
|
||||
bbmodel.getOutliner().forEach((uuidx, group) -> {
|
||||
BlueprintBone bone = this.readBone(collector, bbmodel, null, group, uuidToBone);
|
||||
if (blueprint.getBones().containsKey(bone.getName())) {
|
||||
new WarningDuplicateBoneName(bone.getName(), bone.getUuid()).log(collector);
|
||||
bone.setName(uuidx.toString());
|
||||
}
|
||||
|
||||
blueprint.getBones().put(bone.getName(), bone);
|
||||
uuidToBone.put(bone.getUuid(), bone);
|
||||
});
|
||||
|
||||
for (Entry<String, BlockbenchModel.Animation> entry : bbmodel.getAnimations().entrySet()) {
|
||||
String name = entry.getKey().toLowerCase(Locale.ENGLISH);
|
||||
BlockbenchModel.Animation value = entry.getValue();
|
||||
BlueprintAnimation blueprintAnimation = new BlueprintAnimation(blueprint, name);
|
||||
if (value.getEffects() != null) {
|
||||
Map<String, Map<Float, BlockbenchModel.Keyframe>> effectChannels = value.getEffects().getChannels();
|
||||
Map<Float, BlockbenchModel.Keyframe> script = effectChannels.get("timeline");
|
||||
if (script != null) {
|
||||
for (Entry<Float, BlockbenchModel.Keyframe> scriptEntry : script.entrySet()) {
|
||||
BlockbenchModel.Keyframe bbFrame = scriptEntry.getValue();
|
||||
ScriptKeyframe frame = blueprintAnimation.getGlobalTimeline().getKeyframe(scriptEntry.getKey(), KeyframeTypes.SCRIPT);
|
||||
|
||||
for (Map<String, String> data : bbFrame.getData_points()) {
|
||||
String instructions = data.getOrDefault("script", "");
|
||||
|
||||
for (String instruction : instructions.split("\n")) {
|
||||
frame.getScript().add(ScriptKeyframe.Script.from(instruction));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (Entry<UUID, BlockbenchModel.Animator> timelineEntry : value.getAnimators().entrySet()) {
|
||||
BlockbenchModel.Animator animator = timelineEntry.getValue();
|
||||
if (!animator.getChannels().isEmpty()) {
|
||||
boolean hasKeyframes = false;
|
||||
Timeline timeline = new Timeline(blueprintAnimation, animator.getRotation_global() != null && animator.getRotation_global());
|
||||
hasKeyframes |= putVectorKeyframes(animator, "position", timeline, KeyframeTypes.POSITION, 0.0625F, 0.0625F, -0.0625F);
|
||||
hasKeyframes |= putVectorKeyframes(
|
||||
animator, "rotation", timeline, KeyframeTypes.ROTATION, (float) (Math.PI / 180.0), (float) (-Math.PI / 180.0), (float) (-Math.PI / 180.0)
|
||||
);
|
||||
hasKeyframes |= putVectorKeyframes(animator, "scale", timeline, KeyframeTypes.SCALE, 1.0F, 1.0F, 1.0F);
|
||||
if (hasKeyframes) {
|
||||
UUID uuid = animator.getUuid();
|
||||
if (uuid != null) {
|
||||
blueprintAnimation.getTimelines().put(uuid, timeline);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
blueprintAnimation.setLength(value.getLength().floatValue());
|
||||
blueprintAnimation.setLoopMode(BlueprintAnimation.LoopMode.get(value.getLoop()));
|
||||
blueprintAnimation.setOverride(value.getOverride());
|
||||
blueprint.getAnimations().put(name, blueprintAnimation);
|
||||
}
|
||||
|
||||
String[] lines = bbmodel.getAnimation_variable_placeholders().split("\n");
|
||||
|
||||
for (String line : lines) {
|
||||
String[] pair = line.split("=", 2);
|
||||
if (pair.length >= 2) {
|
||||
blueprint.getAnimationsPlaceholders().put(pair[0], pair[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private BlueprintBone readBone(
|
||||
ErrorCollector collector, BlockbenchModel model, @Nullable BlueprintBone parent, BlockbenchModel.Group group, Map<UUID, BlueprintBone> uuidToBone
|
||||
) {
|
||||
BlueprintBone blueprintBone = new BlueprintBone();
|
||||
blueprintBone.setName(group.getName().toLowerCase(Locale.ENGLISH));
|
||||
blueprintBone.setUuid(group.getUuid());
|
||||
blueprintBone.setGlobalPosition(vector3f(group.getOrigin()).mul(-0.0625F, 0.0625F, -0.0625F));
|
||||
Vector3f rotation = vector3f(group.getRotation()).mul((float) (-Math.PI / 180.0), (float) (Math.PI / 180.0), (float) (-Math.PI / 180.0));
|
||||
blueprintBone.setLocalRotation(rotation);
|
||||
blueprintBone.getLocalQuaternion().rotateZYX(rotation.z, rotation.y, rotation.x);
|
||||
if (parent != null) {
|
||||
blueprintBone.setLocalPosition(blueprintBone.getGlobalPosition().sub(parent.getGlobalPosition(), new Vector3f()));
|
||||
Quaternionf boneQuaternion = new Quaternionf().rotationZYX(rotation.z, rotation.y, rotation.x);
|
||||
Quaternionf parentQuaternion = parent.getGlobalQuaternion();
|
||||
parentQuaternion.mul(boneQuaternion, boneQuaternion);
|
||||
Vector3f global = TMath.getEulerAnglesZYX(boneQuaternion, new Vector3f());
|
||||
blueprintBone.setGlobalRotation(new Vector3f(global.x, global.y, global.z));
|
||||
blueprintBone.setGlobalQuaternion(boneQuaternion);
|
||||
Vector3f rotatedLocal = blueprintBone.getLocalPosition().rotate(parentQuaternion, new Vector3f());
|
||||
blueprintBone.setRotatedGlobalPosition(rotatedLocal.add(parent.getRotatedGlobalPosition()));
|
||||
} else {
|
||||
blueprintBone.setLocalPosition(new Vector3f(blueprintBone.getGlobalPosition()));
|
||||
blueprintBone.setGlobalRotation(rotation);
|
||||
blueprintBone.setGlobalQuaternion(new Quaternionf(blueprintBone.getLocalQuaternion()));
|
||||
blueprintBone.setRotatedGlobalPosition(new Vector3f(blueprintBone.getGlobalPosition()));
|
||||
}
|
||||
|
||||
blueprintBone.setParent(parent);
|
||||
this.behaviorParsers.forEach(parser -> parser.processBone(collector, model, group, blueprintBone));
|
||||
|
||||
for (Entry<UUID, BlockbenchModel.Group> entry : group.getChildGroup().entrySet()) {
|
||||
BlueprintBone child = this.readBone(collector, model, blueprintBone, entry.getValue(), uuidToBone);
|
||||
if (blueprintBone.getChildren().containsKey(child.getName())) {
|
||||
new WarningDuplicateBoneName(child.getName(), child.getUuid()).log(collector);
|
||||
child.setName(child.getUuid().toString());
|
||||
}
|
||||
|
||||
blueprintBone.getChildren().put(child.getName(), child);
|
||||
}
|
||||
|
||||
for (UUID element : group.getElement()) {
|
||||
if (model.getElements().get(element) instanceof BlockbenchModel.AnimatableElement animatable) {
|
||||
BlueprintBone child = this.readElementAsBone(blueprintBone, animatable, uuidToBone);
|
||||
if (blueprintBone.getChildren().containsKey(child.getName())) {
|
||||
new WarningDuplicateBoneName(child.getName(), child.getUuid()).log(collector);
|
||||
child.setName(child.getUuid().toString());
|
||||
}
|
||||
|
||||
blueprintBone.getChildren().put(child.getName(), child);
|
||||
}
|
||||
}
|
||||
|
||||
uuidToBone.put(blueprintBone.getUuid(), blueprintBone);
|
||||
return blueprintBone;
|
||||
}
|
||||
|
||||
private BlueprintBone readElementAsBone(@Nullable BlueprintBone parent, BlockbenchModel.AnimatableElement element, Map<UUID, BlueprintBone> uuidToBone) {
|
||||
BlueprintBone blueprintBone = new BlueprintBone();
|
||||
blueprintBone.setName(element.getName().toLowerCase(Locale.ENGLISH));
|
||||
blueprintBone.setUuid(element.getUuid());
|
||||
blueprintBone.setGlobalPosition(vector3f(element.getOrigin()).mul(-0.0625F, 0.0625F, -0.0625F));
|
||||
Vector3f rotation = vector3f(element.getRotation()).mul((float) (-Math.PI / 180.0), (float) (Math.PI / 180.0), (float) (-Math.PI / 180.0));
|
||||
blueprintBone.setLocalRotation(rotation);
|
||||
blueprintBone.getLocalQuaternion().rotateZYX(rotation.z, rotation.y, rotation.x);
|
||||
if (parent != null) {
|
||||
blueprintBone.setLocalPosition(blueprintBone.getGlobalPosition().sub(parent.getGlobalPosition(), new Vector3f()));
|
||||
Quaternionf boneQuaternion = new Quaternionf().rotationZYX(rotation.z, rotation.y, rotation.x);
|
||||
Quaternionf parentQuaternion = parent.getGlobalQuaternion();
|
||||
parentQuaternion.mul(boneQuaternion, boneQuaternion);
|
||||
Vector3f global = TMath.getEulerAnglesZYX(boneQuaternion, new Vector3f());
|
||||
blueprintBone.setGlobalRotation(new Vector3f(global.x, global.y, global.z));
|
||||
blueprintBone.setGlobalQuaternion(boneQuaternion);
|
||||
Vector3f rotatedLocal = blueprintBone.getLocalPosition().rotate(parentQuaternion, new Vector3f());
|
||||
blueprintBone.setRotatedGlobalPosition(rotatedLocal.add(parent.getRotatedGlobalPosition()));
|
||||
} else {
|
||||
blueprintBone.setLocalPosition(new Vector3f(blueprintBone.getGlobalPosition()));
|
||||
blueprintBone.setGlobalRotation(rotation);
|
||||
blueprintBone.setGlobalQuaternion(new Quaternionf(blueprintBone.getLocalQuaternion()));
|
||||
blueprintBone.setRotatedGlobalPosition(new Vector3f(blueprintBone.getGlobalPosition()));
|
||||
}
|
||||
|
||||
blueprintBone.setParent(parent);
|
||||
uuidToBone.put(blueprintBone.getUuid(), blueprintBone);
|
||||
return blueprintBone;
|
||||
}
|
||||
|
||||
private void populateAssets(BlockbenchModel bbmodel, ModelBlueprint blueprint, ModelAssets assets, ErrorCollector collector) {
|
||||
this.populateTexture(bbmodel, blueprint, assets, collector);
|
||||
this.populateModel(bbmodel, blueprint, assets, collector);
|
||||
}
|
||||
|
||||
private void populateTexture(BlockbenchModel bbmodel, ModelBlueprint blueprint, ModelAssets assets, ErrorCollector collector) {
|
||||
Map<Integer, BlockbenchModel.Texture> textures = bbmodel.getTextures();
|
||||
|
||||
for (Entry<Integer, BlockbenchModel.Texture> entry : textures.entrySet()) {
|
||||
Integer id = entry.getKey();
|
||||
BlockbenchModel.Texture bbTexture = entry.getValue();
|
||||
BlueprintTexture.MCMeta meta;
|
||||
if (bbTexture.getRaw_mcmeta() == null) {
|
||||
meta = new BlueprintTexture.MCMeta();
|
||||
meta.setFrametime(bbTexture.getFrame_time());
|
||||
meta.setInterpolate(MiscUtils.orDef(false, bbTexture.getFrame_interpolate()) ? true : null);
|
||||
if (bbTexture.getFrame_order() != null && !bbTexture.getFrame_order().isBlank()) {
|
||||
for (String frame : bbTexture.getFrame_order().split(" ")) {
|
||||
meta.addFrame(TMath.tryParse(frame, 0));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
meta = (BlueprintTexture.MCMeta)this.gson.fromJson(bbTexture.getRaw_mcmeta(), BlueprintTexture.MCMeta.class);
|
||||
meta.setMustGenerate(true);
|
||||
}
|
||||
|
||||
BlueprintTexture texture = this.constructBlueprintTexture(id, bbmodel, bbTexture, meta, blueprint, collector);
|
||||
assets.getTextures().add(texture);
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private BlueprintTexture constructBlueprintTexture(
|
||||
Integer id, BlockbenchModel bbmodel, BlockbenchModel.Texture bbTexture, BlueprintTexture.MCMeta meta, ModelBlueprint blueprint, ErrorCollector collector
|
||||
) {
|
||||
BlueprintTexture texture = new BlueprintTexture();
|
||||
texture.setId(id);
|
||||
texture.setFrameWidth(MiscUtils.or(bbTexture.getUv_width(), bbmodel.getResolution().getWidth()));
|
||||
texture.setFrameHeight(MiscUtils.or(bbTexture.getUv_height(), bbmodel.getResolution().getHeight()));
|
||||
String namespace = bbTexture.getNamespace().isBlank() ? this.generator.getNamespace() : bbTexture.getNamespace();
|
||||
String folder = !namespace.equals(this.generator.getNamespace()) && !bbTexture.getFolder().isBlank()
|
||||
? bbTexture.getFolder().toLowerCase(Locale.ENGLISH)
|
||||
: this.generator.getTexturePath();
|
||||
String name = TFile.removeExtension(bbTexture.getName()).toLowerCase(Locale.ENGLISH);
|
||||
ResourceLocation location = new ResourceLocation(namespace, folder + "/" + name);
|
||||
if (!location.isValid()) {
|
||||
ResourceLocation correct = new ResourceLocation(
|
||||
this.generator.getNamespace(), this.generator.getTexturePath() + "/" + MiscUtils.generateUUIDFromString(name)
|
||||
);
|
||||
new WarnBadTexture(location, correct).log(collector);
|
||||
location = correct;
|
||||
}
|
||||
|
||||
Map<String, String> cache = this.generator.getTextureNameCache();
|
||||
if (Optional.ofNullable(cache.get(location.toString())).map(string -> !string.equals(bbTexture.getSource())).orElse(false)) {
|
||||
ResourceLocation correct = new ResourceLocation(
|
||||
this.generator.getNamespace(), this.generator.getTexturePath() + "/" + MiscUtils.generateUUIDFromString(blueprint.getName() + ":" + name)
|
||||
);
|
||||
new WarnDuplicateTexture(location, correct).log(collector);
|
||||
location = correct;
|
||||
}
|
||||
|
||||
this.generator.getTextureNameCache().put(location.toString(), bbTexture.getSource());
|
||||
texture.setPath(location);
|
||||
texture.setMcMeta(meta);
|
||||
texture.setSource(bbTexture.getSource());
|
||||
return texture;
|
||||
}
|
||||
|
||||
private void populateModel(BlockbenchModel bbmodel, ModelBlueprint blueprint, ModelAssets assets, ErrorCollector collector) {
|
||||
label67:
|
||||
for (Entry<String, BlueprintBone> entry : blueprint.getFlatMap().entrySet()) {
|
||||
String name = entry.getKey();
|
||||
BlueprintBone bone = entry.getValue();
|
||||
BlockbenchModel.Group bbBone = bbmodel.getGroup(bone.getUuid());
|
||||
if (bbBone != null && bbBone.isExport()) {
|
||||
for (BoneBehaviorType<?> behaviorType : bone.getCachedBehaviorProvider().keySet()) {
|
||||
if (behaviorType.isIgnoreCubes()) {
|
||||
continue label67;
|
||||
}
|
||||
}
|
||||
|
||||
Set<JavaItemModel> javaModels = null;
|
||||
int scale = 1;
|
||||
if (ModelEngineAPI.getConfigCache().isUseNewRotation()) {
|
||||
JavaItemModel model = this.createItemModel(bbmodel, bone, bbBone, assets);
|
||||
if (model != null) {
|
||||
javaModels = Set.of(model);
|
||||
scale = model.scaleToFit();
|
||||
}
|
||||
} else {
|
||||
ProcessedBone processedBone = this.process(bbmodel, bone, bbBone, assets, collector);
|
||||
javaModels = processedBone.getModels();
|
||||
scale = processedBone.getScale();
|
||||
}
|
||||
|
||||
if (javaModels != null && !javaModels.isEmpty()) {
|
||||
bone.setRenderer(true);
|
||||
bone.setScale(scale);
|
||||
ItemModelData.MultiModels multiModel = bone.getModelData().getMultiModels();
|
||||
|
||||
for (int i = 0; i < javaModels.size(); i++) {
|
||||
multiModel.addSubModel(new ItemModelData.SubModel(blueprint.getName() + ":" + (i == 0 ? bone.getName() : bone.getName() + "/" + i)));
|
||||
}
|
||||
|
||||
assets.getModels().put(name, javaModels);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private JavaItemModel createItemModel(BlockbenchModel model, BlueprintBone blueprintBone, BlockbenchModel.Group group, ModelAssets assets) {
|
||||
JavaItemModel javaItemModel = new JavaItemModel();
|
||||
javaItemModel.setName(blueprintBone.getName());
|
||||
boolean isRenderer = false;
|
||||
|
||||
for (UUID elementId : group.getElement()) {
|
||||
BlockbenchModel.Element bbElement = model.getElements().get(elementId);
|
||||
if (bbElement instanceof BlockbenchModel.Cube cube) {
|
||||
JavaItemModel.JavaElement element = new JavaItemModel.JavaElement();
|
||||
float[] boneOrigin = unwrap(group.getOrigin(), 3);
|
||||
float[] cubeOrigin = unwrap(cube.getOrigin(), 3);
|
||||
float[] from = unwrap(cube.getFrom(), 3);
|
||||
float[] to = unwrap(cube.getTo(), 3);
|
||||
element.from(boneOrigin, from, cube.getInflate());
|
||||
element.to(boneOrigin, to, cube.getInflate());
|
||||
JavaItemModel.JavaElement.RotationFree free = new JavaItemModel.JavaElement.RotationFree();
|
||||
free.origin(boneOrigin, cubeOrigin);
|
||||
free.rotation(unwrap(cube.getRotation(), 3));
|
||||
element.setRotation(free);
|
||||
|
||||
for (Entry<String, BlockbenchModel.Face> faceEntry : cube.getFaces().entrySet()) {
|
||||
String dir = faceEntry.getKey();
|
||||
BlockbenchModel.Face bbFace = faceEntry.getValue();
|
||||
if (!bbFace.isEmpty()) {
|
||||
int id = bbFace.getTexture();
|
||||
if (assets.getTextures().size() > id) {
|
||||
BlockbenchModel.Texture tex = model.getTextures().get(id);
|
||||
JavaItemModel.JavaElement.Face face = new JavaItemModel.JavaElement.Face();
|
||||
face.setRotation(bbFace.getRotation());
|
||||
face.uv(
|
||||
MiscUtils.or(tex.getUv_width(), model.getResolution().getWidth()),
|
||||
MiscUtils.or(tex.getUv_height(), model.getResolution().getHeight()),
|
||||
unwrap(bbFace.getUv(), 4)
|
||||
);
|
||||
face.setTexture("#" + id);
|
||||
element.getFaces().put(dir, face);
|
||||
Map<String, String> textures = javaItemModel.getTextures();
|
||||
textures.computeIfAbsent(String.valueOf(id), s -> assets.getTextures().get(id).getPath().toString());
|
||||
if (textures.size() == 1) {
|
||||
textures.computeIfAbsent("particle", s -> "#" + id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!element.getFaces().isEmpty()) {
|
||||
isRenderer = true;
|
||||
javaItemModel.addElement(element);
|
||||
}
|
||||
|
||||
if (cube.isTranslucent()) {
|
||||
blueprintBone.getModelData().setTranslucent(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return isRenderer ? javaItemModel : null;
|
||||
}
|
||||
|
||||
private ProcessedBone process(BlockbenchModel model, BlueprintBone blueprintBone, BlockbenchModel.Group group, ModelAssets assets, ErrorCollector collector) {
|
||||
ProcessedBone bone = new ProcessedBone(blueprintBone.getName(), vector3f(group.getOrigin()), vector3f(group.getRotation()));
|
||||
|
||||
for (UUID uuid : group.getElement()) {
|
||||
if (model.getElements().get(uuid) instanceof BlockbenchModel.Cube cube) {
|
||||
Map<Direction, ProcessedBone.Face> faces = new HashMap<>();
|
||||
|
||||
for (Entry<String, BlockbenchModel.Face> faceEntry : cube.getFaces().entrySet()) {
|
||||
BlockbenchModel.Face face = faceEntry.getValue();
|
||||
if (!face.isEmpty()) {
|
||||
Float[] faceUV = face.getUv();
|
||||
ProcessedBone.UV uv = new ProcessedBone.UV(
|
||||
faceUV[0] == null ? 0.0F : faceUV[0],
|
||||
faceUV[1] == null ? 0.0F : faceUV[1],
|
||||
faceUV[2] == null ? 0.0F : faceUV[2],
|
||||
faceUV[3] == null ? 0.0F : faceUV[3],
|
||||
face.getRotation() == null ? 0 : face.getRotation()
|
||||
);
|
||||
ProcessedBone.Face procFace = new ProcessedBone.Face(uv, face.getTexture());
|
||||
faces.put(Direction.valueOf(faceEntry.getKey().toUpperCase(Locale.ENGLISH)), procFace);
|
||||
}
|
||||
}
|
||||
|
||||
if (!faces.isEmpty()) {
|
||||
ProcessedBone.Cube procCube = new ProcessedBone.Cube(
|
||||
cube.getName(),
|
||||
vector3d(cube.getOrigin()).sub(bone.getBoneOrigin()),
|
||||
vector3d(cube.getRotation()),
|
||||
vector3d(cube.getFrom()).sub(bone.getBoneOrigin()),
|
||||
vector3d(cube.getTo()).sub(bone.getBoneOrigin()),
|
||||
faces,
|
||||
cube.getInflate() == null ? 0.0F : cube.getInflate()
|
||||
);
|
||||
bone.getCubes().add(procCube);
|
||||
if (cube.isTranslucent()) {
|
||||
blueprintBone.getModelData().setTranslucent(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bone.splitModels(model, assets);
|
||||
return bone;
|
||||
}
|
||||
|
||||
private static Vector3f vector3f(@Nullable Float[] vec) {
|
||||
return vec == null ? new Vector3f() : new Vector3f(vec[0] == null ? 0.0F : vec[0], vec[1] == null ? 0.0F : vec[1], vec[2] == null ? 0.0F : vec[2]);
|
||||
}
|
||||
|
||||
private static Vector3d vector3d(@Nullable Float[] vec) {
|
||||
return vec == null
|
||||
? new Vector3d()
|
||||
: new Vector3d(vec[0] == null ? 0.0 : vec[0].floatValue(), vec[1] == null ? 0.0 : vec[1].floatValue(), vec[2] == null ? 0.0 : vec[2].floatValue());
|
||||
}
|
||||
|
||||
private static float[] unwrap(Float[] arr, int length) {
|
||||
if (arr == null) {
|
||||
return new float[length];
|
||||
} else {
|
||||
float[] a = new float[arr.length];
|
||||
|
||||
for (int i = 0; i < arr.length; i++) {
|
||||
if (arr[i] != null) {
|
||||
a[i] = arr[i];
|
||||
}
|
||||
}
|
||||
|
||||
return a;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean putVectorKeyframes(
|
||||
BlockbenchModel.Animator animator,
|
||||
String channel,
|
||||
Timeline timeline,
|
||||
KeyframeType<VectorKeyframe, Vector3f> keyframeType,
|
||||
float scaleX,
|
||||
float scaleY,
|
||||
float scaleZ
|
||||
) {
|
||||
Map<Float, BlockbenchModel.Keyframe> frames = animator.getChannels().get(channel);
|
||||
if (frames != null && !frames.isEmpty()) {
|
||||
for (Entry<Float, BlockbenchModel.Keyframe> entry : frames.entrySet()) {
|
||||
Float time = entry.getKey();
|
||||
BlockbenchModel.Keyframe keyframe = entry.getValue();
|
||||
VectorKeyframe vectorKeyframe = timeline.getKeyframe(time, keyframeType);
|
||||
if (!keyframe.getData_points().isEmpty()) {
|
||||
KeyframeReaderRegistry reader = ModelEngineAPI.getAPI().getKeyframeReaderRegistry();
|
||||
Map<String, String> pre = keyframe.getData_points().get(0);
|
||||
vectorKeyframe.setXFactor(scaleX)
|
||||
.setYFactor(scaleY)
|
||||
.setZFactor(scaleZ)
|
||||
.setX(reader.tryParse(pre.getOrDefault("x", "0")))
|
||||
.setY(reader.tryParse(pre.getOrDefault("y", "0")))
|
||||
.setZ(reader.tryParse(pre.getOrDefault("z", "0")));
|
||||
if (keyframe.getData_points().size() >= 2) {
|
||||
Map<String, String> post = keyframe.getData_points().get(1);
|
||||
vectorKeyframe.setDiscontinuous(true);
|
||||
vectorKeyframe.setPostX(reader.tryParse(post.getOrDefault("x", "0")))
|
||||
.setPostY(reader.tryParse(post.getOrDefault("y", "0")))
|
||||
.setPostZ(reader.tryParse(post.getOrDefault("z", "0")));
|
||||
}
|
||||
}
|
||||
|
||||
vectorKeyframe.setInterpolation(keyframe.getInterpolation());
|
||||
if (vectorKeyframe.isBezier()) {
|
||||
float[] leftTime = unwrap(keyframe.getBezier_left_time(), 3);
|
||||
float[] leftValue = unwrap(keyframe.getBezier_left_value(), 3);
|
||||
float[] rightTime = unwrap(keyframe.getBezier_right_time(), 3);
|
||||
float[] rightValue = unwrap(keyframe.getBezier_right_value(), 3);
|
||||
vectorKeyframe.setBezierLeftTime(leftTime[0], leftTime[1], leftTime[2]);
|
||||
vectorKeyframe.setBezierLeftValue(leftValue[0], leftValue[1], leftValue[2]);
|
||||
vectorKeyframe.setBezierRightTime(rightTime[0], rightTime[1], rightTime[2]);
|
||||
vectorKeyframe.setBezierRightValue(rightValue[0], rightValue[1], rightValue[2]);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private record CachedBBFile(long lastModified, long size, long hash, String json) {
|
||||
}
|
||||
}
|
||||
+371
@@ -0,0 +1,371 @@
|
||||
package com.ticxo.modelengine.core.generator.parser.blockbench.json;
|
||||
|
||||
import com.ticxo.modelengine.api.entity.Hitbox;
|
||||
import com.ticxo.modelengine.api.error.ErrorCollector;
|
||||
import com.ticxo.modelengine.api.error.IError;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchBehaviorParser;
|
||||
import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchModel;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes;
|
||||
import com.ticxo.modelengine.api.model.bone.type.PlayerLimb;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Predicate;
|
||||
import org.bukkit.entity.ItemDisplay.ItemDisplayTransform;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class DefaultBehaviorParser implements BlockbenchBehaviorParser {
|
||||
@Override
|
||||
public void processModel(ErrorCollector collector, BlockbenchModel model, ModelBlueprint blueprint) {
|
||||
this.searchBone(model, "hitbox", bone -> {
|
||||
Hitbox mainHitbox = this.readHitbox(collector, model, bone);
|
||||
if (mainHitbox == null) {
|
||||
return false;
|
||||
} else {
|
||||
blueprint.setMainHitbox(mainHitbox);
|
||||
return true;
|
||||
}
|
||||
}, () -> IError.NO_HITBOX.log(collector));
|
||||
this.searchBone(model, "shadow", bone -> {
|
||||
float radius = this.readShadow(model, bone);
|
||||
if (radius < 1.0E-5F) {
|
||||
return false;
|
||||
} else {
|
||||
blueprint.setShadowRadius(radius);
|
||||
return true;
|
||||
}
|
||||
}, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processBone(ErrorCollector collector, BlockbenchModel model, BlockbenchModel.Group group, BlueprintBone bone) {
|
||||
String name = this.readOptions(model, group, bone);
|
||||
bone.setName(name);
|
||||
}
|
||||
|
||||
private void searchBone(BlockbenchModel model, String name, Predicate<BlockbenchModel.Group> consumer, Runnable missing) {
|
||||
BlockbenchModel.Group group = model.getGroup(name);
|
||||
if (group != null && consumer.test(group)) {
|
||||
model.removeGroup(group);
|
||||
} else if (missing != null) {
|
||||
missing.run();
|
||||
}
|
||||
}
|
||||
|
||||
private Hitbox readHitbox(ErrorCollector collector, BlockbenchModel model, BlockbenchModel.Group hitbox) {
|
||||
Float[] boneOrigin = hitbox.getOrigin();
|
||||
|
||||
for (UUID uuid : hitbox.getElement()) {
|
||||
BlockbenchModel.Element element = model.getElements().get(uuid);
|
||||
if (element instanceof BlockbenchModel.Cube cube) {
|
||||
Float[] cubeOrigin = cube.getOrigin();
|
||||
float eyeHeight = boneOrigin[1] <= 0.0F ? cubeOrigin[1] : boneOrigin[1];
|
||||
if (eyeHeight <= 0.0F) {
|
||||
IError.BAD_EYE_HEIGHT.log(collector);
|
||||
}
|
||||
|
||||
return new Hitbox(cube.width() * 0.0625F, cube.height() * 0.0625F, cube.depth() * 0.0625F, eyeHeight * 0.0625F);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private float readShadow(BlockbenchModel model, BlockbenchModel.Group shadow) {
|
||||
for (UUID uuid : shadow.getElement()) {
|
||||
BlockbenchModel.Element element = model.getElements().get(uuid);
|
||||
if (element instanceof BlockbenchModel.Cube cube) {
|
||||
return Math.max(cube.width(), cube.depth()) * 0.03125F;
|
||||
}
|
||||
}
|
||||
|
||||
return -1.0F;
|
||||
}
|
||||
|
||||
private String readOptions(BlockbenchModel model, BlockbenchModel.Group group, BlueprintBone bone) {
|
||||
String name = bone.getName();
|
||||
Map<String, Map<String, Object>> options = bone.getBehaviors();
|
||||
if (name.startsWith("h_")) {
|
||||
name = name.substring(2);
|
||||
options.put(BoneBehaviorTypes.HEAD.getId(), new HashMap<>());
|
||||
} else if (name.startsWith("hi_")) {
|
||||
name = name.substring(3);
|
||||
options.put(BoneBehaviorTypes.HEAD.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("inherited", true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (name.equals("mount")) {
|
||||
options.put(BoneBehaviorTypes.MOUNT.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("driver", true);
|
||||
}
|
||||
});
|
||||
return name;
|
||||
} else {
|
||||
boolean isOBB = name.startsWith("ob_");
|
||||
if (!isOBB && !name.startsWith("b_")) {
|
||||
String[] split = name.split("_(?![^\\[]*\\])");
|
||||
if (!group.getElement().isEmpty()) {
|
||||
for (int i = 0; i < split.length; i++) {
|
||||
String tag = split[i];
|
||||
String[] paramSplit = tag.split("\\[|;|\\]");
|
||||
tag = paramSplit[0];
|
||||
final HashMap<String, String> paramMap = new HashMap<>();
|
||||
|
||||
for (int p = 1; p < paramSplit.length; p++) {
|
||||
String[] pair = paramSplit[p].split("=", 2);
|
||||
if (pair.length == 2) {
|
||||
paramMap.put(pair[0], pair[1]);
|
||||
}
|
||||
}
|
||||
|
||||
switch (tag) {
|
||||
case "phead":
|
||||
options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("limb", PlayerLimb.Limb.HEAD);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "prarm":
|
||||
options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("limb", PlayerLimb.Limb.RIGHT_ARM);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "plarm":
|
||||
options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("limb", PlayerLimb.Limb.LEFT_ARM);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "pbody":
|
||||
options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("limb", PlayerLimb.Limb.BODY);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "prleg":
|
||||
options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("limb", PlayerLimb.Limb.RIGHT_LEG);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "plleg":
|
||||
options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("limb", PlayerLimb.Limb.LEFT_LEG);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "limb":
|
||||
options.put(BoneBehaviorTypes.USER_LIMB.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("type", paramMap.get("type"));
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "tl":
|
||||
options.put(BoneBehaviorTypes.TAIL.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("back_pivot", true);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "tlf":
|
||||
options.put(BoneBehaviorTypes.TAIL.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("back_pivot", false);
|
||||
}
|
||||
});
|
||||
break;
|
||||
default:
|
||||
StringBuilder builder = new StringBuilder(tag);
|
||||
|
||||
for (int j = i + 1; j < split.length; j++) {
|
||||
builder.append("_").append(split[j]);
|
||||
}
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
|
||||
return name;
|
||||
} else {
|
||||
for (int i = 0; i < split.length; i++) {
|
||||
String tag = split[i];
|
||||
String[] paramSplit = tag.split("\\[|;|\\]");
|
||||
tag = paramSplit[0];
|
||||
final HashMap<String, String> paramMap = new HashMap<>();
|
||||
|
||||
for (int px = 1; px < paramSplit.length; px++) {
|
||||
String[] pair = paramSplit[px].split("=", 2);
|
||||
if (pair.length == 2) {
|
||||
paramMap.put(pair[0], pair[1]);
|
||||
}
|
||||
}
|
||||
|
||||
switch (tag) {
|
||||
case "g":
|
||||
options.put(BoneBehaviorTypes.GHOST.getId(), new HashMap<>());
|
||||
break;
|
||||
case "tag":
|
||||
options.put(BoneBehaviorTypes.NAMETAG.getId(), new HashMap<>());
|
||||
break;
|
||||
case "p":
|
||||
options.put(BoneBehaviorTypes.MOUNT.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("driver", false);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "ir":
|
||||
options.put(BoneBehaviorTypes.ITEM.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("display", ItemDisplayTransform.THIRDPERSON_RIGHTHAND);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "il":
|
||||
options.put(BoneBehaviorTypes.ITEM.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("display", ItemDisplayTransform.THIRDPERSON_LEFTHAND);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "ih":
|
||||
options.put(BoneBehaviorTypes.ITEM.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("display", ItemDisplayTransform.HEAD);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "l":
|
||||
options.put(BoneBehaviorTypes.LEASH.getId(), new HashMap<>());
|
||||
break;
|
||||
case "phead":
|
||||
options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("limb", PlayerLimb.Limb.HEAD);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "prarm":
|
||||
options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("limb", PlayerLimb.Limb.RIGHT_ARM);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "plarm":
|
||||
options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("limb", PlayerLimb.Limb.LEFT_ARM);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "pbody":
|
||||
options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("limb", PlayerLimb.Limb.BODY);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "prleg":
|
||||
options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("limb", PlayerLimb.Limb.RIGHT_LEG);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "plleg":
|
||||
options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("limb", PlayerLimb.Limb.LEFT_LEG);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "limb":
|
||||
options.put(BoneBehaviorTypes.USER_LIMB.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("type", paramMap.get("type"));
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "seg":
|
||||
options.put(BoneBehaviorTypes.SEGMENT.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("back_pivot", true);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "segf":
|
||||
options.put(BoneBehaviorTypes.SEGMENT.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("back_pivot", false);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "tl":
|
||||
options.put(BoneBehaviorTypes.TAIL.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("back_pivot", true);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "tlf":
|
||||
options.put(BoneBehaviorTypes.TAIL.getId(), new HashMap<String, Object>() {
|
||||
{
|
||||
this.put("back_pivot", false);
|
||||
}
|
||||
});
|
||||
break;
|
||||
default:
|
||||
StringBuilder builder = new StringBuilder(tag);
|
||||
|
||||
for (int j = i + 1; j < split.length; j++) {
|
||||
builder.append("_").append(split[j]);
|
||||
}
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
} else {
|
||||
HashMap<String, Object> map = new HashMap<>();
|
||||
if (isOBB) {
|
||||
map.put("obb", true);
|
||||
}
|
||||
|
||||
for (UUID uuid : group.getElement()) {
|
||||
BlockbenchModel.Element element = model.getElements().get(uuid);
|
||||
if (element instanceof BlockbenchModel.Cube cube) {
|
||||
map.put("dimension", new Hitbox(cube.width() * 0.0625, cube.height() * 0.0625, cube.depth() * 0.0625, 0.0));
|
||||
Float[] from = cube.getFrom();
|
||||
Float[] to = cube.getTo();
|
||||
map.put("origin", new Vector3f((from[0] + to[0]) * -0.03125F, (from[1] + to[1]) * 0.03125F, (from[2] + to[2]) * -0.03125F));
|
||||
Float[] rotation = cube.getRotation();
|
||||
map.put("rotation", rotation != null ? new Vector3f(-rotation[0], rotation[1], -rotation[2]).mul((float) (Math.PI / 180.0)) : new Vector3f());
|
||||
Float[] origin = cube.getOrigin();
|
||||
map.put("cube_origin", new Vector3f(origin[0] * -0.0625F, origin[1] * 0.0625F, origin[2] * -0.0625F));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
options.put(BoneBehaviorTypes.SUB_HITBOX.getId(), map);
|
||||
return name;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.ticxo.modelengine.core.generator.parser.blockbench.json;
|
||||
|
||||
import com.google.gson.JsonDeserializationContext;
|
||||
import com.google.gson.JsonDeserializer;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.ticxo.modelengine.api.generator.assets.BlueprintTexture;
|
||||
import com.ticxo.modelengine.api.utils.data.GSONUtils;
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
public class MCMetaDeserializer implements JsonDeserializer<BlueprintTexture.MCMeta> {
|
||||
public BlueprintTexture.MCMeta deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
|
||||
JsonObject animation = GSONUtils.get(jsonElement, "animation", JsonElement::getAsJsonObject);
|
||||
if (animation == null) {
|
||||
return null;
|
||||
} else {
|
||||
BlueprintTexture.MCMeta meta = new BlueprintTexture.MCMeta();
|
||||
meta.setInterpolate(GSONUtils.get(animation, "interpolate", JsonElement::getAsBoolean));
|
||||
meta.setWidth(GSONUtils.get(animation, "width", JsonElement::getAsInt));
|
||||
meta.setHeight(GSONUtils.get(animation, "height", JsonElement::getAsInt));
|
||||
meta.setFrametime(GSONUtils.get(animation, "frametime", JsonElement::getAsInt));
|
||||
GSONUtils.ifArray(animation, "frames", element -> {
|
||||
if (element.isJsonPrimitive()) {
|
||||
meta.addFrame(element.getAsInt());
|
||||
} else if (element.isJsonObject()) {
|
||||
JsonObject frameObject = element.getAsJsonObject();
|
||||
Integer index = GSONUtils.get(frameObject, "index", JsonElement::getAsInt);
|
||||
Integer time = GSONUtils.get(frameObject, "time", JsonElement::getAsInt);
|
||||
if (index != null && time != null) {
|
||||
meta.addFrame(index, time);
|
||||
}
|
||||
}
|
||||
});
|
||||
return meta;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package com.ticxo.modelengine.core.generator.processed;
|
||||
|
||||
import com.ticxo.modelengine.api.generator.assets.JavaItemModel;
|
||||
import com.ticxo.modelengine.api.generator.assets.ModelAssets;
|
||||
import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchModel;
|
||||
import com.ticxo.modelengine.api.utils.math.Direction;
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import com.ticxo.modelengine.core.generator.util.ItemGroup;
|
||||
import com.ticxo.modelengine.core.generator.util.RotationSolver;
|
||||
import java.text.NumberFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.joml.Quaterniond;
|
||||
import org.joml.Vector3d;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class ProcessedBone {
|
||||
private final String name;
|
||||
private final Vector3f boneOrigin;
|
||||
private final Vector3f rotation;
|
||||
private final Set<ProcessedBone.Cube> cubes = new LinkedHashSet<>();
|
||||
private final Set<ItemGroup> groups = new LinkedHashSet<>();
|
||||
private final Set<JavaItemModel> models = new LinkedHashSet<>();
|
||||
private int scale;
|
||||
|
||||
public void splitModels(BlockbenchModel model, ModelAssets assets) {
|
||||
RotationSolver.solve(this.groups, this.cubes);
|
||||
float maxDistToOrigin = 0.0F;
|
||||
|
||||
for (ItemGroup group : this.groups) {
|
||||
JavaItemModel jiModel = group.toJavaItemModel(this.name, model, assets);
|
||||
maxDistToOrigin = Math.max(jiModel.getMaxDistToOrigin(), maxDistToOrigin);
|
||||
this.models.add(jiModel);
|
||||
}
|
||||
|
||||
for (JavaItemModel m : this.models) {
|
||||
m.setMaxDistToOrigin(maxDistToOrigin);
|
||||
this.scale = m.scaleToFit();
|
||||
}
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public Vector3f getBoneOrigin() {
|
||||
return this.boneOrigin;
|
||||
}
|
||||
|
||||
public Vector3f getRotation() {
|
||||
return this.rotation;
|
||||
}
|
||||
|
||||
public Set<ProcessedBone.Cube> getCubes() {
|
||||
return this.cubes;
|
||||
}
|
||||
|
||||
public Set<ItemGroup> getGroups() {
|
||||
return this.groups;
|
||||
}
|
||||
|
||||
public Set<JavaItemModel> getModels() {
|
||||
return this.models;
|
||||
}
|
||||
|
||||
public int getScale() {
|
||||
return this.scale;
|
||||
}
|
||||
|
||||
public ProcessedBone(String name, Vector3f boneOrigin, Vector3f rotation) {
|
||||
this.name = name;
|
||||
this.boneOrigin = boneOrigin;
|
||||
this.rotation = rotation;
|
||||
}
|
||||
|
||||
public static class Cube {
|
||||
private final String name;
|
||||
private final Vector3d origin;
|
||||
private final Vector3d rotation;
|
||||
private final Quaterniond quaternion;
|
||||
private final Vector3d from;
|
||||
private final Vector3d to;
|
||||
private final Map<Direction, ProcessedBone.Face> faces;
|
||||
private final float inflate;
|
||||
|
||||
public Cube(String name, Vector3d origin, Vector3d rotation, Vector3d from, Vector3d to, Map<Direction, ProcessedBone.Face> faces, float inflate) {
|
||||
this.name = name;
|
||||
this.origin = new Vector3d(origin);
|
||||
this.rotation = new Vector3d(rotation);
|
||||
this.quaternion = TMath.fromEulerZYX(rotation);
|
||||
this.from = new Vector3d(from);
|
||||
this.to = new Vector3d(to);
|
||||
this.faces = faces;
|
||||
this.inflate = inflate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.name + ": " + this.rotation.toString(NumberFormat.getInstance());
|
||||
}
|
||||
|
||||
public List<Vector3d> getCorners() {
|
||||
return new ArrayList<Vector3d>() {
|
||||
{
|
||||
this.add(new Vector3d(Cube.this.from.x, Cube.this.from.y, Cube.this.from.z));
|
||||
this.add(new Vector3d(Cube.this.from.x, Cube.this.from.y, Cube.this.to.z));
|
||||
this.add(new Vector3d(Cube.this.from.x, Cube.this.to.y, Cube.this.from.z));
|
||||
this.add(new Vector3d(Cube.this.from.x, Cube.this.to.y, Cube.this.to.z));
|
||||
this.add(new Vector3d(Cube.this.to.x, Cube.this.from.y, Cube.this.from.z));
|
||||
this.add(new Vector3d(Cube.this.to.x, Cube.this.from.y, Cube.this.to.z));
|
||||
this.add(new Vector3d(Cube.this.to.x, Cube.this.to.y, Cube.this.from.z));
|
||||
this.add(new Vector3d(Cube.this.to.x, Cube.this.to.y, Cube.this.to.z));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public void rotate(Quaterniond rot) {
|
||||
this.from.sub(this.origin);
|
||||
this.to.sub(this.origin);
|
||||
this.origin.rotate(rot);
|
||||
this.quaternion.premul(rot);
|
||||
this.rotation.set(TMath.fixEuler(TMath.toEulerZYX(this.quaternion)));
|
||||
this.from.add(this.origin);
|
||||
this.to.add(this.origin);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public JavaItemModel.JavaElement.RotationSingle rotation() {
|
||||
int zeros = 0;
|
||||
float[] origin = TMath.unwrap(this.origin);
|
||||
float[] rotation = TMath.unwrap(this.rotation);
|
||||
|
||||
for (float angle : rotation) {
|
||||
zeros += angle == 0.0F ? 1 : 0;
|
||||
}
|
||||
|
||||
if (zeros == 3) {
|
||||
return null;
|
||||
} else {
|
||||
JavaItemModel.JavaElement.RotationSingle javaRotation = new JavaItemModel.JavaElement.RotationSingle();
|
||||
int i = TMath.absMax(rotation[0], rotation[1], rotation[2]);
|
||||
|
||||
javaRotation.setAxis(switch (i) {
|
||||
case 1 -> "y";
|
||||
case 2 -> "z";
|
||||
default -> "x";
|
||||
});
|
||||
float angle = Math.round(rotation[i] / 22.5F) * 22.5F;
|
||||
javaRotation.setAngle(angle);
|
||||
javaRotation.origin(origin);
|
||||
return javaRotation;
|
||||
}
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public Vector3d getOrigin() {
|
||||
return this.origin;
|
||||
}
|
||||
|
||||
public Vector3d getRotation() {
|
||||
return this.rotation;
|
||||
}
|
||||
|
||||
public Quaterniond getQuaternion() {
|
||||
return this.quaternion;
|
||||
}
|
||||
|
||||
public Vector3d getFrom() {
|
||||
return this.from;
|
||||
}
|
||||
|
||||
public Vector3d getTo() {
|
||||
return this.to;
|
||||
}
|
||||
|
||||
public Map<Direction, ProcessedBone.Face> getFaces() {
|
||||
return this.faces;
|
||||
}
|
||||
|
||||
public float getInflate() {
|
||||
return this.inflate;
|
||||
}
|
||||
}
|
||||
|
||||
public record Face(ProcessedBone.UV uv, int texture) {
|
||||
public boolean isEmpty() {
|
||||
return TMath.isSimilar(this.uv.u1(), this.uv.u2()) || TMath.isSimilar(this.uv.v1, this.uv.v2);
|
||||
}
|
||||
}
|
||||
|
||||
public record UV(float u1, float v1, float u2, float v2, int rotation) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.ticxo.modelengine.core.generator.skin;
|
||||
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
public record FaceMapper(String sourceTexture, float[] from, FaceMapper.Face to) {
|
||||
public float[] getSourcePixel(float x, float y) {
|
||||
float fx1 = this.from[0];
|
||||
float fy1 = this.from[1];
|
||||
float fx2 = this.from[2];
|
||||
float fy2 = this.from[3];
|
||||
float tx1 = this.to.uv[0];
|
||||
float ty1 = this.to.uv[1];
|
||||
float tx2 = this.to.uv[2];
|
||||
float ty2 = this.to.uv[3];
|
||||
float txr = TMath.invLerp(tx1, tx2, x);
|
||||
float tyr = TMath.invLerp(ty1, ty2, y);
|
||||
return new float[]{TMath.lerp(fx1, fx2, txr), TMath.lerp(fy1, fy2, tyr)};
|
||||
}
|
||||
|
||||
public static enum Face {
|
||||
NORTH(new int[]{8, 8, 16, 16}),
|
||||
EAST(new int[]{0, 8, 8, 16}),
|
||||
SOUTH(new int[]{24, 8, 32, 16}),
|
||||
WEST(new int[]{16, 8, 24, 16}),
|
||||
UP(new int[]{16, 8, 8, 0}),
|
||||
DOWN(new int[]{24, 0, 16, 8}),
|
||||
NORTH_HAT(new int[]{40, 8, 48, 16}),
|
||||
EAST_HAT(new int[]{32, 8, 40, 16}),
|
||||
SOUTH_HAT(new int[]{56, 8, 64, 16}),
|
||||
WEST_HAT(new int[]{48, 8, 56, 16}),
|
||||
UP_HAT(new int[]{48, 8, 40, 0}),
|
||||
DOWN_HAT(new int[]{56, 0, 48, 8});
|
||||
|
||||
private final int[] uv;
|
||||
|
||||
public void forPixel(BiConsumer<Integer, Integer> consumer) {
|
||||
for (int x = Math.min(this.uv[0], this.uv[2]); x < Math.max(this.uv[0], this.uv[2]); x++) {
|
||||
for (int y = Math.min(this.uv[1], this.uv[3]); y < Math.max(this.uv[1], this.uv[3]); y++) {
|
||||
consumer.accept(x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static FaceMapper.Face getFace(String val, boolean hat) {
|
||||
return switch (val) {
|
||||
case "north" -> hat ? NORTH_HAT : NORTH;
|
||||
case "east" -> hat ? EAST_HAT : EAST;
|
||||
case "south" -> hat ? SOUTH_HAT : SOUTH;
|
||||
case "west" -> hat ? WEST_HAT : WEST;
|
||||
case "up" -> hat ? UP_HAT : UP;
|
||||
case "down" -> hat ? DOWN_HAT : DOWN;
|
||||
default -> throw new IllegalStateException("Unexpected value: " + val);
|
||||
};
|
||||
}
|
||||
|
||||
private Face(int[] uv) {
|
||||
this.uv = uv;
|
||||
}
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package com.ticxo.modelengine.core.generator.skin;
|
||||
|
||||
import com.ticxo.modelengine.api.generator.skin.SkinGeneratorService;
|
||||
import com.ticxo.modelengine.api.utils.config.ConfigProperty;
|
||||
import com.ticxo.modelengine.api.utils.logger.TLogger;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.logging.Logger;
|
||||
import org.mineskin.JsoupRequestHandler;
|
||||
import org.mineskin.MineSkinClient;
|
||||
import org.mineskin.data.Visibility;
|
||||
import org.mineskin.exception.MineSkinRequestException;
|
||||
import org.mineskin.options.GenerateQueueOptions;
|
||||
import org.mineskin.request.GenerateRequest;
|
||||
import org.mineskin.response.MineSkinResponse;
|
||||
|
||||
public class MineSkinGeneratorService implements SkinGeneratorService {
|
||||
private boolean enabled;
|
||||
private MineSkinClient client;
|
||||
|
||||
@Override
|
||||
public void onReload() {
|
||||
String key = ConfigProperty.MINESKIN_API_KEY.getString();
|
||||
if (key != null && !key.isBlank()) {
|
||||
this.client = MineSkinClient.builder()
|
||||
.requestHandler(JsoupRequestHandler::new)
|
||||
.userAgent("ModelEngine/R4.0.9")
|
||||
.apiKey(key)
|
||||
.generateQueueOptions(GenerateQueueOptions.createAuto())
|
||||
.build();
|
||||
quietenClientLogger();
|
||||
this.enabled = true;
|
||||
} else {
|
||||
TLogger.warn("Unable to activate MineSkin skin generation: Empty API Key");
|
||||
this.enabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void quietenClientLogger() {
|
||||
Logger.getLogger("org.mineskin.MineSkinClient").setFilter(record -> {
|
||||
Throwable thrown = record.getThrown();
|
||||
if (thrown == null) {
|
||||
return true;
|
||||
} else {
|
||||
TLogger.warn("Failed to communicate with MineSkin: " + summarize(thrown));
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static String summarize(Throwable thrown) {
|
||||
for (Throwable cause = thrown; cause != null; cause = cause.getCause()) {
|
||||
if (cause instanceof MineSkinRequestException requestException) {
|
||||
MineSkinResponse<?> response = requestException.getResponse();
|
||||
return response != null ? "HTTP " + response.getStatus() + " - " + requestException.getMessage() : requestException.getMessage();
|
||||
}
|
||||
|
||||
if (cause.getCause() == cause) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Throwable root = thrown;
|
||||
|
||||
while (root.getCause() != null && root.getCause() != root) {
|
||||
root = root.getCause();
|
||||
}
|
||||
|
||||
String message = root.getMessage();
|
||||
return root.getClass().getSimpleName() + (message != null ? ": " + firstLine(message) : "");
|
||||
}
|
||||
|
||||
private static String firstLine(String message) {
|
||||
int newline = message.indexOf(10);
|
||||
String line = newline < 0 ? message : message.substring(0, newline);
|
||||
return line.length() > 120 ? line.substring(0, 120) + "..." : line;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<String> generate(byte[] rawImage) {
|
||||
GenerateRequest request = GenerateRequest.upload(new ByteArrayInputStream(rawImage)).visibility(Visibility.UNLISTED);
|
||||
return this.client
|
||||
.queue()
|
||||
.submit(request)
|
||||
.thenCompose(queueResponse -> queueResponse.getJob().waitForCompletion(this.client))
|
||||
.thenCompose(jobResponse -> jobResponse.getOrLoadSkin(this.client))
|
||||
.thenApply(skinInfo -> skinInfo.texture().url().skin());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return this.enabled;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.ticxo.modelengine.core.generator.skin;
|
||||
|
||||
import com.ticxo.modelengine.api.generator.skin.LimbData;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
public class PlayerMapper {
|
||||
private final Map<String, LimbData> limbData = new HashMap<>();
|
||||
private final Map<String, BufferedImage> textureReference = new HashMap<>();
|
||||
private final Map<String, Set<FaceMapper>> faceMappers = new HashMap<>();
|
||||
|
||||
public void registerLimbData(LimbData data) {
|
||||
this.limbData.put(data.limbType(), data);
|
||||
}
|
||||
|
||||
public LimbData getLimbData(String data) {
|
||||
return this.limbData.get(data);
|
||||
}
|
||||
|
||||
public void registerTextureSource(String name, BufferedImage texture) {
|
||||
this.textureReference.put(name, texture);
|
||||
}
|
||||
|
||||
public void registerFaceMapper(String name, FaceMapper mapper) {
|
||||
this.faceMappers.computeIfAbsent(name, s -> new HashSet<>()).add(mapper);
|
||||
}
|
||||
|
||||
public Map<String, byte[]> generateAll(Map<String, BufferedImage> placeholderReference) {
|
||||
return this.generate(this.faceMappers.keySet(), placeholderReference);
|
||||
}
|
||||
|
||||
public Map<String, byte[]> generate(Collection<String> parts, Map<String, BufferedImage> placeholderReference) {
|
||||
HashMap<String, byte[]> map = new HashMap<>();
|
||||
|
||||
for (String key : parts) {
|
||||
try {
|
||||
byte[] data = this.generatePartTexture(key, placeholderReference);
|
||||
if (data.length > 0) {
|
||||
map.put(key, data);
|
||||
}
|
||||
} catch (IOException var7) {
|
||||
var7.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
public byte[] generatePartTexture(String part, Map<String, BufferedImage> placeholderReference) throws IOException {
|
||||
Set<FaceMapper> mappers = this.faceMappers.get(part);
|
||||
if (mappers != null && !mappers.isEmpty()) {
|
||||
BufferedImage image = new BufferedImage(64, 64, 2);
|
||||
|
||||
for (FaceMapper mapper : mappers) {
|
||||
BufferedImage texture = placeholderReference.get(mapper.sourceTexture());
|
||||
if (texture == null) {
|
||||
texture = this.textureReference.get(mapper.sourceTexture());
|
||||
if (texture == null) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
BufferedImage finalTexture = texture;
|
||||
mapper.to().forPixel((x, y) -> {
|
||||
float[] source = mapper.getSourcePixel(x.intValue(), y.intValue());
|
||||
int xx = (int)(source[0] * (finalTexture.getWidth() / 64.0F));
|
||||
int yy = (int)(source[1] * (finalTexture.getHeight() / 64.0F));
|
||||
image.setRGB(x, y, finalTexture.getRGB(xx, yy));
|
||||
});
|
||||
}
|
||||
|
||||
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
|
||||
ImageIO.write(image, "png", byteStream);
|
||||
return byteStream.toByteArray();
|
||||
} else {
|
||||
return new byte[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.ticxo.modelengine.core.generator.skin;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchDeserializer;
|
||||
import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchModel;
|
||||
import com.ticxo.modelengine.api.generator.skin.LimbData;
|
||||
import com.ticxo.modelengine.api.generator.skin.SkinSplitter;
|
||||
import com.ticxo.modelengine.api.utils.TFile;
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Map.Entry;
|
||||
import javax.imageio.ImageIO;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class SkinSplitterImpl implements SkinSplitter {
|
||||
private static final String PLACEHOLDER_SKIN = "<placeholder.skin>";
|
||||
private final Gson gson = new GsonBuilder().registerTypeAdapter(BlockbenchModel.class, new BlockbenchDeserializer()).create();
|
||||
private final File internalSteveMapped;
|
||||
private final File internalAlexMapped;
|
||||
private PlayerMapper steveMapper;
|
||||
private PlayerMapper alexMapper;
|
||||
|
||||
public void copyMapped(ModelEngineAPI plugin) {
|
||||
TFile.copyResource(plugin, this.internalSteveMapped, "internal/steve_mapped.bbmodel");
|
||||
TFile.copyResource(plugin, this.internalAlexMapped, "internal/alex_mapped.bbmodel");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reloadMapping() {
|
||||
try {
|
||||
this.steveMapper = this.createSkinMaps((BlockbenchModel)this.gson.fromJson(new FileReader(this.internalSteveMapped), BlockbenchModel.class));
|
||||
this.alexMapper = this.createSkinMaps((BlockbenchModel)this.gson.fromJson(new FileReader(this.internalAlexMapped), BlockbenchModel.class));
|
||||
} catch (IOException var2) {
|
||||
var2.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private PlayerMapper createSkinMaps(BlockbenchModel model) {
|
||||
PlayerMapper playerTemplate = new PlayerMapper();
|
||||
HashMap<Integer, String> texMap = new HashMap<>();
|
||||
|
||||
for (Entry<Integer, BlockbenchModel.Texture> entry : model.getTextures().entrySet()) {
|
||||
BlockbenchModel.Texture texture = entry.getValue();
|
||||
if (!texture.getName().equals("<placeholder.skin>")) {
|
||||
BufferedImage image = TFile.toImage(texture.getSource());
|
||||
playerTemplate.registerTextureSource(texture.getName(), image);
|
||||
}
|
||||
|
||||
texMap.put(entry.getKey(), texture.getName());
|
||||
}
|
||||
|
||||
Map<String, BlockbenchModel.Group> groups = model.getFlatOutlinerByName();
|
||||
|
||||
for (Entry<String, BlockbenchModel.Group> entry : groups.entrySet()) {
|
||||
String boneId = entry.getKey();
|
||||
if (boneId.equals("head")) {
|
||||
playerTemplate.registerLimbData(new LimbData(boneId, new Vector3f(0.0F, 0.5F, 0.0F), new Vector3f(1.0F), true));
|
||||
} else {
|
||||
BlockbenchModel.Group group = entry.getValue();
|
||||
if (!group.getElement().isEmpty()) {
|
||||
List<BlockbenchModel.Cube> cubes = group.getElement()
|
||||
.stream()
|
||||
.map(uuid -> model.getElements().get(uuid))
|
||||
.map(element -> element instanceof BlockbenchModel.Cube cubex ? cubex : null)
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
if (!cubes.isEmpty()) {
|
||||
Vector3f origin = new Vector3f(0.0F);
|
||||
Vector3f scale = new Vector3f(1.0F);
|
||||
|
||||
for (BlockbenchModel.Cube cube : cubes) {
|
||||
boolean hatLayer = cube.getName().startsWith("hat_");
|
||||
if (!hatLayer) {
|
||||
origin.set(cube.centerX(), cube.maxY(), cube.centerZ()).sub(TMath.wrap(group.getOrigin())).mul(-0.0625F, 0.0625F, -0.0625F);
|
||||
scale.set(cube.width(), cube.height(), cube.depth()).mul(0.125F);
|
||||
}
|
||||
|
||||
for (Entry<String, BlockbenchModel.Face> faceEntry : cube.getFaces().entrySet()) {
|
||||
String texName = texMap.get(faceEntry.getValue().getTexture());
|
||||
if (texName != null) {
|
||||
FaceMapper.Face face = FaceMapper.Face.getFace(faceEntry.getKey(), hatLayer);
|
||||
Float[] uv = faceEntry.getValue().getUv();
|
||||
FaceMapper faceMapper = new FaceMapper(texName, new float[]{uv[0], uv[1], uv[2], uv[3]}, face);
|
||||
playerTemplate.registerFaceMapper(boneId, faceMapper);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
playerTemplate.registerLimbData(new LimbData(boneId, origin, scale, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return playerTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LimbData getLimb(String id, boolean slim) {
|
||||
return (slim ? this.alexMapper : this.steveMapper).getLimbData(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, byte[]> splitSkin(byte[] skinData, boolean slim) {
|
||||
return this.split(skinData, slim, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, byte[]> splitSkin(byte[] skinData, boolean slim, Collection<String> limbTypes) {
|
||||
return this.split(skinData, slim, limbTypes);
|
||||
}
|
||||
|
||||
private Map<String, byte[]> split(byte[] skinData, boolean slim, @Nullable Collection<String> limbTypes) {
|
||||
try {
|
||||
BufferedImage skinImage = ImageIO.read(new ByteArrayInputStream(skinData));
|
||||
HashMap<String, BufferedImage> placeholder = new HashMap<>();
|
||||
placeholder.put("<placeholder.skin>", skinImage);
|
||||
PlayerMapper mapper = slim ? this.alexMapper : this.steveMapper;
|
||||
return limbTypes == null ? mapper.generateAll(placeholder) : mapper.generate(limbTypes, placeholder);
|
||||
} catch (IOException var7) {
|
||||
var7.printStackTrace();
|
||||
return new HashMap<>();
|
||||
}
|
||||
}
|
||||
|
||||
public SkinSplitterImpl(File internalSteveMapped, File internalAlexMapped) {
|
||||
this.internalSteveMapped = internalSteveMapped;
|
||||
this.internalAlexMapped = internalAlexMapped;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.ticxo.modelengine.core.generator.util;
|
||||
|
||||
import com.ticxo.modelengine.api.utils.math.Axis;
|
||||
import java.util.Objects;
|
||||
import org.joml.Vector3d;
|
||||
|
||||
public class HashedVector3d extends Vector3d {
|
||||
private static final int PRECISION = 10000;
|
||||
private final Axis axis;
|
||||
|
||||
public HashedVector3d(Axis axis, double x, double y, double z) {
|
||||
super(x, y, z);
|
||||
this.axis = axis;
|
||||
}
|
||||
|
||||
public HashedVector3d() {
|
||||
this.axis = Axis.X;
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return Objects.hash(this.axis, (int)Math.round(this.x * 10000.0), (int)Math.round(this.y * 10000.0), (int)Math.round(this.z * 10000.0));
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
} else if (obj == null) {
|
||||
return false;
|
||||
} else {
|
||||
return this.getClass() != obj.getClass() ? false : this.hashCode() == obj.hashCode();
|
||||
}
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package com.ticxo.modelengine.core.generator.util;
|
||||
|
||||
import com.ticxo.modelengine.api.utils.data.Triple;
|
||||
import com.ticxo.modelengine.api.utils.math.Axis;
|
||||
import com.ticxo.modelengine.api.utils.math.Direction;
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import com.ticxo.modelengine.core.generator.processed.ProcessedBone;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map.Entry;
|
||||
import org.joml.Quaterniond;
|
||||
import org.joml.Vector3d;
|
||||
import org.joml.Vector3dc;
|
||||
|
||||
public class IllegalRotationSolver {
|
||||
private static final List<Vector3d> AXES = List.of(Axis.X.getVector(), Axis.Y.getVector(), Axis.Z.getVector());
|
||||
|
||||
public static ProcessedBone.Cube solve(ProcessedBone.Cube cube) {
|
||||
if (isLegal(cube)) {
|
||||
return cube;
|
||||
} else {
|
||||
Quaterniond quaternion = cube.getQuaternion();
|
||||
HashMap<Direction, Triple<Vector3d, Vector3d, ProcessedBone.Face>> uvs = new HashMap<>();
|
||||
|
||||
for (Entry<Direction, ProcessedBone.Face> entry : cube.getFaces().entrySet()) {
|
||||
Direction dir = entry.getKey();
|
||||
ProcessedBone.Face uv = entry.getValue();
|
||||
uvs.put(dir, new Triple<>(dir.getNormal().rotate(quaternion), dir.getUvUp().rotate(quaternion), uv));
|
||||
}
|
||||
|
||||
List<Vector3d> corners = cube.getCorners();
|
||||
corners.forEach(vector3d -> vector3d.sub(cube.getOrigin()).rotate(quaternion).add(cube.getOrigin()));
|
||||
Vector3d srcDir = new Vector3d(0.0, 0.0, 1.0).rotate(quaternion);
|
||||
Vector3d dstAxis = closestAxis(srcDir);
|
||||
double dot = srcDir.dot(dstAxis);
|
||||
Quaterniond undoQuat;
|
||||
if (TMath.isSimilar(dot, 1.0)) {
|
||||
srcDir = new Vector3d(0.0, 1.0, 0.0).rotate(quaternion);
|
||||
dstAxis = closestAxis(srcDir);
|
||||
dot = srcDir.dot(dstAxis);
|
||||
if (TMath.isSimilar(dot, 1.0)) {
|
||||
undoQuat = new Quaterniond();
|
||||
} else {
|
||||
Vector3d cross = srcDir.cross(dstAxis, new Vector3d()).normalize();
|
||||
undoQuat = new Quaterniond().rotateAxis(Math.acos(dot), cross);
|
||||
}
|
||||
} else {
|
||||
Vector3d cross = srcDir.cross(dstAxis, new Vector3d()).normalize();
|
||||
undoQuat = new Quaterniond().rotateAxis(Math.acos(dot), cross);
|
||||
}
|
||||
|
||||
HashMap<Direction, ProcessedBone.Face> newUVs = new HashMap<>();
|
||||
|
||||
for (Entry<Direction, Triple<Vector3d, Vector3d, ProcessedBone.Face>> entry : uvs.entrySet()) {
|
||||
Triple<Vector3d, Vector3d, ProcessedBone.Face> triple = entry.getValue();
|
||||
Vector3d currNormal = triple.getFirst().rotate(undoQuat);
|
||||
Direction currDir = Direction.fromNormal(currNormal);
|
||||
if (currDir != null) {
|
||||
Vector3d currUVUp = currDir.getUvUp();
|
||||
Vector3d targetUVUp = triple.getSecond().rotate(undoQuat);
|
||||
int angle = 0;
|
||||
double upDot = targetUVUp.dot(currUVUp);
|
||||
if (TMath.isSimilar(upDot, -1.0)) {
|
||||
angle = 180;
|
||||
} else if (TMath.isSimilar(upDot, 0.0)) {
|
||||
Vector3d cross = targetUVUp.cross(currUVUp, new Vector3d());
|
||||
angle = cross.dot(currNormal) > 0.0 ? 90 : 270;
|
||||
}
|
||||
|
||||
ProcessedBone.Face face = triple.getThird();
|
||||
ProcessedBone.UV uv = face.uv();
|
||||
ProcessedBone.Face tFace = new ProcessedBone.Face(
|
||||
new ProcessedBone.UV(uv.u1(), uv.v1(), uv.u2(), uv.v2(), (uv.rotation() + angle) % 360), face.texture()
|
||||
);
|
||||
newUVs.put(currDir, tFace);
|
||||
}
|
||||
}
|
||||
|
||||
Vector3d from = new Vector3d(2.147483647E9);
|
||||
Vector3d to = new Vector3d(-2.1474836E9F);
|
||||
corners.forEach(vector3d -> {
|
||||
Vector3d vec = vector3d.sub(cube.getOrigin()).rotate(undoQuat).add(cube.getOrigin());
|
||||
from.set(Math.min(from.x, vec.x), Math.min(from.y, vec.y), Math.min(from.z, vec.z));
|
||||
to.set(Math.max(to.x, vec.x), Math.max(to.y, vec.y), Math.max(to.z, vec.z));
|
||||
});
|
||||
Vector3d rotation = TMath.fixEuler(TMath.toEulerZYX(undoQuat.invert()));
|
||||
return new ProcessedBone.Cube(cube.getName(), cube.getOrigin(), rotation, from, to, newUVs, cube.getInflate());
|
||||
}
|
||||
}
|
||||
|
||||
private static Vector3d closestAxis(Vector3d dir) {
|
||||
if (TMath.isSimilar(dir.lengthSquared(), 0.0)) {
|
||||
return new Vector3d((Vector3dc)AXES.get(2));
|
||||
} else {
|
||||
Vector3d closest = null;
|
||||
double dot = 0.0;
|
||||
|
||||
for (Vector3d axis : AXES) {
|
||||
double d = Math.abs(dir.dot(axis));
|
||||
if (d > dot) {
|
||||
dot = d;
|
||||
closest = axis;
|
||||
}
|
||||
}
|
||||
|
||||
if (closest == null) {
|
||||
return new Vector3d((Vector3dc)AXES.get(2));
|
||||
} else {
|
||||
return closest.dot(dir) > 0.0 ? new Vector3d(closest) : closest.negate(new Vector3d());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isLegal(ProcessedBone.Cube cube) {
|
||||
Vector3d rot = cube.getRotation();
|
||||
return TMath.isAlmostBetween(rot.x, -45.0, 45.0) && TMath.isInterval(rot.x, 22.5) && TMath.isSimilar(rot.y, 0.0) && TMath.isSimilar(rot.z, 0.0)
|
||||
|| TMath.isAlmostBetween(rot.y, -45.0, 45.0) && TMath.isInterval(rot.y, 22.5) && TMath.isSimilar(rot.x, 0.0) && TMath.isSimilar(rot.z, 0.0)
|
||||
|| TMath.isAlmostBetween(rot.z, -45.0, 45.0) && TMath.isInterval(rot.z, 22.5) && TMath.isSimilar(rot.x, 0.0) && TMath.isSimilar(rot.y, 0.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.ticxo.modelengine.core.generator.util;
|
||||
|
||||
import com.ticxo.modelengine.api.generator.assets.JavaDisplay;
|
||||
import com.ticxo.modelengine.api.generator.assets.JavaItemModel;
|
||||
import com.ticxo.modelengine.api.generator.assets.ModelAssets;
|
||||
import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchModel;
|
||||
import com.ticxo.modelengine.api.utils.MiscUtils;
|
||||
import com.ticxo.modelengine.api.utils.math.Direction;
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import com.ticxo.modelengine.core.generator.processed.ProcessedBone;
|
||||
import java.text.NumberFormat;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import org.joml.Quaterniond;
|
||||
import org.joml.Vector3d;
|
||||
|
||||
public record ItemGroup(int debug, Quaterniond displayQuaternion, Vector3d displayRotation, List<ProcessedBone.Cube> cubes) {
|
||||
public JavaItemModel toJavaItemModel(String name, BlockbenchModel model, ModelAssets assets) {
|
||||
JavaItemModel javaItem = new JavaItemModel();
|
||||
javaItem.setName(name);
|
||||
|
||||
for (ProcessedBone.Cube cube : this.cubes) {
|
||||
JavaItemModel.JavaElement element = new JavaItemModel.JavaElement();
|
||||
element.from(TMath.unwrap(cube.getFrom()), cube.getInflate());
|
||||
element.to(TMath.unwrap(cube.getTo()), cube.getInflate());
|
||||
element.setRotation(cube.rotation());
|
||||
|
||||
for (Entry<Direction, ProcessedBone.Face> faceEntry : cube.getFaces().entrySet()) {
|
||||
Direction dir = faceEntry.getKey();
|
||||
ProcessedBone.Face bbFace = faceEntry.getValue();
|
||||
if (!bbFace.isEmpty()) {
|
||||
int id = bbFace.texture();
|
||||
if (id < assets.getTextures().size()) {
|
||||
BlockbenchModel.Texture tex = model.getTextures().get(id);
|
||||
JavaItemModel.JavaElement.Face face = new JavaItemModel.JavaElement.Face();
|
||||
face.setRotation(bbFace.uv().rotation());
|
||||
face.uv(
|
||||
MiscUtils.or(tex.getUv_width(), model.getResolution().getWidth()),
|
||||
MiscUtils.or(tex.getUv_height(), model.getResolution().getHeight()),
|
||||
new float[]{bbFace.uv().u1(), bbFace.uv().v1(), bbFace.uv().u2(), bbFace.uv().v2()}
|
||||
);
|
||||
face.setTexture("#" + id);
|
||||
element.getFaces().put(dir.name().toLowerCase(Locale.ENGLISH), face);
|
||||
Map<String, String> textures = javaItem.getTextures();
|
||||
textures.computeIfAbsent(String.valueOf(id), s -> assets.getTextures().get(id).getPath().toString());
|
||||
if (textures.size() == 1) {
|
||||
textures.computeIfAbsent("particle", s -> "#" + id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
javaItem.addElement(element);
|
||||
}
|
||||
|
||||
javaItem.setDisplay(
|
||||
JavaDisplay.THIRDPERSON_RIGHTHAND,
|
||||
JavaDisplay.Transform.ROTATION,
|
||||
(float)this.displayRotation.x,
|
||||
(float)this.displayRotation.y,
|
||||
(float)this.displayRotation.z
|
||||
);
|
||||
javaItem.setDisplay(
|
||||
JavaDisplay.FIRSTPERSON_RIGHTHAND,
|
||||
JavaDisplay.Transform.ROTATION,
|
||||
(float)this.displayRotation.x,
|
||||
(float)this.displayRotation.y,
|
||||
(float)this.displayRotation.z
|
||||
);
|
||||
javaItem.setDisplay(
|
||||
JavaDisplay.GROUND, JavaDisplay.Transform.ROTATION, (float)this.displayRotation.x, (float)this.displayRotation.y, (float)this.displayRotation.z
|
||||
);
|
||||
javaItem.setDisplay(
|
||||
JavaDisplay.HEAD, JavaDisplay.Transform.ROTATION, (float)this.displayRotation.x, (float)this.displayRotation.y, (float)this.displayRotation.z
|
||||
);
|
||||
javaItem.setDisplay(
|
||||
JavaDisplay.FIXED, JavaDisplay.Transform.ROTATION, (float)this.displayRotation.x, (float)this.displayRotation.y, (float)this.displayRotation.z
|
||||
);
|
||||
Vector3d guiRotation = TMath.toEulerXYZ(TMath.fromEulerXYZ(new Vector3d(30.0, 225.0, 0.0)).mul(this.displayQuaternion));
|
||||
javaItem.setDisplay(JavaDisplay.GUI, JavaDisplay.Transform.ROTATION, (float)guiRotation.x, (float)guiRotation.y, (float)guiRotation.z);
|
||||
javaItem.setDisplay(
|
||||
JavaDisplay.THIRDPERSON_LEFTHAND,
|
||||
JavaDisplay.Transform.ROTATION,
|
||||
(float)this.displayRotation.x,
|
||||
(float)(-this.displayRotation.y),
|
||||
(float)(-this.displayRotation.z)
|
||||
);
|
||||
javaItem.setDisplay(
|
||||
JavaDisplay.FIRSTPERSON_LEFTHAND,
|
||||
JavaDisplay.Transform.ROTATION,
|
||||
(float)this.displayRotation.x,
|
||||
(float)(-this.displayRotation.y),
|
||||
(float)(-this.displayRotation.z)
|
||||
);
|
||||
return javaItem;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ItemGroup{debug=" + this.debug + ", displayRotation=" + this.displayRotation.toString(NumberFormat.getInstance()) + ", cubes=" + this.cubes + "}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.ticxo.modelengine.core.generator.util;
|
||||
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import com.ticxo.modelengine.core.generator.processed.ProcessedBone;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
||||
import it.unimi.dsi.fastutil.ints.IntSet;
|
||||
import java.text.NumberFormat;
|
||||
import org.joml.Quaterniond;
|
||||
import org.joml.Vector3d;
|
||||
|
||||
public record PlaneGroup(Vector3d axis, int modAngle, Quaterniond origin, Quaterniond invOrigin, IntSet cubes) {
|
||||
@Override
|
||||
public String toString() {
|
||||
return "PlaneGroup{axis="
|
||||
+ this.axis
|
||||
+ ", modAngle="
|
||||
+ this.modAngle
|
||||
+ ", origin="
|
||||
+ TMath.toEulerZYX(this.origin).toString(NumberFormat.getInstance())
|
||||
+ ", invOrigin="
|
||||
+ TMath.toEulerZYX(this.invOrigin).toString(NumberFormat.getInstance())
|
||||
+ ", cubes="
|
||||
+ this.cubes
|
||||
+ "}";
|
||||
}
|
||||
|
||||
public String toString(Int2ObjectMap<ProcessedBone.Cube> map) {
|
||||
return "PlaneGroup{axis="
|
||||
+ this.axis
|
||||
+ ", modAngle="
|
||||
+ this.modAngle
|
||||
+ ", origin="
|
||||
+ TMath.toEulerZYX(this.origin).toString(NumberFormat.getInstance())
|
||||
+ ", invOrigin="
|
||||
+ TMath.toEulerZYX(this.invOrigin).toString(NumberFormat.getInstance())
|
||||
+ ", cubes="
|
||||
+ map.int2ObjectEntrySet().stream().filter(cubeEntry -> this.cubes.contains(cubeEntry.getIntKey())).toList()
|
||||
+ "}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
package com.ticxo.modelengine.core.generator.util;
|
||||
|
||||
import com.ticxo.modelengine.api.utils.math.Axis;
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import com.ticxo.modelengine.core.generator.processed.ProcessedBone;
|
||||
import it.unimi.dsi.fastutil.Pair;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectLinkedOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.ints.IntIterator;
|
||||
import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet;
|
||||
import it.unimi.dsi.fastutil.ints.IntListIterator;
|
||||
import it.unimi.dsi.fastutil.ints.IntSet;
|
||||
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectBidirectionalIterator;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectIterator;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.PriorityQueue;
|
||||
import java.util.Set;
|
||||
import java.util.Map.Entry;
|
||||
import org.joml.Quaterniond;
|
||||
import org.joml.Vector3d;
|
||||
import org.joml.Vector3dc;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class RotationSolver {
|
||||
private static final Logger log = LoggerFactory.getLogger(RotationSolver.class);
|
||||
private static final List<Vector3d> CARDINAL_AXES = new ArrayList<Vector3d>() {
|
||||
{
|
||||
this.add(new Vector3d(1.0, 0.0, 0.0));
|
||||
this.add(new Vector3d(0.0, 1.0, 0.0));
|
||||
this.add(new Vector3d(0.0, 0.0, 1.0));
|
||||
this.add(new Vector3d(-1.0, 0.0, 0.0));
|
||||
this.add(new Vector3d(0.0, -1.0, 0.0));
|
||||
this.add(new Vector3d(0.0, 0.0, -1.0));
|
||||
}
|
||||
};
|
||||
private final Int2ObjectMap<ProcessedBone.Cube> cubes = new Int2ObjectOpenHashMap();
|
||||
private final Int2ObjectMap<List<Vector3d>> axes = new Int2ObjectOpenHashMap();
|
||||
|
||||
public static void solve(Collection<ItemGroup> result, Collection<ProcessedBone.Cube> cubes) {
|
||||
RotationSolver solver = new RotationSolver();
|
||||
solver.initialize(result, cubes);
|
||||
solver.solve(result);
|
||||
}
|
||||
|
||||
private void initialize(Collection<ItemGroup> result, Collection<ProcessedBone.Cube> collection) {
|
||||
int cubeId = 0;
|
||||
ArrayList<ProcessedBone.Cube> list = new ArrayList<>();
|
||||
|
||||
for (ProcessedBone.Cube cube : collection) {
|
||||
if (isLegal(cube)) {
|
||||
list.add(IllegalRotationSolver.solve(cube));
|
||||
} else {
|
||||
this.cubes.put(cubeId++, cube);
|
||||
}
|
||||
}
|
||||
|
||||
if (!list.isEmpty()) {
|
||||
result.add(new ItemGroup(-1, new Quaterniond(), new Vector3d(), list));
|
||||
}
|
||||
}
|
||||
|
||||
private void solve(Collection<ItemGroup> result) {
|
||||
Map<Vector3d, IntLinkedOpenHashSet> axisGroup = this.groupByAxis();
|
||||
List<PlaneGroup> moduloGroup = this.groupByModulo(axisGroup);
|
||||
Map<PlaneGroup, Set<PlaneGroup>> planeGroup = this.combineGroup(moduloGroup);
|
||||
this.fixGroups(result, planeGroup);
|
||||
}
|
||||
|
||||
private void simpleConvert(Collection<ItemGroup> result, List<PlaneGroup> moduloGroup) {
|
||||
for (PlaneGroup plane : moduloGroup) {
|
||||
ArrayList<ProcessedBone.Cube> list = new ArrayList<>();
|
||||
this.rotateCubes(list, plane.cubes(), plane.invOrigin());
|
||||
result.add(new ItemGroup(0, new Quaterniond(plane.origin()), TMath.toEulerXYZ(plane.origin()), list));
|
||||
}
|
||||
}
|
||||
|
||||
private List<Vector3d> toAxes(int cubeId) {
|
||||
ProcessedBone.Cube cube = (ProcessedBone.Cube)this.cubes.get(cubeId);
|
||||
Vector3d px = TMath.fixVector(new HashedVector3d(Axis.X, 1.0, 0.0, 0.0).rotate(cube.getQuaternion()));
|
||||
Vector3d py = TMath.fixVector(new HashedVector3d(Axis.Y, 0.0, 1.0, 0.0).rotate(cube.getQuaternion()));
|
||||
Vector3d pz = TMath.fixVector(new HashedVector3d(Axis.Z, 0.0, 0.0, 1.0).rotate(cube.getQuaternion()));
|
||||
return Arrays.asList(px, py, pz);
|
||||
}
|
||||
|
||||
private Map<Vector3d, IntLinkedOpenHashSet> groupByAxis() {
|
||||
Object2ObjectLinkedOpenHashMap<Vector3d, IntLinkedOpenHashSet> map = new Object2ObjectLinkedOpenHashMap();
|
||||
IntIterator var2 = this.cubes.keySet().iterator();
|
||||
|
||||
while (var2.hasNext()) {
|
||||
int key = (Integer)var2.next();
|
||||
List<Vector3d> axes = this.toAxes(key);
|
||||
this.axes.put(key, axes);
|
||||
|
||||
for (Vector3d axis : axes) {
|
||||
((IntLinkedOpenHashSet)map.computeIfAbsent(axis, vector3d -> new IntLinkedOpenHashSet())).add(key);
|
||||
}
|
||||
}
|
||||
|
||||
return fetch(map);
|
||||
}
|
||||
|
||||
private List<PlaneGroup> groupByModulo(Map<Vector3d, IntLinkedOpenHashSet> byAxis) {
|
||||
Object2ObjectLinkedOpenHashMap<Vector3d, Int2ObjectMap<IntSet>> temp = new Object2ObjectLinkedOpenHashMap();
|
||||
ArrayList<PlaneGroup> result = new ArrayList<>();
|
||||
|
||||
for (Entry<Vector3d, IntLinkedOpenHashSet> entry : byAxis.entrySet()) {
|
||||
Quaterniond toOrigin = null;
|
||||
IntListIterator subGroup = entry.getValue().iterator();
|
||||
|
||||
while (subGroup.hasNext()) {
|
||||
int cubeId = (Integer)subGroup.next();
|
||||
ProcessedBone.Cube cube = (ProcessedBone.Cube)this.cubes.get(cubeId);
|
||||
double angle;
|
||||
if (toOrigin == null) {
|
||||
toOrigin = cube.getQuaternion().invert(new Quaterniond());
|
||||
angle = 0.0;
|
||||
} else {
|
||||
Quaterniond localQ = toOrigin.mul(cube.getQuaternion(), new Quaterniond());
|
||||
Vector3d lqVec = new Vector3d(localQ.x, localQ.y, localQ.z);
|
||||
double sign = Math.signum(lqVec.dot((Vector3dc)entry.getKey()));
|
||||
angle = sign * 2.0 * Math.acos(localQ.w) * (180.0 / Math.PI);
|
||||
}
|
||||
|
||||
int groupId = getGroupId(angle);
|
||||
((IntSet)((Int2ObjectMap)temp.computeIfAbsent(entry.getKey(), vector3d -> new Int2ObjectLinkedOpenHashMap()))
|
||||
.computeIfAbsent(groupId, integer -> new IntLinkedOpenHashSet()))
|
||||
.add(cubeId);
|
||||
}
|
||||
}
|
||||
|
||||
ObjectBidirectionalIterator var16 = temp.entrySet().iterator();
|
||||
|
||||
while (var16.hasNext()) {
|
||||
Entry<Vector3d, Int2ObjectMap<IntSet>> group = (Entry<Vector3d, Int2ObjectMap<IntSet>>)var16.next();
|
||||
ObjectIterator var18 = group.getValue().int2ObjectEntrySet().iterator();
|
||||
|
||||
while (var18.hasNext()) {
|
||||
it.unimi.dsi.fastutil.ints.Int2ObjectMap.Entry<IntSet> subGroup = (it.unimi.dsi.fastutil.ints.Int2ObjectMap.Entry<IntSet>)var18.next();
|
||||
int firstCubeId = ((IntSet)subGroup.getValue()).iterator().nextInt();
|
||||
Quaterniond rotation = ((ProcessedBone.Cube)this.cubes.get(firstCubeId)).getQuaternion();
|
||||
result.add(
|
||||
new PlaneGroup(
|
||||
new Vector3d((Vector3dc)group.getKey()),
|
||||
subGroup.getIntKey(),
|
||||
new Quaterniond(rotation),
|
||||
rotation.invert(new Quaterniond()),
|
||||
(IntSet)subGroup.getValue()
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private Map<PlaneGroup, Set<PlaneGroup>> combineGroup(List<PlaneGroup> planes) {
|
||||
Object2ObjectLinkedOpenHashMap<PlaneGroup, Set<PlaneGroup>> map = new Object2ObjectLinkedOpenHashMap();
|
||||
|
||||
for (int a = 0; a < planes.size(); a++) {
|
||||
PlaneGroup groupA = planes.get(a);
|
||||
Set<PlaneGroup> set = (Set<PlaneGroup>)map.computeIfAbsent(groupA, planeGroup -> new ObjectLinkedOpenHashSet());
|
||||
set.add(groupA);
|
||||
|
||||
label55:
|
||||
for (int b = a + 1; b < planes.size(); b++) {
|
||||
PlaneGroup groupB = planes.get(b);
|
||||
if (TMath.isSimilar(groupA.axis().dot(groupB.axis()), -1.0)) {
|
||||
List<Vector3d> axesA = (List<Vector3d>)this.axes.get(groupA.cubes().iterator().nextInt());
|
||||
List<Vector3d> axesB = (List<Vector3d>)this.axes.get(groupB.cubes().iterator().nextInt());
|
||||
|
||||
for (int i = 0; i < 3; i++) {
|
||||
Vector3d axisA = axesA.get(i);
|
||||
Vector3d axisB = axesB.get(i);
|
||||
if (getGroupId(Math.acos(axisA.dot(axisB)) * (180.0 / Math.PI)) != 0) {
|
||||
continue label55;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (PlaneGroup g : set) {
|
||||
double dot = g.axis().dot(groupB.axis());
|
||||
if (!TMath.isSimilar(dot, 0.0) && !TMath.isSimilar(dot, -1.0)) {
|
||||
continue label55;
|
||||
}
|
||||
|
||||
Vector3d vA = groupB.axis().rotate(g.invOrigin(), new Vector3d());
|
||||
Vector3d vB = g.axis().rotate(groupB.invOrigin(), new Vector3d());
|
||||
if (!isGroupable(vA) || !isGroupable(vB)) {
|
||||
continue label55;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
set.add(groupB);
|
||||
}
|
||||
}
|
||||
|
||||
return fetch(map);
|
||||
}
|
||||
|
||||
private void fixGroups(Collection<ItemGroup> result, Map<PlaneGroup, Set<PlaneGroup>> planeGroupMap) {
|
||||
for (Entry<PlaneGroup, Set<PlaneGroup>> entry : planeGroupMap.entrySet()) {
|
||||
Set<PlaneGroup> planeGroups = entry.getValue();
|
||||
if (planeGroups.size() < 2) {
|
||||
PlaneGroup group = planeGroups.iterator().next();
|
||||
result.add(
|
||||
new ItemGroup(
|
||||
0, new Quaterniond(group.origin()), TMath.toEulerXYZ(group.origin()), this.rotateCubes(new ArrayList<>(), group.cubes(), group.invOrigin())
|
||||
)
|
||||
);
|
||||
} else {
|
||||
Iterator<PlaneGroup> iterator = planeGroups.iterator();
|
||||
PlaneGroup groupA = iterator.next();
|
||||
Vector3d axisA = groupA.axis();
|
||||
Vector3d axisB = iterator.next().axis();
|
||||
|
||||
while (TMath.isSimilar(Math.abs(axisA.dot(axisB)), 1.0) && iterator.hasNext()) {
|
||||
axisB = iterator.next().axis();
|
||||
}
|
||||
|
||||
if (TMath.isSimilar(Math.abs(axisA.dot(axisB)), 1.0)) {
|
||||
ArrayList<ProcessedBone.Cube> list = new ArrayList<>();
|
||||
|
||||
for (PlaneGroup planeGroup : planeGroups) {
|
||||
this.rotateCubes(list, planeGroup.cubes(), groupA.invOrigin());
|
||||
}
|
||||
|
||||
result.add(new ItemGroup(0, new Quaterniond(groupA.origin()), TMath.toEulerXYZ(groupA.origin()), list));
|
||||
} else {
|
||||
Vector3d cardinalA = getClosestCardinal(axisA);
|
||||
Quaterniond aToCardinal = axisA.rotationTo(cardinalA, new Quaterniond());
|
||||
Vector3d axisBPrime = axisB.rotate(aToCardinal, new Vector3d());
|
||||
Vector3d cardinalB = getClosestCardinal(axisBPrime);
|
||||
Quaterniond bPrimeToCardinal = axisBPrime.rotationTo(cardinalB, new Quaterniond());
|
||||
Quaterniond invRoot = bPrimeToCardinal.mul(aToCardinal);
|
||||
Quaterniond rootRotation = invRoot.invert(new Quaterniond());
|
||||
Vector3d rootEuler = TMath.fixEuler(TMath.toEulerXYZ(rootRotation));
|
||||
ArrayList<ProcessedBone.Cube> list = new ArrayList<>();
|
||||
|
||||
for (PlaneGroup planeGroup : planeGroups) {
|
||||
this.rotateCubes(list, planeGroup.cubes(), invRoot);
|
||||
}
|
||||
|
||||
result.add(new ItemGroup(1, rootRotation, rootEuler, list));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<ProcessedBone.Cube> rotateCubes(List<ProcessedBone.Cube> result, IntSet cubeIds, Quaterniond quaterniond) {
|
||||
IntIterator var4 = cubeIds.iterator();
|
||||
|
||||
while (var4.hasNext()) {
|
||||
int cubeId = (Integer)var4.next();
|
||||
ProcessedBone.Cube cube = (ProcessedBone.Cube)this.cubes.get(cubeId);
|
||||
cube.rotate(quaterniond);
|
||||
result.add(IllegalRotationSolver.solve(cube));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static <T, R extends Collection<S>, S> Map<T, R> fetch(Map<T, R> map) {
|
||||
PriorityQueue<Pair<T, R>> queue = new PriorityQueue<>(Comparator.<Pair<T, R>, Integer>comparing(pair -> ((Collection)pair.second()).size()).reversed());
|
||||
map.forEach((t, rs) -> queue.add(Pair.of(t, rs)));
|
||||
Object2ObjectLinkedOpenHashMap<T, R> result = new Object2ObjectLinkedOpenHashMap();
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
Pair<T, R> largest = queue.poll();
|
||||
if (((Collection)largest.second()).isEmpty()) {
|
||||
break;
|
||||
}
|
||||
|
||||
queue.clear();
|
||||
map.remove(largest.first());
|
||||
result.put(largest.first(), largest.second());
|
||||
map.forEach((t, rs) -> {
|
||||
rs.removeAll((Collection<?>)largest.second());
|
||||
queue.add(Pair.of(t, rs));
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int getGroupId(double angle) {
|
||||
while (angle < 0.0) {
|
||||
angle += 360.0;
|
||||
}
|
||||
|
||||
int intAngle = (int)Math.round(angle * 10000.0);
|
||||
return intAngle % 225000;
|
||||
}
|
||||
|
||||
private static boolean isGroupable(Vector3d vec) {
|
||||
for (Axis axis : Axis.values()) {
|
||||
if (getGroupId(Math.acos(vec.dot(axis.getVector())) * (float) (180.0 / Math.PI)) != 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Vector3d getClosestCardinal(Vector3d vec) {
|
||||
double dot = -1.0;
|
||||
Vector3d cardinal = null;
|
||||
|
||||
for (Vector3d axis : CARDINAL_AXES) {
|
||||
double d = vec.dot(axis);
|
||||
if (d > dot) {
|
||||
dot = d;
|
||||
cardinal = axis;
|
||||
}
|
||||
}
|
||||
|
||||
return cardinal;
|
||||
}
|
||||
|
||||
private static boolean isLegal(ProcessedBone.Cube cube) {
|
||||
return legalId(cube.getRotation().x) + legalId(cube.getRotation().y) + legalId(cube.getRotation().z) < 2;
|
||||
}
|
||||
|
||||
private static int legalId(double angle) {
|
||||
if (TMath.isInterval(angle, 90.0)) {
|
||||
return 0;
|
||||
} else {
|
||||
return TMath.isInterval(angle, 22.5) ? 1 : 999;
|
||||
}
|
||||
}
|
||||
|
||||
private RotationSolver() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.ticxo.modelengine.core.javasupport;
|
||||
|
||||
import com.ticxo.modelengine.api.utils.CompatibilityManager;
|
||||
import com.ticxo.modelengine.api.utils.MiscUtils;
|
||||
import com.ticxo.modelengine.api.utils.ReflectionUtils;
|
||||
import com.ticxo.modelengine.core.ModelEngine;
|
||||
|
||||
public enum Java21Access implements ReflectionUtils.MethodEnum {
|
||||
registerCompatibility(CompatibilityManager.class, ModelEngine.class),
|
||||
createNMSHandler(String.class),
|
||||
getMythicPackModelFiles();
|
||||
|
||||
private static Class<?> HELPER;
|
||||
private final Class<?>[] parameterClasses;
|
||||
|
||||
private static Class<?> getHelper() {
|
||||
if (!MiscUtils.isJavaVersionOrHigher(21)) {
|
||||
throw new RuntimeException("Cannot get Java 21 Helper: Server is not using Java 21+!");
|
||||
} else {
|
||||
if (HELPER == null) {
|
||||
try {
|
||||
HELPER = Class.forName("com.ticxo.modelengine.core21.Java21Helper");
|
||||
} catch (ClassNotFoundException var1) {
|
||||
throw new RuntimeException(var1);
|
||||
}
|
||||
}
|
||||
|
||||
return HELPER;
|
||||
}
|
||||
}
|
||||
|
||||
private Java21Access(Class<?>... parameterClasses) {
|
||||
this.parameterClasses = parameterClasses;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getTarget() {
|
||||
return getHelper();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getObfuscated() {
|
||||
return this.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMapped() {
|
||||
return this.toString();
|
||||
}
|
||||
|
||||
public <T> T call(Object... parameters) {
|
||||
return !MiscUtils.isJavaVersionOrHigher(21) ? null : ReflectionUtils.call(null, this, parameters);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?>[] getParameterClasses() {
|
||||
return this.parameterClasses;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.ticxo.modelengine.core.javasupport;
|
||||
|
||||
import com.ticxo.modelengine.api.utils.MiscUtils;
|
||||
import com.ticxo.modelengine.api.utils.ReflectionUtils;
|
||||
|
||||
public enum Java25Access implements ReflectionUtils.MethodEnum {
|
||||
createNMSHandler(String.class);
|
||||
|
||||
private static Class<?> HELPER;
|
||||
private final Class<?>[] parameterClasses;
|
||||
|
||||
private static Class<?> getHelper() {
|
||||
if (!MiscUtils.isJavaVersionOrHigher(25)) {
|
||||
throw new RuntimeException("Cannot get Java 25 Helper: Server is not using Java 25+!");
|
||||
} else {
|
||||
if (HELPER == null) {
|
||||
try {
|
||||
HELPER = Class.forName("com.ticxo.modelengine.core25.Java25Helper");
|
||||
} catch (ClassNotFoundException var1) {
|
||||
throw new RuntimeException(var1);
|
||||
}
|
||||
}
|
||||
|
||||
return HELPER;
|
||||
}
|
||||
}
|
||||
|
||||
private Java25Access(Class<?>... parameterClasses) {
|
||||
this.parameterClasses = parameterClasses;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getTarget() {
|
||||
return getHelper();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getObfuscated() {
|
||||
return this.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMapped() {
|
||||
return this.toString();
|
||||
}
|
||||
|
||||
public <T> T call(Object... parameters) {
|
||||
return !MiscUtils.isJavaVersionOrHigher(25) ? null : ReflectionUtils.call(null, this, parameters);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?>[] getParameterClasses() {
|
||||
return this.parameterClasses;
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.ticxo.modelengine.core.libsdisguises;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import me.libraryaddict.disguise.events.DisguiseEvent;
|
||||
import me.libraryaddict.disguise.events.UndisguiseEvent;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
public class DisguiseCompatibility implements Listener {
|
||||
private final Map<UUID, UUID> disguiseToEntity = new HashMap<>();
|
||||
|
||||
@EventHandler(
|
||||
priority = EventPriority.MONITOR
|
||||
)
|
||||
public void onDisguise(DisguiseEvent event) {
|
||||
this.disguiseToEntity.put(event.getDisguise().getUUID(), event.getDisguised().getUniqueId());
|
||||
}
|
||||
|
||||
@EventHandler(
|
||||
priority = EventPriority.MONITOR
|
||||
)
|
||||
public void onUndisguise(UndisguiseEvent event) {
|
||||
this.disguiseToEntity.remove(event.getDisguise().getUUID());
|
||||
}
|
||||
|
||||
public UUID getRelayOrDefault(UUID uuid) {
|
||||
return this.disguiseToEntity.getOrDefault(uuid, uuid);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.ticxo.modelengine.core.listener;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import io.papermc.paper.event.player.AsyncChatEvent;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Predicate;
|
||||
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
public class ChatListener implements Listener {
|
||||
private static final Map<UUID, Predicate<String>> FETCH_MAP = Maps.newConcurrentMap();
|
||||
|
||||
@EventHandler
|
||||
public void onAsyncChat(AsyncChatEvent event) {
|
||||
UUID uuid = event.getPlayer().getUniqueId();
|
||||
Predicate<String> fetch = FETCH_MAP.get(uuid);
|
||||
if (fetch != null) {
|
||||
event.setCancelled(true);
|
||||
if (fetch.test(PlainTextComponentSerializer.plainText().serialize(event.message()))) {
|
||||
FETCH_MAP.remove(uuid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void fetch(Player player, Predicate<String> consumer) {
|
||||
FETCH_MAP.put(player.getUniqueId(), consumer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.ticxo.modelengine.core.listener;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.MountManager;
|
||||
import com.ticxo.modelengine.api.mount.controller.MountController;
|
||||
import com.ticxo.modelengine.core.menu.SelectionManager;
|
||||
import com.ticxo.modelengine.core.menu.screen.NavigationScreen;
|
||||
import it.unimi.dsi.fastutil.Pair;
|
||||
import java.util.Optional;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.entity.EntityDamageByEntityEvent;
|
||||
import org.bukkit.event.entity.EntityDamageEvent;
|
||||
import org.bukkit.event.entity.EntityDeathEvent;
|
||||
import org.bukkit.event.entity.EntityPortalEvent;
|
||||
import org.bukkit.event.entity.EntityTeleportEvent;
|
||||
import org.bukkit.event.entity.ProjectileHitEvent;
|
||||
import org.bukkit.event.player.PlayerInteractEntityEvent;
|
||||
|
||||
public class EntityListener implements Listener {
|
||||
@EventHandler(
|
||||
priority = EventPriority.MONITOR
|
||||
)
|
||||
public void onEntityDamage(EntityDamageEvent event) {
|
||||
if (!event.isCancelled()) {
|
||||
ModeledEntity model = ModelEngineAPI.getModeledEntity(event.getEntity());
|
||||
if (model != null) {
|
||||
model.markHurt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onEntityAttacked(EntityDamageByEntityEvent event) {
|
||||
if (event.getDamager() instanceof Player player && SelectionManager.isSelecting(player)) {
|
||||
Entity target = event.getEntity();
|
||||
event.setCancelled(true);
|
||||
SelectionManager.setSelecting(player, false);
|
||||
SelectionManager.setSelected(player, target);
|
||||
player.sendActionBar(Component.text("Selected " + target.getName() + "."));
|
||||
new NavigationScreen(player).openScreen();
|
||||
} else {
|
||||
Pair<ActiveModel, MountController> pair = ModelEngineAPI.getMountPairManager().get(event.getDamager().getUniqueId());
|
||||
if (pair != null) {
|
||||
Object base = ((ActiveModel)pair.left()).getModeledEntity().getBase().getOriginal();
|
||||
MountController controller = (MountController)pair.right();
|
||||
if (base.equals(event.getEntity()) && !controller.canDamageMount()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onEntityInteracted(PlayerInteractEntityEvent event) {
|
||||
Pair<ActiveModel, MountController> pair = ModelEngineAPI.getMountPairManager().get(event.getPlayer().getUniqueId());
|
||||
if (pair != null) {
|
||||
Object base = ((ActiveModel)pair.left()).getModeledEntity().getBase().getOriginal();
|
||||
MountController controller = (MountController)pair.right();
|
||||
if (base.equals(event.getRightClicked()) && !controller.canInteractMount()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onProjectileHit(ProjectileHitEvent event) {
|
||||
if (event.getEntity().getShooter() instanceof Entity entity && event.getHitEntity() != null) {
|
||||
Pair<ActiveModel, MountController> pair = ModelEngineAPI.getMountPairManager().get(entity.getUniqueId());
|
||||
if (pair == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object base = ((ActiveModel)pair.left()).getModeledEntity().getBase().getOriginal();
|
||||
MountController controller = (MountController)pair.right();
|
||||
if (base.equals(event.getHitEntity()) && !controller.canDamageMount()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPortal(EntityPortalEvent event) {
|
||||
Entity entity = event.getEntity();
|
||||
if (ModelEngineAPI.getMountPairManager().get(entity.getUniqueId()) != null) {
|
||||
event.setCancelled(true);
|
||||
} else {
|
||||
ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(entity);
|
||||
if (modeledEntity != null) {
|
||||
for (ActiveModel model : modeledEntity.getModels().values()) {
|
||||
Optional manager = model.getMountManager();
|
||||
if (!manager.isEmpty() && ((MountManager)((BehaviorManager)manager.get())).hasPassengers()) {
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onTeleport(EntityTeleportEvent event) {
|
||||
if (!(event instanceof EntityPortalEvent)) {
|
||||
ModelEngineAPI.getMountPairManager().tryDismount(event.getEntity());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onDeath(EntityDeathEvent event) {
|
||||
ModelEngineAPI.getMountPairManager().tryDismount(event.getEntity());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.ticxo.modelengine.core.listener;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.menu.AbstractScreen;
|
||||
import com.ticxo.modelengine.api.menu.ScreenManager;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.event.inventory.InventoryCloseEvent;
|
||||
import org.bukkit.event.inventory.InventoryDragEvent;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
|
||||
public class InventoryListener implements Listener {
|
||||
@EventHandler
|
||||
public void onInventoryClick(InventoryClickEvent event) {
|
||||
if (!event.isCancelled()) {
|
||||
Inventory inventory = event.getInventory();
|
||||
AbstractScreen screen = this.getScreenManager().getScreen(inventory);
|
||||
if (screen != null && event.getWhoClicked() instanceof Player player) {
|
||||
if (event.getClickedInventory() == inventory) {
|
||||
event.setCancelled(true);
|
||||
screen.onClick(player, event.getSlot(), event);
|
||||
} else {
|
||||
screen.onClickPlayer(player, event.getSlot(), event);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onInventoryDrag(InventoryDragEvent event) {
|
||||
if (this.getScreenManager().isScreen(event.getInventory())) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onInventoryClose(InventoryCloseEvent event) {
|
||||
this.getScreenManager().unregisterScreen(event.getInventory());
|
||||
}
|
||||
|
||||
private ScreenManager getScreenManager() {
|
||||
return ModelEngineAPI.getAPI().getScreenManager();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.ticxo.modelengine.core.listener;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.ServerInfo;
|
||||
import com.ticxo.modelengine.api.entity.BukkitPlayer;
|
||||
import com.ticxo.modelengine.api.entity.cull.BasicCulling;
|
||||
import com.ticxo.modelengine.api.entity.data.BukkitEntityData;
|
||||
import com.ticxo.modelengine.api.lod.AnimationLODHandler;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.api.nms.network.ModPlayerTracker;
|
||||
import com.ticxo.modelengine.core.menu.SelectionManager;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.entity.PlayerDeathEvent;
|
||||
import org.bukkit.event.player.PlayerChangedWorldEvent;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerMoveEvent;
|
||||
import org.bukkit.event.player.PlayerPortalEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.player.PlayerRegisterChannelEvent;
|
||||
import org.bukkit.event.player.PlayerTeleportEvent;
|
||||
import org.bukkit.event.player.PlayerUnregisterChannelEvent;
|
||||
import org.bukkit.util.Vector;
|
||||
|
||||
public class PlayerListener implements Listener {
|
||||
@EventHandler
|
||||
public void onJoin(PlayerJoinEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
ServerInfo.setOnline(player.getUniqueId(), true);
|
||||
ModelEngineAPI.getNetworkHandler().injectChannel(player);
|
||||
AnimationLODHandler.registerPlayer(player.getUniqueId());
|
||||
if (ModelEngineAPI.getConfigCache().isEagerGenerate()) {
|
||||
ModelEngineAPI.getUserLimbRegistry().generate(player);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
ServerInfo.setOnline(player.getUniqueId(), false);
|
||||
ModelEngineAPI.getNetworkHandler().ejectChannel(player);
|
||||
ModelEngineAPI.getMountPairManager().tryDismount(player);
|
||||
ModelEngineAPI.getInteractionTracker().removeDynamicHitbox(player.getUniqueId());
|
||||
ModelEngineAPI.getEntityHandler().setForcedInvisible(player, false);
|
||||
SelectionManager.removePlayer(event.getPlayer());
|
||||
AnimationLODHandler.setPlayerActive(event.getPlayer().getUniqueId(), false);
|
||||
BasicCulling.setGlobalCullExempt(player.getUniqueId(), false);
|
||||
ModelEngineAPI.getPivotOverrideRegistry().remove(player.getUniqueId());
|
||||
ModPlayerTracker.removePlayer(player.getUniqueId());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onChannelRegister(PlayerRegisterChannelEvent event) {
|
||||
if ("modelengine:bulk_data".equals(event.getChannel())) {
|
||||
ModPlayerTracker.addPlayer(event.getPlayer().getUniqueId());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onChannelUnregister(PlayerUnregisterChannelEvent event) {
|
||||
if ("modelengine:bulk_data".equals(event.getChannel())) {
|
||||
ModPlayerTracker.removePlayer(event.getPlayer().getUniqueId());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPortal(PlayerPortalEvent event) {
|
||||
Player entity = event.getPlayer();
|
||||
if (ModelEngineAPI.getMountPairManager().get(entity.getUniqueId()) != null) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onTeleport(PlayerTeleportEvent event) {
|
||||
if (!(event instanceof PlayerPortalEvent)) {
|
||||
ModelEngineAPI.getMountPairManager().tryDismount(event.getPlayer());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onChangedWorld(PlayerChangedWorldEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(player.getUniqueId());
|
||||
if (modeledEntity != null) {
|
||||
if (modeledEntity.getBase().getData() instanceof BukkitEntityData data) {
|
||||
data.resendTracking(player.getUniqueId());
|
||||
}
|
||||
|
||||
ModelEngineAPI.getPivotOverrideRegistry().get(player.getUniqueId()).ifPresent(override -> override.getPassengers().markDirty());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onDeath(PlayerDeathEvent event) {
|
||||
ModelEngineAPI.getMountPairManager().tryDismount(event.getPlayer());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onMove(PlayerMoveEvent event) {
|
||||
Vector dir = event.getTo().toVector().subtract(event.getFrom().toVector());
|
||||
if (!dir.isZero()) {
|
||||
Player player = event.getPlayer();
|
||||
ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(player.getUniqueId());
|
||||
if (modeledEntity != null) {
|
||||
if (modeledEntity.getBase().getData() instanceof BukkitPlayer.BukkitPlayerData playerData) {
|
||||
if (dir.getX() != 0.0 || dir.getZ() != 0.0) {
|
||||
playerData.setWalkTick(3);
|
||||
}
|
||||
|
||||
if (dir.getY() > 0.0) {
|
||||
playerData.setJumpTick(3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package com.ticxo.modelengine.core.listener;
|
||||
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.ServerInfo;
|
||||
import com.ticxo.modelengine.api.generator.ModelGenerator;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.api.utils.config.ConfigProperty;
|
||||
import com.ticxo.modelengine.api.utils.data.io.SavedData;
|
||||
import com.ticxo.modelengine.api.utils.ticker.DualTicker;
|
||||
import com.ticxo.modelengine.core.data.DataUpdater;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import net.citizensnpcs.api.CitizensAPI;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.world.EntitiesLoadEvent;
|
||||
import org.bukkit.event.world.EntitiesUnloadEvent;
|
||||
import org.bukkit.event.world.WorldLoadEvent;
|
||||
import org.bukkit.event.world.WorldUnloadEvent;
|
||||
import org.bukkit.persistence.PersistentDataContainer;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
public class WorldListener implements Listener {
|
||||
private static final int PHANTOM_UNLOAD_RECHECK_TICKS = 5;
|
||||
private final ModelGenerator generator;
|
||||
private boolean onWorldLoad = false;
|
||||
private boolean onWorldUnload = false;
|
||||
|
||||
public WorldListener() {
|
||||
this.generator = ModelEngineAPI.getAPI().getModelGenerator();
|
||||
ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> {
|
||||
this.onWorldLoad = ConfigProperty.LOAD_ON_WORLD_LOAD.getBoolean();
|
||||
this.onWorldUnload = ConfigProperty.UNLOAD_ON_WORLD_UNLOAD.getBoolean();
|
||||
});
|
||||
}
|
||||
|
||||
@EventHandler(
|
||||
priority = EventPriority.MONITOR
|
||||
)
|
||||
private void onWorldLoad(WorldLoadEvent event) {
|
||||
if (this.onWorldLoad) {
|
||||
if (this.generator.isInitialized()) {
|
||||
this.loadEntities(event.getWorld().getEntities());
|
||||
} else {
|
||||
this.generator.queueTask(ModelGenerator.Phase.POST_IMPORT, () -> DualTicker.queueSyncTask(() -> this.loadEntities(event.getWorld().getEntities())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(
|
||||
priority = EventPriority.MONITOR
|
||||
)
|
||||
private void onWorldUnload(WorldUnloadEvent event) {
|
||||
if (this.onWorldUnload) {
|
||||
if (this.generator.isInitialized()) {
|
||||
this.unloadEntities(event.getWorld().getEntities());
|
||||
} else {
|
||||
this.generator
|
||||
.queueTask(ModelGenerator.Phase.POST_IMPORT, () -> DualTicker.queueSyncTask(() -> this.unloadEntities(event.getWorld().getEntities())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(
|
||||
priority = EventPriority.LOWEST
|
||||
)
|
||||
private void onEntityLoad(EntitiesLoadEvent event) {
|
||||
if (!this.onWorldLoad) {
|
||||
if (this.generator.isInitialized()) {
|
||||
this.loadEntities(event.getEntities());
|
||||
} else {
|
||||
this.generator.queueTask(ModelGenerator.Phase.POST_IMPORT, () -> DualTicker.queueSyncTask(() -> this.loadEntities(event.getEntities())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(
|
||||
priority = EventPriority.MONITOR
|
||||
)
|
||||
private void onEntityUnload(EntitiesUnloadEvent event) {
|
||||
if (!this.onWorldUnload) {
|
||||
if (this.generator.isInitialized()) {
|
||||
this.unloadEntities(event.getEntities());
|
||||
} else {
|
||||
this.generator.queueTask(ModelGenerator.Phase.POST_IMPORT, () -> DualTicker.queueSyncTask(() -> this.unloadEntities(event.getEntities())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void loadEntities(List<Entity> entities) {
|
||||
for (Entity entity : entities) {
|
||||
if (!(entity instanceof Player) && !ServerInfo.scheduleOnRegion(entity, () -> this.restoreSavedModel(entity))) {
|
||||
this.restoreSavedModel(entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void restoreSavedModel(Entity entity) {
|
||||
if (ModelEngineAPI.getModeledEntity(entity.getUniqueId()) == null) {
|
||||
String jsonData = (String)entity.getPersistentDataContainer().get(SavedData.DATA_KEY, PersistentDataType.STRING);
|
||||
if (jsonData != null) {
|
||||
try {
|
||||
SavedData data = DataUpdater.convertToSavedData(entity.getLocation(), jsonData);
|
||||
if (!DataUpdater.tryUpdate(data)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ModeledEntity model = ModelEngineAPI.createModeledEntity(entity);
|
||||
model.load(data);
|
||||
} catch (JsonSyntaxException var5) {
|
||||
var5.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void unloadEntities(List<Entity> entities) {
|
||||
List<Entity> unloaded = null;
|
||||
|
||||
for (Entity entity : entities) {
|
||||
if (!(entity instanceof Player) && (!ServerInfo.HAS_CITIZENS || !CitizensAPI.getNPCRegistry().isNPC(entity))) {
|
||||
PersistentDataContainer pdc = entity.getPersistentDataContainer();
|
||||
ModeledEntity model = ModelEngineAPI.getModeledEntity(entity.getUniqueId());
|
||||
if (model == null) {
|
||||
pdc.remove(SavedData.DATA_KEY);
|
||||
} else {
|
||||
if (model.shouldBeSaved()) {
|
||||
try {
|
||||
String cachedJson = model.getCachedSaveJson();
|
||||
if (cachedJson != null) {
|
||||
pdc.set(SavedData.DATA_KEY, PersistentDataType.STRING, cachedJson);
|
||||
} else {
|
||||
model.save()
|
||||
.ifPresentOrElse(
|
||||
data -> pdc.set(SavedData.DATA_KEY, PersistentDataType.STRING, data.toString()), () -> pdc.remove(SavedData.DATA_KEY)
|
||||
);
|
||||
}
|
||||
} catch (Throwable var8) {
|
||||
throw new IllegalStateException(
|
||||
"Failed to save data for entity "
|
||||
+ entity.getType()
|
||||
+ " "
|
||||
+ entity.getUniqueId()
|
||||
+ " at "
|
||||
+ entity.getLocation().getX()
|
||||
+ ","
|
||||
+ entity.getLocation().getY()
|
||||
+ ","
|
||||
+ entity.getLocation().getZ(),
|
||||
var8
|
||||
);
|
||||
}
|
||||
} else {
|
||||
entity.getPersistentDataContainer().remove(SavedData.DATA_KEY);
|
||||
}
|
||||
|
||||
ModelEngineAPI.getEntityHandler().setForcedInvisible(entity, false);
|
||||
ModelEngineAPI.getAPI().getModelUpdaters().forceRemoveModeledEntity(model);
|
||||
if (model.shouldBeSaved()) {
|
||||
if (unloaded == null) {
|
||||
unloaded = new ArrayList<>();
|
||||
}
|
||||
|
||||
unloaded.add(entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (unloaded != null) {
|
||||
List<Entity> recheck = unloaded;
|
||||
if (ServerInfo.IS_FOLIA) {
|
||||
for (Entity entityx : recheck) {
|
||||
ServerInfo.scheduleOnRegionDelayed(entityx, () -> {
|
||||
if (entityx.isValid()) {
|
||||
this.restoreSavedModel(entityx);
|
||||
}
|
||||
}, 5L);
|
||||
}
|
||||
} else {
|
||||
DualTicker.queueDelayedSyncTask(() -> {
|
||||
for (Entity entityx : recheck) {
|
||||
if (entityx.isValid()) {
|
||||
this.restoreSavedModel(entityx);
|
||||
}
|
||||
}
|
||||
}, 5);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.ticxo.modelengine.core.menu;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.common.collect.Sets;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class SelectionManager {
|
||||
private static final Set<UUID> SELECTING = Sets.newConcurrentHashSet();
|
||||
private static final Map<UUID, Entity> SELECTED = Maps.newConcurrentMap();
|
||||
|
||||
public static void setSelecting(Player player, boolean flag) {
|
||||
if (flag) {
|
||||
SELECTING.add(player.getUniqueId());
|
||||
} else {
|
||||
SELECTING.remove(player.getUniqueId());
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isSelecting(Player player) {
|
||||
return SELECTING.contains(player.getUniqueId());
|
||||
}
|
||||
|
||||
public static void setSelected(Player player, @Nullable Entity entity) {
|
||||
if (entity == null) {
|
||||
SELECTED.remove(player.getUniqueId());
|
||||
} else {
|
||||
SELECTED.put(player.getUniqueId(), entity);
|
||||
}
|
||||
}
|
||||
|
||||
public static Entity getSelected(Player player) {
|
||||
return SELECTED.get(player.getUniqueId());
|
||||
}
|
||||
|
||||
public static void removePlayer(Player player) {
|
||||
SELECTING.remove(player.getUniqueId());
|
||||
SELECTED.remove(player.getUniqueId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.ticxo.modelengine.core.menu.screen;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.menu.AbstractScreen;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.ModelRegistry;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.api.utils.data.ComponentUtil;
|
||||
import com.ticxo.modelengine.api.utils.data.ItemUtils;
|
||||
import com.ticxo.modelengine.core.menu.widget.BasicItemWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.BorderWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.CloseWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.PaginatorWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.page.AbstractModelButton;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.TextDecoration;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
public class AddModelScreen extends AbstractScreen {
|
||||
private final Entity selected;
|
||||
private final PaginatorWidget page;
|
||||
|
||||
public AddModelScreen(AbstractScreen rootScreen, Player viewer, Entity selected) {
|
||||
super(viewer, "Add Model", 6);
|
||||
this.selected = selected;
|
||||
this.addWidget(new BorderWidget());
|
||||
this.page = new PaginatorWidget();
|
||||
this.addWidget(this.page);
|
||||
ModelRegistry registry = ModelEngineAPI.getAPI().getModelRegistry();
|
||||
ItemStack statSign = new ItemStack(Material.OAK_SIGN);
|
||||
ItemUtils.name(statSign, Component.text("Stats", ComponentUtil.reset().decoration(TextDecoration.BOLD, true)));
|
||||
ItemUtils.lore(statSign, Component.empty(), Component.text("Models: " + registry.getKeys().size(), ComponentUtil.reset()));
|
||||
this.addWidget(new BasicItemWidget(53, statSign));
|
||||
this.addWidget(new CloseWidget(rootScreen));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void openScreen() {
|
||||
this.updatePage();
|
||||
super.openScreen();
|
||||
}
|
||||
|
||||
private void updatePage() {
|
||||
this.page.clearButtons();
|
||||
ModelRegistry registry = ModelEngineAPI.getAPI().getModelRegistry();
|
||||
ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.selected);
|
||||
|
||||
for (String modelId : registry.getOrderedId()) {
|
||||
if (modeledEntity == null || !modeledEntity.getModel(modelId).isPresent()) {
|
||||
ModelBlueprint blueprint = registry.get(modelId);
|
||||
AddModelScreen.ModelButton button = new AddModelScreen.ModelButton(blueprint);
|
||||
this.page.addButton(button);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ModelButton extends AbstractModelButton {
|
||||
public ModelButton(ModelBlueprint blueprint) {
|
||||
super(blueprint);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
ModeledEntity modeledEntity = ModelEngineAPI.getOrCreateModeledEntity(AddModelScreen.this.selected, me -> me.setBaseEntityVisible(false));
|
||||
ActiveModel activeModel = ModelEngineAPI.createActiveModel(this.blueprint);
|
||||
modeledEntity.addModel(activeModel, true).ifPresent(ActiveModel::destroy);
|
||||
AddModelScreen.this.updatePage();
|
||||
AddModelScreen.this.draw(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
package com.ticxo.modelengine.core.menu.screen;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.menu.AbstractScreen;
|
||||
import com.ticxo.modelengine.api.menu.Widget;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.api.utils.MiscUtils;
|
||||
import com.ticxo.modelengine.api.utils.data.ComponentUtil;
|
||||
import com.ticxo.modelengine.api.utils.data.ItemUtils;
|
||||
import com.ticxo.modelengine.api.utils.ticker.DualTicker;
|
||||
import com.ticxo.modelengine.core.listener.ChatListener;
|
||||
import com.ticxo.modelengine.core.menu.widget.BorderWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.CloseWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.PaginatorWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.TabWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.page.AbstractModelButton;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import net.kyori.adventure.text.format.TextDecoration;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class EditEntityScreen extends AbstractScreen {
|
||||
private final Entity selected;
|
||||
private final TabWidget tab;
|
||||
|
||||
public EditEntityScreen(AbstractScreen rootScreen, Player viewer, @NotNull Entity selected) {
|
||||
super(viewer, "Editing: " + selected.getName(), 6);
|
||||
this.selected = selected;
|
||||
this.addWidget(new BorderWidget());
|
||||
this.tab = new TabWidget();
|
||||
this.tab.addTab(new EditEntityScreen.SettingsTab());
|
||||
this.tab.addTab(new EditEntityScreen.ModelTab());
|
||||
this.addWidget(this.tab);
|
||||
this.addWidget(new EditEntityScreen.EntityStatsWidget());
|
||||
this.addWidget(new CloseWidget(rootScreen));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void openScreen() {
|
||||
if (this.tab.getSelectedTab() instanceof EditEntityScreen.ModelTab modelTab) {
|
||||
modelTab.updatePage();
|
||||
}
|
||||
|
||||
super.openScreen();
|
||||
}
|
||||
|
||||
class EntityStatsWidget implements Widget {
|
||||
private static final int SLOT = 53;
|
||||
private final ItemStack stack = new ItemStack(Material.OAK_SIGN);
|
||||
|
||||
public EntityStatsWidget() {
|
||||
this.updateStats();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemForSlot(int size, int slot) {
|
||||
return slot == 53 ? this.stack : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
if (slot == 53) {
|
||||
if (event.isLeftClick()) {
|
||||
this.updateStats();
|
||||
EditEntityScreen.this.markSlotDirty(53);
|
||||
} else if (event.isRightClick()) {
|
||||
player.teleport(EditEntityScreen.this.selected.getLocation());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void updateStats() {
|
||||
String location = EditEntityScreen.this.selected.getLocation().getBlockX()
|
||||
+ ", "
|
||||
+ EditEntityScreen.this.selected.getLocation().getBlockY()
|
||||
+ ", "
|
||||
+ EditEntityScreen.this.selected.getLocation().getBlockZ();
|
||||
ItemUtils.name(this.stack, Component.text("Stats", ComponentUtil.reset().decoration(TextDecoration.BOLD, true)));
|
||||
ItemUtils.lore(
|
||||
this.stack,
|
||||
Component.empty(),
|
||||
Component.text("Type: ", ComponentUtil.reset()).append(Component.translatable(EditEntityScreen.this.selected.getType().getTranslationKey())),
|
||||
Component.text("UUID: " + EditEntityScreen.this.selected.getUniqueId(), ComponentUtil.reset()),
|
||||
Component.text("Position: " + location, ComponentUtil.reset()),
|
||||
Component.text("Status: " + (EditEntityScreen.this.selected.isDead() ? "Dead" : "Alive"), ComponentUtil.reset()),
|
||||
Component.empty(),
|
||||
Component.text("Left click to refresh stats.", ComponentUtil.color(NamedTextColor.DARK_GRAY)),
|
||||
Component.text("Right click to teleport to entity.", ComponentUtil.color(NamedTextColor.DARK_GRAY))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ModelTab implements TabWidget.Tab {
|
||||
private final ItemStack stack = new ItemStack(Material.ARMOR_STAND);
|
||||
private final PaginatorWidget page;
|
||||
|
||||
public ModelTab() {
|
||||
ItemUtils.name(this.stack, Component.text("Models", ComponentUtil.reset()));
|
||||
this.page = new PaginatorWidget();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemStack() {
|
||||
return this.stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Widget getWidget() {
|
||||
return this.page;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSelect() {
|
||||
this.updatePage();
|
||||
}
|
||||
|
||||
private void updatePage() {
|
||||
this.page.clearButtons();
|
||||
ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(EditEntityScreen.this.selected);
|
||||
if (modeledEntity != null) {
|
||||
for (ActiveModel model : modeledEntity.getModels().values()) {
|
||||
EditEntityScreen.ModelTab.ModelButton button = new EditEntityScreen.ModelTab.ModelButton(model);
|
||||
this.page.addButton(button);
|
||||
}
|
||||
}
|
||||
|
||||
this.page.addButton(new EditEntityScreen.ModelTab.AddModelButton());
|
||||
}
|
||||
|
||||
class AddModelButton implements PaginatorWidget.PageButton {
|
||||
private final ItemStack stack = new ItemStack(Material.NETHER_STAR);
|
||||
|
||||
public AddModelButton() {
|
||||
ItemUtils.name(this.stack, Component.text("Add Model", ComponentUtil.reset()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemStack() {
|
||||
return this.stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
new AddModelScreen(screen, player, EditEntityScreen.this.selected).openScreen();
|
||||
}
|
||||
}
|
||||
|
||||
class ModelButton extends AbstractModelButton {
|
||||
private final ActiveModel model;
|
||||
|
||||
public ModelButton(ActiveModel model) {
|
||||
super(model.getBlueprint());
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void updateItem() {
|
||||
ItemUtils.name(this.stack, Component.text(this.blueprint.getName(), ComponentUtil.reset()));
|
||||
ItemUtils.lore(
|
||||
this.stack,
|
||||
Component.empty(),
|
||||
Component.text("Model ID: " + this.blueprint.getName(), ComponentUtil.reset()),
|
||||
Component.text("Hitbox: " + this.blueprint.getMainHitbox().toSimpleString(), ComponentUtil.reset()),
|
||||
Component.text("Eye Height: " + this.blueprint.getMainHitbox().toEyeHeightString(), ComponentUtil.reset()),
|
||||
Component.text("Shadow: " + this.blueprint.getShadowRadius(), ComponentUtil.reset()),
|
||||
Component.text("Bone Count: " + this.blueprint.getFlatMap().size(), ComponentUtil.reset()),
|
||||
Component.empty(),
|
||||
Component.text("Shift-click to remove model.", ComponentUtil.color(NamedTextColor.DARK_GRAY))
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
if (event.isShiftClick()) {
|
||||
ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(EditEntityScreen.this.selected);
|
||||
if (modeledEntity == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
modeledEntity.removeModel(this.model.getBlueprint().getName()).ifPresent(ActiveModel::destroy);
|
||||
if (modeledEntity.getModels().isEmpty()) {
|
||||
modeledEntity.setBaseEntityVisible(true);
|
||||
ModelEngineAPI.removeModeledEntity(EditEntityScreen.this.selected);
|
||||
}
|
||||
|
||||
ModelTab.this.updatePage();
|
||||
EditEntityScreen.this.draw(true);
|
||||
} else {
|
||||
new EditModelScreen(screen, player, this.model).openScreen();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SettingsTab implements TabWidget.Tab {
|
||||
private final ItemStack stack = new ItemStack(Material.COMMAND_BLOCK);
|
||||
private final EditEntityScreen.SettingsWidget widget;
|
||||
|
||||
public SettingsTab() {
|
||||
ItemUtils.name(this.stack, Component.text("Entity Settings", ComponentUtil.reset()));
|
||||
this.widget = EditEntityScreen.this.new SettingsWidget();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemStack() {
|
||||
return this.stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Widget getWidget() {
|
||||
return this.widget;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSelect() {
|
||||
}
|
||||
}
|
||||
|
||||
class SettingsWidget implements Widget {
|
||||
private static final int VISIBLE_SLOT = 29;
|
||||
private static final int SAVED_SLOT = 30;
|
||||
private static final int ROT_LOCK_SLOT = 31;
|
||||
private static final int RENDER_RADIUS_SLOT = 32;
|
||||
private static final int STEP_HEIGHT_SLOT = 33;
|
||||
private final ModeledEntity modeledEntity = ModelEngineAPI.getOrCreateModeledEntity(EditEntityScreen.this.selected, me -> me.setBaseEntityVisible(false));
|
||||
private final ItemStack visible = new ItemStack(Material.ENDER_EYE);
|
||||
private final ItemStack saved;
|
||||
private final ItemStack rotLock;
|
||||
private final ItemStack renderRadius;
|
||||
private final ItemStack stepHeight;
|
||||
|
||||
public SettingsWidget() {
|
||||
ItemUtils.name(
|
||||
this.visible,
|
||||
Component.text(
|
||||
"Base Entity Visible: " + this.modeledEntity.isBaseEntityVisible(),
|
||||
ComponentUtil.color(this.modeledEntity.isBaseEntityVisible() ? NamedTextColor.GREEN : NamedTextColor.RED)
|
||||
)
|
||||
);
|
||||
ItemUtils.lore(this.visible, Component.empty(), Component.text("Is the actual entity visible.", ComponentUtil.reset()));
|
||||
this.saved = new ItemStack(Material.CHEST);
|
||||
ItemUtils.name(
|
||||
this.saved,
|
||||
Component.text(
|
||||
"Model Persistent: " + this.modeledEntity.shouldBeSaved(),
|
||||
ComponentUtil.color(this.modeledEntity.shouldBeSaved() ? NamedTextColor.GREEN : NamedTextColor.RED)
|
||||
)
|
||||
);
|
||||
ItemUtils.lore(this.saved, Component.empty(), Component.text("Should the models be saved on unload.", ComponentUtil.reset()));
|
||||
this.rotLock = new ItemStack(Material.COMPASS);
|
||||
ItemUtils.name(
|
||||
this.rotLock,
|
||||
Component.text(
|
||||
"Rotation Locked: " + this.modeledEntity.isModelRotationLocked(),
|
||||
ComponentUtil.color(this.modeledEntity.isModelRotationLocked() ? NamedTextColor.GREEN : NamedTextColor.RED)
|
||||
)
|
||||
);
|
||||
ItemUtils.lore(this.rotLock, Component.empty(), Component.text("Can the models rotate with the entity.", ComponentUtil.reset()));
|
||||
this.renderRadius = new ItemStack(Material.SPYGLASS);
|
||||
ItemUtils.name(this.renderRadius, Component.text("Render Radius: " + this.modeledEntity.getBase().getRenderRadius(), ComponentUtil.reset()));
|
||||
ItemUtils.lore(this.renderRadius, Component.empty(), Component.text("The render radius of the entity in blocks.", ComponentUtil.reset()));
|
||||
this.stepHeight = new ItemStack(Material.STONE_STAIRS);
|
||||
ItemUtils.name(
|
||||
this.stepHeight,
|
||||
Component.text("Step Height: " + MiscUtils.FORMATTER.format(this.modeledEntity.getBase().getMaxStepHeight()), ComponentUtil.reset())
|
||||
);
|
||||
ItemUtils.lore(this.stepHeight, Component.empty(), Component.text("The step height of the entity in blocks.", ComponentUtil.reset()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemForSlot(int size, int slot) {
|
||||
return switch (slot) {
|
||||
case 29 -> this.visible;
|
||||
case 30 -> this.saved;
|
||||
case 31 -> this.rotLock;
|
||||
case 32 -> this.renderRadius;
|
||||
case 33 -> this.stepHeight;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
switch (slot) {
|
||||
case 29:
|
||||
this.modeledEntity.setBaseEntityVisible(!this.modeledEntity.isBaseEntityVisible());
|
||||
ItemUtils.name(
|
||||
this.visible,
|
||||
Component.text(
|
||||
"Base Entity Visible: " + this.modeledEntity.isBaseEntityVisible(),
|
||||
ComponentUtil.color(this.modeledEntity.isBaseEntityVisible() ? NamedTextColor.GREEN : NamedTextColor.RED)
|
||||
)
|
||||
);
|
||||
screen.markSlotDirty(29);
|
||||
break;
|
||||
case 30:
|
||||
this.modeledEntity.setSaved(!this.modeledEntity.shouldBeSaved());
|
||||
ItemUtils.name(
|
||||
this.saved,
|
||||
Component.text(
|
||||
"Model Persistent: " + this.modeledEntity.shouldBeSaved(),
|
||||
ComponentUtil.color(this.modeledEntity.shouldBeSaved() ? NamedTextColor.GREEN : NamedTextColor.RED)
|
||||
)
|
||||
);
|
||||
screen.markSlotDirty(30);
|
||||
break;
|
||||
case 31:
|
||||
this.modeledEntity.setModelRotationLocked(!this.modeledEntity.isModelRotationLocked());
|
||||
ItemUtils.name(
|
||||
this.rotLock,
|
||||
Component.text(
|
||||
"Rotation Locked: " + this.modeledEntity.isModelRotationLocked(),
|
||||
ComponentUtil.color(this.modeledEntity.isModelRotationLocked() ? NamedTextColor.GREEN : NamedTextColor.RED)
|
||||
)
|
||||
);
|
||||
screen.markSlotDirty(31);
|
||||
break;
|
||||
case 32:
|
||||
player.closeInventory();
|
||||
ComponentUtil.sendMessage(player, Component.text("[ModelEngine] Enter render radius:", ComponentUtil.color(NamedTextColor.AQUA)));
|
||||
ChatListener.fetch(
|
||||
player,
|
||||
s -> {
|
||||
try {
|
||||
this.modeledEntity.getBase().setRenderRadius(Integer.parseInt(s));
|
||||
ComponentUtil.sendMessage(
|
||||
player, Component.text("[ModelEngine] Set render radius of model to " + s + ".", ComponentUtil.color(NamedTextColor.GREEN))
|
||||
);
|
||||
screen.markSlotDirty(32);
|
||||
DualTicker.queueSyncTask(EditEntityScreen.this::openScreen);
|
||||
return true;
|
||||
} catch (NumberFormatException var5) {
|
||||
ComponentUtil.sendMessage(
|
||||
player, Component.text("[ModelEngine] \"" + s + "\" is not an integer. Try again.", ComponentUtil.color(NamedTextColor.RED))
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
);
|
||||
break;
|
||||
case 33:
|
||||
player.closeInventory();
|
||||
ComponentUtil.sendMessage(player, Component.text("[ModelEngine] Enter step height:", ComponentUtil.color(NamedTextColor.AQUA)));
|
||||
ChatListener.fetch(
|
||||
player,
|
||||
s -> {
|
||||
try {
|
||||
this.modeledEntity.getBase().setMaxStepHeight(Double.parseDouble(s));
|
||||
ComponentUtil.sendMessage(
|
||||
player, Component.text("[ModelEngine] Set step height of model to " + s + ".", ComponentUtil.color(NamedTextColor.GREEN))
|
||||
);
|
||||
screen.markSlotDirty(33);
|
||||
DualTicker.queueSyncTask(EditEntityScreen.this::openScreen);
|
||||
return true;
|
||||
} catch (NumberFormatException var5) {
|
||||
ComponentUtil.sendMessage(
|
||||
player, Component.text("[ModelEngine] \"" + s + "\" is not a number. Try again.", ComponentUtil.color(NamedTextColor.RED))
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,683 @@
|
||||
package com.ticxo.modelengine.core.menu.screen;
|
||||
|
||||
import com.ticxo.modelengine.api.animation.BlueprintAnimation;
|
||||
import com.ticxo.modelengine.api.animation.handler.AnimationHandler;
|
||||
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
|
||||
import com.ticxo.modelengine.api.animation.property.SimpleProperty;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.menu.AbstractScreen;
|
||||
import com.ticxo.modelengine.api.menu.Widget;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.utils.MiscUtils;
|
||||
import com.ticxo.modelengine.api.utils.data.ComponentUtil;
|
||||
import com.ticxo.modelengine.api.utils.data.ItemUtils;
|
||||
import com.ticxo.modelengine.api.utils.ticker.DualTicker;
|
||||
import com.ticxo.modelengine.core.animation.handler.StateMachineHandler;
|
||||
import com.ticxo.modelengine.core.listener.ChatListener;
|
||||
import com.ticxo.modelengine.core.menu.widget.BorderWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.CloseWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.CompositeWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.PaginatorWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.TabWidget;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import net.kyori.adventure.text.format.Style;
|
||||
import net.kyori.adventure.text.format.TextColor;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.ItemFlag;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
public class EditModelScreen extends AbstractScreen {
|
||||
private final ActiveModel model;
|
||||
private final TabWidget tab;
|
||||
|
||||
public EditModelScreen(AbstractScreen rootScreen, Player viewer, ActiveModel model) {
|
||||
super(viewer, model.getBlueprint().getName(), 6);
|
||||
this.model = model;
|
||||
this.addWidget(new BorderWidget());
|
||||
this.tab = new TabWidget();
|
||||
this.tab.addTab(new EditModelScreen.SettingsTab());
|
||||
this.tab.addTab(new EditModelScreen.BoneTab());
|
||||
this.tab.addTab(new EditModelScreen.AnimationTab());
|
||||
this.addWidget(this.tab);
|
||||
this.addWidget(new CloseWidget(rootScreen));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTick() {
|
||||
if (this.tab.getSelectedTab() instanceof EditModelScreen.AnimationTab animationTab) {
|
||||
animationTab.onTick();
|
||||
}
|
||||
|
||||
super.onTick();
|
||||
}
|
||||
|
||||
class AnimationTab implements TabWidget.Tab {
|
||||
private final ItemStack stack = new ItemStack(Material.ARMOR_STAND);
|
||||
private final CompositeWidget composite;
|
||||
private final PaginatorWidget page;
|
||||
private final EditModelScreen.AnimationTab.PriorityButton priority;
|
||||
|
||||
public AnimationTab() {
|
||||
ItemUtils.name(this.stack, Component.text("Animations", ComponentUtil.reset()));
|
||||
this.page = new PaginatorWidget();
|
||||
if (EditModelScreen.this.model.getAnimationHandler() instanceof StateMachineHandler) {
|
||||
this.priority = new EditModelScreen.AnimationTab.PriorityButton();
|
||||
this.composite = new CompositeWidget(this.page, this.priority);
|
||||
} else {
|
||||
this.priority = null;
|
||||
this.composite = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemStack() {
|
||||
return this.stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Widget getWidget() {
|
||||
return (Widget)(this.composite != null ? this.composite : this.page);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSelect() {
|
||||
this.page.clearButtons();
|
||||
ModelBlueprint blueprint = EditModelScreen.this.model.getBlueprint();
|
||||
Map<String, BlueprintAnimation> pairs = blueprint.getAnimations();
|
||||
|
||||
for (Entry<String, BlueprintAnimation> entry : pairs.entrySet()) {
|
||||
this.page.addButton(new EditModelScreen.AnimationTab.AnimationButton(entry.getValue()));
|
||||
}
|
||||
}
|
||||
|
||||
protected void onTick() {
|
||||
int i = 19;
|
||||
|
||||
while (i <= 43) {
|
||||
switch (i % 9) {
|
||||
default:
|
||||
if (this.page.getButton(i) instanceof EditModelScreen.AnimationTab.AnimationButton button && button.update(false)) {
|
||||
EditModelScreen.this.markSlotDirty(i);
|
||||
}
|
||||
case 0:
|
||||
case 8:
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class AnimationButton implements PaginatorWidget.PageButton {
|
||||
private final BlueprintAnimation animation;
|
||||
private ItemStack stack;
|
||||
private IAnimationProperty trackedProperty;
|
||||
private int lastHash;
|
||||
|
||||
public AnimationButton(BlueprintAnimation animation) {
|
||||
this.animation = animation;
|
||||
this.update(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemStack() {
|
||||
return this.stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
AnimationHandler handler = EditModelScreen.this.model.getAnimationHandler();
|
||||
SimpleProperty prop = new SimpleProperty(EditModelScreen.this.model, this.animation);
|
||||
if (prop.getLoopMode() == BlueprintAnimation.LoopMode.LOOP) {
|
||||
prop.setSkipLastFrame(true);
|
||||
}
|
||||
|
||||
if (handler instanceof StateMachineHandler stateMachineHandler) {
|
||||
if (stateMachineHandler.isPlayingAnimation(AnimationTab.this.priority.priority, this.animation.getName())) {
|
||||
stateMachineHandler.stopAnimation(AnimationTab.this.priority.priority, this.animation.getName());
|
||||
} else {
|
||||
stateMachineHandler.playAnimation(AnimationTab.this.priority.priority, prop, true);
|
||||
}
|
||||
} else if (handler.isPlayingAnimation(this.animation.getName())) {
|
||||
handler.stopAnimation(this.animation.getName());
|
||||
} else {
|
||||
handler.playAnimation(prop, true);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean update(boolean force) {
|
||||
AnimationHandler handler = EditModelScreen.this.model.getAnimationHandler();
|
||||
IAnimationProperty property = handler instanceof StateMachineHandler stateMachineHandler
|
||||
? stateMachineHandler.getAnimation(AnimationTab.this.priority.priority, this.animation.getName())
|
||||
: handler.getAnimation(this.animation.getName());
|
||||
if (property == null) {
|
||||
if (!force && this.trackedProperty == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.trackedProperty = null;
|
||||
this.stack = new ItemStack(Material.RED_CONCRETE);
|
||||
ItemUtils.name(this.stack, Component.text(this.animation.getName(), ComponentUtil.color(NamedTextColor.RED)));
|
||||
ItemUtils.lore(
|
||||
this.stack,
|
||||
Component.empty(),
|
||||
Component.text("Animation:", ComponentUtil.reset()),
|
||||
Component.text("- Animation ID: " + this.animation.getName(), ComponentUtil.reset()),
|
||||
Component.text("- Loop Mode: " + this.animation.getLoopMode(), ComponentUtil.reset()),
|
||||
Component.text("- Override: " + this.animation.isOverride(), ComponentUtil.reset()),
|
||||
Component.text("- Length: " + MiscUtils.FORMATTER.format(this.animation.getLength()) + "s", ComponentUtil.reset())
|
||||
);
|
||||
} else {
|
||||
if (!force && this.trackedProperty != null) {
|
||||
int hash = this.trackedProperty.hashCode();
|
||||
if (hash == this.lastHash) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.lastHash = hash;
|
||||
}
|
||||
|
||||
this.trackedProperty = property;
|
||||
this.stack = new ItemStack(Material.LIME_CONCRETE);
|
||||
ItemUtils.name(this.stack, Component.text(this.animation.getName(), ComponentUtil.color(NamedTextColor.GREEN)));
|
||||
ItemUtils.lore(
|
||||
this.stack,
|
||||
Component.empty(),
|
||||
Component.text("Animation:", ComponentUtil.reset()),
|
||||
Component.text("- Animation ID: " + this.animation.getName(), ComponentUtil.reset()),
|
||||
Component.text("- Loop Mode: " + this.animation.getLoopMode(), ComponentUtil.reset()),
|
||||
Component.text("- Override: " + this.animation.isOverride(), ComponentUtil.reset()),
|
||||
Component.text("- Length: " + MiscUtils.FORMATTER.format(this.animation.getLength()) + "s", ComponentUtil.reset()),
|
||||
Component.empty(),
|
||||
Component.text("Property:", ComponentUtil.reset()),
|
||||
Component.text(
|
||||
"- Phase: "
|
||||
+ property.getPhase()
|
||||
+ (property.getPhase() == IAnimationProperty.Phase.PLAY ? " (" + MiscUtils.FORMATTER.format(property.getTime()) + "s)" : ""),
|
||||
ComponentUtil.reset()
|
||||
),
|
||||
Component.text("- Forced Loop Mode: " + property.getForceLoopMode(), ComponentUtil.reset()),
|
||||
Component.text("- Forced Override: " + property.getForceOverride(), ComponentUtil.reset()),
|
||||
Component.text("- Speed: " + MiscUtils.FORMATTER.format(property.getSpeed()) + "x", ComponentUtil.reset()),
|
||||
Component.text("- Lerp-In: " + MiscUtils.FORMATTER.format(property.getLerpIn()) + "s", ComponentUtil.reset()),
|
||||
Component.text("- Lerp-Out: " + MiscUtils.FORMATTER.format(property.getLerpOut()) + "s", ComponentUtil.reset())
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
class PriorityButton implements Widget {
|
||||
private static final int SLOT = 51;
|
||||
private final ItemStack stack;
|
||||
private int priority = 0;
|
||||
|
||||
public PriorityButton() {
|
||||
this.stack = new ItemStack(Material.COMPARATOR);
|
||||
ItemUtils.name(this.stack, Component.text("Priority: " + this.priority, ComponentUtil.reset()));
|
||||
ItemUtils.lore(
|
||||
this.stack,
|
||||
((TextComponent)((TextComponent)((TextComponent)Component.empty().style(ComponentUtil.reset())).append(Component.text("<<< Left Click")))
|
||||
.append(Component.text(" | ")))
|
||||
.append(Component.text("Right Click >>>"))
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemForSlot(int size, int slot) {
|
||||
return 51 == slot ? this.stack : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
if (slot == 51) {
|
||||
if (event.getClick().isLeftClick()) {
|
||||
this.priority--;
|
||||
} else if (event.getClick().isRightClick()) {
|
||||
this.priority++;
|
||||
}
|
||||
|
||||
AnimationTab.this.page.refreshPage(screen);
|
||||
ItemUtils.name(this.stack, Component.text("Priority: " + this.priority, ComponentUtil.reset()));
|
||||
screen.markSlotsDirty(51);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static class BoneButton implements PaginatorWidget.PageButton {
|
||||
private final ModelBone bone;
|
||||
private ItemStack stack;
|
||||
|
||||
public BoneButton(ModelBone bone) {
|
||||
this.bone = bone;
|
||||
this.updateItem();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemStack() {
|
||||
return this.stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
this.bone.setVisible(!this.bone.isVisible());
|
||||
this.updateItem();
|
||||
screen.markSlotDirty(slot);
|
||||
}
|
||||
|
||||
private void updateItem() {
|
||||
BlueprintBone blueprintBone = this.bone.getBlueprintBone();
|
||||
if (blueprintBone.isRenderer()) {
|
||||
Collection<ItemStack> items = blueprintBone.getModelData().createItemStack();
|
||||
if (!items.isEmpty()) {
|
||||
this.stack = items.iterator().next();
|
||||
this.stack.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_DYE});
|
||||
}
|
||||
}
|
||||
|
||||
if (this.stack == null) {
|
||||
this.stack = new ItemStack(Material.BONE);
|
||||
}
|
||||
|
||||
if (this.bone.isEnchanted()) {
|
||||
this.stack.addUnsafeEnchantment(Enchantment.VANISHING_CURSE, 1);
|
||||
this.stack.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_ENCHANTS});
|
||||
}
|
||||
|
||||
ItemUtils.name(this.stack, Component.text(this.bone.getUniqueBoneId(), ComponentUtil.reset()));
|
||||
ArrayList<Component> lore = new ArrayList<>();
|
||||
lore.add(Component.empty());
|
||||
lore.add(Component.text("Bone ID: " + this.bone.getBoneId(), ComponentUtil.reset()));
|
||||
if (this.bone.getParent() != null) {
|
||||
lore.add(Component.text("Parent: " + this.bone.getParent().getBoneId(), ComponentUtil.reset()));
|
||||
}
|
||||
|
||||
lore.add(Component.text("Visible: " + this.bone.isVisible(), ComponentUtil.reset()));
|
||||
int defColor = this.bone.getDefaultTint().asRGB();
|
||||
int dmgColor = this.bone.getDamageTint().asRGB();
|
||||
lore.add(
|
||||
Component.text("Default Color: ", ComponentUtil.reset())
|
||||
.append(Component.text("#" + Integer.toString(defColor, 16).toUpperCase(Locale.ENGLISH), Style.style(TextColor.color(defColor))))
|
||||
);
|
||||
lore.add(
|
||||
Component.text("Damage Color: ", ComponentUtil.reset())
|
||||
.append(Component.text("#" + Integer.toString(dmgColor, 16).toUpperCase(Locale.ENGLISH), Style.style(TextColor.color(dmgColor))))
|
||||
);
|
||||
lore.add(Component.text("Enchanted: " + this.bone.isEnchanted(), ComponentUtil.reset()));
|
||||
boolean hasBehavior = false;
|
||||
|
||||
for (Entry<BoneBehaviorType<?>, BoneBehavior> behavior : this.bone.getImmutableBoneBehaviors().entrySet()) {
|
||||
if (!behavior.getValue().isHidden()) {
|
||||
if (!hasBehavior) {
|
||||
hasBehavior = true;
|
||||
lore.add(Component.text("Behavior: ", ComponentUtil.reset()));
|
||||
}
|
||||
|
||||
lore.add(Component.text("- " + behavior.getKey().getId(), ComponentUtil.reset()));
|
||||
}
|
||||
}
|
||||
|
||||
ItemUtils.lore(this.stack, lore);
|
||||
}
|
||||
}
|
||||
|
||||
class BoneTab implements TabWidget.Tab {
|
||||
private final ItemStack stack = new ItemStack(Material.BONE);
|
||||
private final PaginatorWidget page;
|
||||
|
||||
public BoneTab() {
|
||||
ItemUtils.name(this.stack, Component.text("Bones", ComponentUtil.reset()));
|
||||
this.page = new PaginatorWidget();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemStack() {
|
||||
return this.stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Widget getWidget() {
|
||||
return this.page;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSelect() {
|
||||
this.page.clearButtons();
|
||||
|
||||
for (ModelBone bone : EditModelScreen.this.model.getBones().values()) {
|
||||
this.page.addButton(new EditModelScreen.BoneButton(bone));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SettingsTab implements TabWidget.Tab {
|
||||
private final ItemStack stack = new ItemStack(Material.COMMAND_BLOCK);
|
||||
private final EditModelScreen.SettingsWidget widget;
|
||||
|
||||
public SettingsTab() {
|
||||
ItemUtils.name(this.stack, Component.text("Model Settings", ComponentUtil.reset()));
|
||||
this.widget = EditModelScreen.this.new SettingsWidget();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemStack() {
|
||||
return this.stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Widget getWidget() {
|
||||
return this.widget;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSelect() {
|
||||
}
|
||||
}
|
||||
|
||||
class SettingsWidget implements Widget {
|
||||
private static final int RENDER_SCALE_SLOT = 21;
|
||||
private static final int HITBOX_SCALE_SLOT = 22;
|
||||
private static final int HITBOX_VISIBLE_SLOT = 23;
|
||||
private static final int SHADOW_VISIBLE_SLOT = 30;
|
||||
private static final int DEFAULT_TINT_SLOT = 31;
|
||||
private static final int DAMAGE_TINT_SLOT = 32;
|
||||
private static final int DAMAGE_TINT_VISIBLE_SLOT = 39;
|
||||
private static final int PITCH_LOCK_SLOT = 40;
|
||||
private static final int YAW_LOCK_SLOT = 41;
|
||||
private final ItemStack renderScale = new ItemStack(Material.SLIME_BALL);
|
||||
private final ItemStack hitboxScale = new ItemStack(Material.MAGMA_CREAM);
|
||||
private final ItemStack hitboxVisible = new ItemStack(Material.SHULKER_SHELL);
|
||||
private final ItemStack shadowVisible = new ItemStack(Material.BLACK_DYE);
|
||||
private final ItemStack defaultTint = new ItemStack(Material.WHITE_DYE);
|
||||
private final ItemStack damageTint = new ItemStack(Material.RED_DYE);
|
||||
private final ItemStack damageTintVisible = new ItemStack(Material.DIAMOND_SWORD);
|
||||
private final ItemStack pitchLock;
|
||||
private final ItemStack yawLock;
|
||||
|
||||
public SettingsWidget() {
|
||||
ItemUtils.meta(this.damageTintVisible, meta -> meta.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_ATTRIBUTES}));
|
||||
this.pitchLock = new ItemStack(Material.CLOCK);
|
||||
this.yawLock = new ItemStack(Material.COMPASS);
|
||||
this.update();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemForSlot(int size, int slot) {
|
||||
return switch (slot) {
|
||||
case 21 -> this.renderScale;
|
||||
case 22 -> this.hitboxScale;
|
||||
case 23 -> this.hitboxVisible;
|
||||
default -> null;
|
||||
case 30 -> this.shadowVisible;
|
||||
case 31 -> this.defaultTint;
|
||||
case 32 -> this.damageTint;
|
||||
case 39 -> this.damageTintVisible;
|
||||
case 40 -> this.pitchLock;
|
||||
case 41 -> this.yawLock;
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
switch (slot) {
|
||||
case 21:
|
||||
player.closeInventory();
|
||||
ComponentUtil.sendMessage(player, Component.text("[ModelEngine] Enter render scale:", ComponentUtil.color(NamedTextColor.AQUA)));
|
||||
ChatListener.fetch(
|
||||
player,
|
||||
s -> {
|
||||
try {
|
||||
EditModelScreen.this.model.setScale(Double.parseDouble(s));
|
||||
ComponentUtil.sendMessage(
|
||||
player, Component.text("[ModelEngine] Set render scale of model to " + s + ".", ComponentUtil.color(NamedTextColor.GREEN))
|
||||
);
|
||||
this.update(slot);
|
||||
DualTicker.queueSyncTask(EditModelScreen.this::openScreen);
|
||||
return true;
|
||||
} catch (NumberFormatException var5) {
|
||||
ComponentUtil.sendMessage(
|
||||
player, Component.text("[ModelEngine] \"" + s + "\" is not a number. Try again.", ComponentUtil.color(NamedTextColor.RED))
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
);
|
||||
break;
|
||||
case 22:
|
||||
player.closeInventory();
|
||||
ComponentUtil.sendMessage(player, Component.text("[ModelEngine] Enter hitbox scale:", ComponentUtil.color(NamedTextColor.AQUA)));
|
||||
ChatListener.fetch(
|
||||
player,
|
||||
s -> {
|
||||
try {
|
||||
EditModelScreen.this.model.setHitboxScale(Double.parseDouble(s));
|
||||
ComponentUtil.sendMessage(
|
||||
player, Component.text("[ModelEngine] Set hitbox scale of model to " + s + ".", ComponentUtil.color(NamedTextColor.GREEN))
|
||||
);
|
||||
this.update(slot);
|
||||
DualTicker.queueSyncTask(EditModelScreen.this::openScreen);
|
||||
return true;
|
||||
} catch (NumberFormatException var5) {
|
||||
ComponentUtil.sendMessage(
|
||||
player, Component.text("[ModelEngine] \"" + s + "\" is not a number. Try again.", ComponentUtil.color(NamedTextColor.RED))
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
);
|
||||
break;
|
||||
case 23:
|
||||
EditModelScreen.this.model.setHitboxVisible(!EditModelScreen.this.model.isHitboxVisible());
|
||||
case 24:
|
||||
case 25:
|
||||
case 26:
|
||||
case 27:
|
||||
case 28:
|
||||
case 29:
|
||||
case 33:
|
||||
case 34:
|
||||
case 35:
|
||||
case 36:
|
||||
case 37:
|
||||
case 38:
|
||||
default:
|
||||
break;
|
||||
case 30:
|
||||
EditModelScreen.this.model.setShadowVisible(!EditModelScreen.this.model.isShadowVisible());
|
||||
break;
|
||||
case 31:
|
||||
player.closeInventory();
|
||||
ComponentUtil.sendMessage(player, Component.text("[ModelEngine] Enter default color in hex:", ComponentUtil.color(NamedTextColor.AQUA)));
|
||||
ChatListener.fetch(
|
||||
player,
|
||||
s -> {
|
||||
try {
|
||||
if (s.startsWith("#")) {
|
||||
s = s.substring(1);
|
||||
}
|
||||
|
||||
int color = Integer.parseInt(s, 16);
|
||||
EditModelScreen.this.model.setDefaultTint(Color.fromRGB(color));
|
||||
ComponentUtil.sendMessage(
|
||||
player,
|
||||
((TextComponent)Component.text("[ModelEngine] Set default color of model to ", ComponentUtil.color(NamedTextColor.GREEN))
|
||||
.append(Component.text("#" + s.toUpperCase(Locale.ENGLISH), ComponentUtil.color(TextColor.color(color)))))
|
||||
.append(Component.text("."))
|
||||
);
|
||||
this.update(slot);
|
||||
DualTicker.queueSyncTask(EditModelScreen.this::openScreen);
|
||||
return true;
|
||||
} catch (NumberFormatException var5) {
|
||||
ComponentUtil.sendMessage(
|
||||
player, Component.text("[ModelEngine] \"" + s + "\" is not a valid color. Try again.", ComponentUtil.color(NamedTextColor.RED))
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
);
|
||||
break;
|
||||
case 32:
|
||||
player.closeInventory();
|
||||
ComponentUtil.sendMessage(player, Component.text("[ModelEngine] Enter damage color in hex:", ComponentUtil.color(NamedTextColor.AQUA)));
|
||||
ChatListener.fetch(
|
||||
player,
|
||||
s -> {
|
||||
try {
|
||||
if (s.startsWith("#")) {
|
||||
s = s.substring(1);
|
||||
}
|
||||
|
||||
int color = Integer.parseInt(s, 16);
|
||||
EditModelScreen.this.model.setDamageTint(Color.fromRGB(color));
|
||||
ComponentUtil.sendMessage(
|
||||
player,
|
||||
((TextComponent)Component.text("[ModelEngine] Set damage color of model to ", ComponentUtil.color(NamedTextColor.GREEN))
|
||||
.append(Component.text("#" + s.toUpperCase(Locale.ENGLISH), ComponentUtil.color(TextColor.color(color)))))
|
||||
.append(Component.text("."))
|
||||
);
|
||||
this.update(slot);
|
||||
DualTicker.queueSyncTask(EditModelScreen.this::openScreen);
|
||||
return true;
|
||||
} catch (NumberFormatException var5) {
|
||||
ComponentUtil.sendMessage(
|
||||
player, Component.text("[ModelEngine] \"" + s + "\" is not a valid color. Try again.", ComponentUtil.color(NamedTextColor.RED))
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
);
|
||||
break;
|
||||
case 39:
|
||||
EditModelScreen.this.model.setCanHurt(!EditModelScreen.this.model.canHurt());
|
||||
break;
|
||||
case 40:
|
||||
EditModelScreen.this.model.setLockPitch(!EditModelScreen.this.model.isLockPitch());
|
||||
break;
|
||||
case 41:
|
||||
EditModelScreen.this.model.setLockYaw(!EditModelScreen.this.model.isLockYaw());
|
||||
}
|
||||
|
||||
this.update(slot);
|
||||
EditModelScreen.this.markSlotDirty(slot);
|
||||
}
|
||||
|
||||
public void update() {
|
||||
this.update(21);
|
||||
this.update(22);
|
||||
this.update(23);
|
||||
this.update(30);
|
||||
this.update(31);
|
||||
this.update(32);
|
||||
this.update(39);
|
||||
this.update(40);
|
||||
this.update(41);
|
||||
}
|
||||
|
||||
public void update(int slot) {
|
||||
switch (slot) {
|
||||
case 21:
|
||||
ItemUtils.name(
|
||||
this.renderScale,
|
||||
Component.text("Render Scale: " + MiscUtils.FORMATTER.format(EditModelScreen.this.model.getScale().x()), ComponentUtil.reset())
|
||||
);
|
||||
break;
|
||||
case 22:
|
||||
ItemUtils.name(
|
||||
this.hitboxScale,
|
||||
Component.text("Hitbox Scale: " + MiscUtils.FORMATTER.format(EditModelScreen.this.model.getHitboxScale().x()), ComponentUtil.reset())
|
||||
);
|
||||
break;
|
||||
case 23:
|
||||
ItemUtils.name(
|
||||
this.hitboxVisible,
|
||||
Component.text(
|
||||
"Hitbox Visible: " + EditModelScreen.this.model.isHitboxVisible(),
|
||||
ComponentUtil.color(EditModelScreen.this.model.isHitboxVisible() ? NamedTextColor.GREEN : NamedTextColor.RED)
|
||||
)
|
||||
);
|
||||
case 24:
|
||||
case 25:
|
||||
case 26:
|
||||
case 27:
|
||||
case 28:
|
||||
case 29:
|
||||
case 33:
|
||||
case 34:
|
||||
case 35:
|
||||
case 36:
|
||||
case 37:
|
||||
case 38:
|
||||
default:
|
||||
break;
|
||||
case 30:
|
||||
ItemUtils.name(
|
||||
this.shadowVisible,
|
||||
Component.text(
|
||||
"Shadow Visible: " + EditModelScreen.this.model.isShadowVisible(),
|
||||
ComponentUtil.color(EditModelScreen.this.model.isShadowVisible() ? NamedTextColor.GREEN : NamedTextColor.RED)
|
||||
)
|
||||
);
|
||||
break;
|
||||
case 31:
|
||||
ItemUtils.name(
|
||||
this.defaultTint,
|
||||
Component.text(
|
||||
"Default Tint: #" + Integer.toHexString(EditModelScreen.this.model.getDefaultTint().asARGB()).toUpperCase(Locale.ENGLISH).substring(2),
|
||||
ComponentUtil.color(TextColor.color(EditModelScreen.this.model.getDefaultTint().asRGB()))
|
||||
)
|
||||
);
|
||||
break;
|
||||
case 32:
|
||||
ItemUtils.name(
|
||||
this.damageTint,
|
||||
Component.text(
|
||||
"Damage Tint: #" + Integer.toHexString(EditModelScreen.this.model.getDamageTint().asARGB()).toUpperCase(Locale.ENGLISH).substring(2),
|
||||
ComponentUtil.color(TextColor.color(EditModelScreen.this.model.getDamageTint().asRGB()))
|
||||
)
|
||||
);
|
||||
break;
|
||||
case 39:
|
||||
ItemUtils.name(
|
||||
this.damageTintVisible,
|
||||
Component.text(
|
||||
"Damage Tint Visible: " + EditModelScreen.this.model.canHurt(),
|
||||
ComponentUtil.color(EditModelScreen.this.model.canHurt() ? NamedTextColor.GREEN : NamedTextColor.RED)
|
||||
)
|
||||
);
|
||||
break;
|
||||
case 40:
|
||||
ItemUtils.name(
|
||||
this.pitchLock,
|
||||
Component.text(
|
||||
"Pitch Lock: " + EditModelScreen.this.model.isLockPitch(),
|
||||
ComponentUtil.color(EditModelScreen.this.model.isLockPitch() ? NamedTextColor.GREEN : NamedTextColor.RED)
|
||||
)
|
||||
);
|
||||
break;
|
||||
case 41:
|
||||
ItemUtils.name(
|
||||
this.yawLock,
|
||||
Component.text(
|
||||
"Yaw Lock: " + EditModelScreen.this.model.isLockYaw(),
|
||||
ComponentUtil.color(EditModelScreen.this.model.isLockYaw() ? NamedTextColor.GREEN : NamedTextColor.RED)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package com.ticxo.modelengine.core.menu.screen;
|
||||
|
||||
import com.ticxo.modelengine.api.menu.AbstractScreen;
|
||||
import com.ticxo.modelengine.api.menu.Widget;
|
||||
import com.ticxo.modelengine.api.utils.data.ComponentUtil;
|
||||
import com.ticxo.modelengine.api.utils.data.ItemUtils;
|
||||
import com.ticxo.modelengine.core.menu.SelectionManager;
|
||||
import com.ticxo.modelengine.core.menu.widget.BorderWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.CloseWidget;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import net.kyori.adventure.text.format.TextDecoration;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.ClickType;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.ItemFlag;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
public class NavigationScreen extends AbstractScreen {
|
||||
public NavigationScreen(Player player) {
|
||||
super(player, "Model Engine", 6);
|
||||
this.addWidget(new BorderWidget());
|
||||
this.addWidget(new NavigationScreen.Navigator());
|
||||
this.addWidget(new CloseWidget(null));
|
||||
}
|
||||
|
||||
class Navigator implements Widget {
|
||||
private static final int SPAWN_SLOT = 29;
|
||||
private static final int SELECT_SLOT = 31;
|
||||
private static final int EDIT_SLOT = 33;
|
||||
private final ItemStack spawn;
|
||||
private final ItemStack select;
|
||||
private final ItemStack edit;
|
||||
private Entity selected;
|
||||
|
||||
public Navigator() {
|
||||
if (SelectionManager.isSelecting(NavigationScreen.this.viewer)) {
|
||||
SelectionManager.setSelecting(NavigationScreen.this.viewer, false);
|
||||
NavigationScreen.this.viewer
|
||||
.sendActionBar(((TextComponent)Component.empty().style(ComponentUtil.reset())).append(Component.text("Canceled selection mode.")));
|
||||
}
|
||||
|
||||
this.spawn = new ItemStack(Material.PIG_SPAWN_EGG);
|
||||
ItemUtils.name(this.spawn, Component.text("Spawn Model", ComponentUtil.reset()));
|
||||
ItemUtils.lore(this.spawn, Component.empty(), Component.text("Spawn a model at where you are standing.", ComponentUtil.reset()));
|
||||
this.selected = SelectionManager.getSelected(NavigationScreen.this.viewer);
|
||||
this.select = new ItemStack(Material.SPYGLASS);
|
||||
this.updateSelect();
|
||||
this.edit = new ItemStack(Material.WRITABLE_BOOK);
|
||||
ItemUtils.name(this.edit, Component.text("Edit Entity", ComponentUtil.reset()));
|
||||
ItemUtils.lore(
|
||||
this.edit,
|
||||
Component.empty(),
|
||||
Component.text("Add or remove models, states, and edit", ComponentUtil.reset()),
|
||||
Component.text("bone behaviors of the selected entity.", ComponentUtil.reset())
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemForSlot(int size, int slot) {
|
||||
return switch (slot) {
|
||||
case 29 -> this.spawn;
|
||||
default -> null;
|
||||
case 31 -> this.select;
|
||||
case 33 -> this.edit;
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
ClickType click = event.getClick();
|
||||
if (!click.isKeyboardClick()) {
|
||||
switch (slot) {
|
||||
case 29:
|
||||
new SpawnModelScreen(NavigationScreen.this, player).openScreen();
|
||||
case 30:
|
||||
case 32:
|
||||
default:
|
||||
break;
|
||||
case 31:
|
||||
switch (click) {
|
||||
case RIGHT:
|
||||
SelectionManager.setSelected(player, player);
|
||||
player.sendActionBar(Component.text("Select " + player.getName() + ".", ComponentUtil.reset()));
|
||||
this.selected = player;
|
||||
this.updateSelect();
|
||||
NavigationScreen.this.markSlotDirty(31);
|
||||
return;
|
||||
case LEFT:
|
||||
SelectionManager.setSelecting(player, true);
|
||||
player.sendActionBar(Component.text("Select an entity by attacking the target.", ComponentUtil.reset()));
|
||||
player.closeInventory();
|
||||
return;
|
||||
case SHIFT_LEFT:
|
||||
case SHIFT_RIGHT:
|
||||
SelectionManager.setSelected(player, null);
|
||||
this.selected = null;
|
||||
this.updateSelect();
|
||||
NavigationScreen.this.markSlotDirty(31);
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
case 33:
|
||||
Entity entity = SelectionManager.getSelected(player);
|
||||
if (entity != null) {
|
||||
new EditEntityScreen(NavigationScreen.this, player, entity).openScreen();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void updateSelect() {
|
||||
ItemUtils.name(this.select, Component.text("Select Entity", ComponentUtil.reset()));
|
||||
ItemUtils.lore(
|
||||
this.select,
|
||||
Component.empty(),
|
||||
this.selected == null
|
||||
? null
|
||||
: ((TextComponent)Component.empty().style(ComponentUtil.reset().decoration(TextDecoration.BOLD, true).color(NamedTextColor.AQUA)))
|
||||
.append(Component.text("Selected: " + this.selected.getName())),
|
||||
this.selected == null ? null : Component.empty(),
|
||||
Component.text("Left click to select entity.", ComponentUtil.reset()),
|
||||
Component.text("Right click to select yourself.", ComponentUtil.reset()),
|
||||
Component.text("Shift click to clear selection.", ComponentUtil.reset())
|
||||
);
|
||||
this.select.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_ENCHANTS});
|
||||
if (this.selected != null) {
|
||||
this.select.addUnsafeEnchantment(Enchantment.VANISHING_CURSE, 1);
|
||||
} else {
|
||||
this.select.removeEnchantment(Enchantment.VANISHING_CURSE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.ticxo.modelengine.core.menu.screen;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.entity.BukkitEntity;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.menu.AbstractScreen;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.ModelRegistry;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes;
|
||||
import com.ticxo.modelengine.api.model.bone.type.PlayerLimb;
|
||||
import com.ticxo.modelengine.api.model.bone.type.UserLimb;
|
||||
import com.ticxo.modelengine.api.utils.data.ComponentUtil;
|
||||
import com.ticxo.modelengine.api.utils.data.ItemUtils;
|
||||
import com.ticxo.modelengine.core.menu.widget.BasicItemWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.BorderWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.CloseWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.PaginatorWidget;
|
||||
import com.ticxo.modelengine.core.menu.widget.page.AbstractModelButton;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.TextDecoration;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Pig;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
public class SpawnModelScreen extends AbstractScreen {
|
||||
public SpawnModelScreen(AbstractScreen rootScreen, Player viewer) {
|
||||
super(viewer, "Spawn Model", 6);
|
||||
this.addWidget(new BorderWidget());
|
||||
PaginatorWidget page = new PaginatorWidget();
|
||||
ModelRegistry registry = ModelEngineAPI.getAPI().getModelRegistry();
|
||||
|
||||
for (String modelId : registry.getOrderedId()) {
|
||||
ModelBlueprint blueprint = registry.get(modelId);
|
||||
SpawnModelScreen.ModelButton button = new SpawnModelScreen.ModelButton(blueprint);
|
||||
page.addButton(button);
|
||||
}
|
||||
|
||||
this.addWidget(page);
|
||||
ItemStack statSign = new ItemStack(Material.OAK_SIGN);
|
||||
ItemUtils.name(statSign, Component.text("Stats", ComponentUtil.reset().decoration(TextDecoration.BOLD, true)));
|
||||
ItemUtils.lore(statSign, Component.empty(), Component.text("Models: " + registry.getKeys().size(), ComponentUtil.reset()));
|
||||
this.addWidget(new BasicItemWidget(53, statSign));
|
||||
this.addWidget(new CloseWidget(rootScreen));
|
||||
}
|
||||
|
||||
static class ModelButton extends AbstractModelButton {
|
||||
public ModelButton(ModelBlueprint blueprint) {
|
||||
super(blueprint);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
if (event.isLeftClick() || event.isRightClick()) {
|
||||
Location location = player.getLocation();
|
||||
player.getWorld().spawn(location, Pig.class, entity -> {
|
||||
BukkitEntity base = new BukkitEntity(entity);
|
||||
base.getBodyRotationController().setYBodyRot(location.getYaw());
|
||||
ModeledEntity modeledEntity = ModelEngineAPI.createModeledEntity(base);
|
||||
modeledEntity.setBaseEntityVisible(false);
|
||||
ActiveModel activeModel = ModelEngineAPI.createActiveModel(this.blueprint);
|
||||
activeModel.setAutoRendererInitialization(false);
|
||||
modeledEntity.addModel(activeModel, true).ifPresent(ActiveModel::destroy);
|
||||
activeModel.getBones().values().forEach(modelBone -> {
|
||||
modelBone.getBoneBehavior(BoneBehaviorTypes.PLAYER_LIMB).ifPresent(playerLimb -> ((PlayerLimb)playerLimb).setTexture(player));
|
||||
modelBone.getBoneBehavior(BoneBehaviorTypes.USER_LIMB).ifPresent(playerLimb -> ((UserLimb)playerLimb).setTexture(player));
|
||||
});
|
||||
activeModel.initializeRenderer();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.ticxo.modelengine.core.menu.widget;
|
||||
|
||||
import com.ticxo.modelengine.api.menu.AbstractScreen;
|
||||
import com.ticxo.modelengine.api.menu.Widget;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
public class BasicItemWidget implements Widget {
|
||||
private final int slot;
|
||||
private final ItemStack stack;
|
||||
|
||||
@Override
|
||||
public ItemStack getItemForSlot(int size, int slot) {
|
||||
return this.slot == slot ? this.stack : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
}
|
||||
|
||||
public BasicItemWidget(int slot, ItemStack stack) {
|
||||
this.slot = slot;
|
||||
this.stack = stack;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.ticxo.modelengine.core.menu.widget;
|
||||
|
||||
import com.ticxo.modelengine.api.menu.AbstractScreen;
|
||||
import com.ticxo.modelengine.api.menu.Widget;
|
||||
import com.ticxo.modelengine.api.utils.data.ItemUtils;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
public class BorderWidget implements Widget {
|
||||
private final ItemStack border = new ItemStack(Material.TWISTING_VINES);
|
||||
private final ItemStack bar;
|
||||
|
||||
public BorderWidget() {
|
||||
ItemUtils.name(this.border, Component.text(" "));
|
||||
this.bar = new ItemStack(Material.NETHER_SPROUTS);
|
||||
ItemUtils.name(this.bar, Component.text(" "));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemForSlot(int size, int slot) {
|
||||
if (slot % 9 == 0 || slot % 9 == 8) {
|
||||
return this.border;
|
||||
} else {
|
||||
return (slot < 9 || slot >= 18) && slot <= size - 9 ? null : this.bar;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.ticxo.modelengine.core.menu.widget;
|
||||
|
||||
import com.ticxo.modelengine.api.menu.AbstractScreen;
|
||||
import com.ticxo.modelengine.api.menu.Widget;
|
||||
import com.ticxo.modelengine.api.utils.data.ComponentUtil;
|
||||
import com.ticxo.modelengine.api.utils.data.ItemUtils;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class CloseWidget implements Widget {
|
||||
private final ItemStack close = new ItemStack(Material.BARRIER);
|
||||
private final AbstractScreen rootScreen;
|
||||
|
||||
public CloseWidget(@Nullable AbstractScreen screen) {
|
||||
ItemUtils.name(this.close, Component.text("Close", ComponentUtil.reset()));
|
||||
this.rootScreen = screen;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemForSlot(int size, int slot) {
|
||||
return slot == size - 5 ? this.close : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
if (slot == screen.getInventory().getSize() - 5) {
|
||||
if (this.rootScreen == null) {
|
||||
player.closeInventory();
|
||||
} else {
|
||||
this.rootScreen.openScreen();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.ticxo.modelengine.core.menu.widget;
|
||||
|
||||
import com.ticxo.modelengine.api.menu.AbstractScreen;
|
||||
import com.ticxo.modelengine.api.menu.Widget;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
public class CompositeWidget implements Widget {
|
||||
private final Widget first;
|
||||
private final Widget second;
|
||||
|
||||
@Override
|
||||
public ItemStack getItemForSlot(int size, int slot) {
|
||||
ItemStack sItem = this.second.getItemForSlot(size, slot);
|
||||
return sItem != null ? sItem : this.first.getItemForSlot(size, slot);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
this.second.onClick(screen, player, slot, event);
|
||||
this.first.onClick(screen, player, slot, event);
|
||||
}
|
||||
|
||||
public CompositeWidget(Widget first, Widget second) {
|
||||
this.first = first;
|
||||
this.second = second;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.ticxo.modelengine.core.menu.widget;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.ticxo.modelengine.api.menu.AbstractScreen;
|
||||
import com.ticxo.modelengine.api.menu.Widget;
|
||||
import com.ticxo.modelengine.api.utils.data.ComponentUtil;
|
||||
import com.ticxo.modelengine.api.utils.data.ItemUtils;
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
public class PaginatorWidget implements Widget {
|
||||
private static final int PAGE_SLOT = 52;
|
||||
private static final int MAX_ITEM = 21;
|
||||
private static final Map<Integer, Integer> PAGE_PAIR;
|
||||
private final ItemStack pageSwitch;
|
||||
private final List<PaginatorWidget.PageButton> buttons = new ArrayList<>();
|
||||
private int currentPage;
|
||||
|
||||
public PaginatorWidget() {
|
||||
this.pageSwitch = new ItemStack(Material.PAPER);
|
||||
ItemUtils.name(this.pageSwitch, Component.text("Turn Page", ComponentUtil.reset()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemForSlot(int size, int slot) {
|
||||
if (slot == 52) {
|
||||
ItemUtils.lore(
|
||||
this.pageSwitch,
|
||||
((TextComponent)((TextComponent)((TextComponent)Component.empty().style(ComponentUtil.reset()))
|
||||
.append(Component.text("<<< Left Click").color(this.currentPage == 0 ? NamedTextColor.DARK_GRAY : NamedTextColor.WHITE)))
|
||||
.append(Component.text(" | ")))
|
||||
.append(Component.text("Right Click >>>").color(this.currentPage == this.getLastPage() ? NamedTextColor.DARK_GRAY : NamedTextColor.WHITE))
|
||||
);
|
||||
return this.pageSwitch;
|
||||
} else {
|
||||
PaginatorWidget.PageButton button = this.getButton(slot);
|
||||
return button == null ? null : button.getItemStack();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
if (slot == 52) {
|
||||
if (event.getClick().isLeftClick()) {
|
||||
this.currentPage--;
|
||||
} else if (event.getClick().isRightClick()) {
|
||||
this.currentPage++;
|
||||
}
|
||||
|
||||
this.currentPage = TMath.clamp(this.currentPage, 0, this.getLastPage());
|
||||
screen.markSlotsDirty(52);
|
||||
this.refreshPage(screen);
|
||||
} else {
|
||||
PaginatorWidget.PageButton button = this.getButton(slot);
|
||||
if (button != null) {
|
||||
button.onClick(screen, player, slot, event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void addButton(PaginatorWidget.PageButton button) {
|
||||
this.buttons.add(button);
|
||||
}
|
||||
|
||||
public void clearButtons() {
|
||||
this.buttons.clear();
|
||||
}
|
||||
|
||||
public PaginatorWidget.PageButton getButton(int slot) {
|
||||
Integer id = PAGE_PAIR.get(slot);
|
||||
if (id == null) {
|
||||
return null;
|
||||
} else {
|
||||
id = this.currentPage * 21 + id;
|
||||
return id < this.buttons.size() ? this.buttons.get(id) : null;
|
||||
}
|
||||
}
|
||||
|
||||
public void refreshPage(AbstractScreen screen) {
|
||||
PAGE_PAIR.forEach((invSlot, id) -> screen.markSlotDirty(invSlot));
|
||||
}
|
||||
|
||||
private int getLastPage() {
|
||||
return Math.max(TMath.ceil(this.buttons.size() / 21.0F) - 1, 0);
|
||||
}
|
||||
|
||||
static {
|
||||
HashMap<Integer, Integer> pair = new HashMap<>();
|
||||
int id = 0;
|
||||
|
||||
for (int i = 19; i <= 43; i++) {
|
||||
switch (i % 9) {
|
||||
default:
|
||||
pair.put(i, id++);
|
||||
break;
|
||||
case 0:
|
||||
case 8:
|
||||
}
|
||||
}
|
||||
|
||||
PAGE_PAIR = ImmutableMap.copyOf(pair);
|
||||
}
|
||||
|
||||
public interface PageButton {
|
||||
ItemStack getItemStack();
|
||||
|
||||
void onClick(AbstractScreen var1, Player var2, int var3, InventoryClickEvent var4);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.ticxo.modelengine.core.menu.widget;
|
||||
|
||||
import com.ticxo.modelengine.api.menu.AbstractScreen;
|
||||
import com.ticxo.modelengine.api.menu.Widget;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
public class TabWidget implements Widget {
|
||||
private final List<TabWidget.Tab> tabs = new ArrayList<>();
|
||||
private TabWidget.Tab selectedTab;
|
||||
|
||||
@Override
|
||||
public ItemStack getItemForSlot(int size, int slot) {
|
||||
if (slot != 0 && slot < 8) {
|
||||
return this.tabs.size() < slot ? null : this.tabs.get(slot - 1).getItemStack();
|
||||
} else {
|
||||
return this.selectedTab == null ? null : this.selectedTab.getWidget().getItemForSlot(size, slot);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) {
|
||||
if (slot != 0 && slot < 8) {
|
||||
if (this.tabs.size() >= slot) {
|
||||
TabWidget.Tab t = this.tabs.get(slot - 1);
|
||||
if (this.selectedTab != t) {
|
||||
this.selectedTab = t;
|
||||
this.selectedTab.onSelect();
|
||||
screen.draw(true);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (this.selectedTab != null) {
|
||||
this.selectedTab.getWidget().onClick(screen, player, slot, event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void addTab(TabWidget.Tab tab) {
|
||||
this.tabs.add(tab);
|
||||
if (this.selectedTab == null) {
|
||||
this.selectedTab = tab;
|
||||
this.selectedTab.onSelect();
|
||||
}
|
||||
}
|
||||
|
||||
public void clearTab() {
|
||||
this.tabs.clear();
|
||||
}
|
||||
|
||||
public TabWidget.Tab getSelectedTab() {
|
||||
return this.selectedTab;
|
||||
}
|
||||
|
||||
public interface Tab {
|
||||
ItemStack getItemStack();
|
||||
|
||||
Widget getWidget();
|
||||
|
||||
void onSelect();
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.ticxo.modelengine.core.menu.widget.page;
|
||||
|
||||
import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.utils.data.ComponentUtil;
|
||||
import com.ticxo.modelengine.api.utils.data.ItemUtils;
|
||||
import com.ticxo.modelengine.core.menu.widget.PaginatorWidget;
|
||||
import java.util.Collection;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.inventory.ItemFlag;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
public abstract class AbstractModelButton implements PaginatorWidget.PageButton {
|
||||
protected final ModelBlueprint blueprint;
|
||||
protected final ItemStack stack;
|
||||
|
||||
public AbstractModelButton(ModelBlueprint blueprint) {
|
||||
this.blueprint = blueprint;
|
||||
ItemStack bone = null;
|
||||
BlueprintBone headBone = blueprint.getFlatMap().get("head");
|
||||
if (headBone != null && headBone.isRenderer()) {
|
||||
Collection<ItemStack> items = headBone.getModelData().createItemStack();
|
||||
if (!items.isEmpty()) {
|
||||
bone = items.iterator().next();
|
||||
bone.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_DYE});
|
||||
}
|
||||
}
|
||||
|
||||
if (bone == null) {
|
||||
bone = new ItemStack(Material.ARMOR_STAND);
|
||||
}
|
||||
|
||||
this.stack = bone;
|
||||
this.updateItem();
|
||||
}
|
||||
|
||||
protected void updateItem() {
|
||||
ItemUtils.name(this.stack, Component.text(this.blueprint.getName(), ComponentUtil.reset()));
|
||||
ItemUtils.lore(
|
||||
this.stack,
|
||||
Component.empty(),
|
||||
Component.text("Model ID: " + this.blueprint.getName(), ComponentUtil.reset()),
|
||||
Component.text("Hitbox: " + this.blueprint.getMainHitbox().toSimpleString(), ComponentUtil.reset()),
|
||||
Component.text("Eye Height: " + this.blueprint.getMainHitbox().toEyeHeightString(), ComponentUtil.reset()),
|
||||
Component.text("Shadow: " + this.blueprint.getShadowRadius(), ComponentUtil.reset()),
|
||||
Component.text("Bone Count: " + this.blueprint.getFlatMap().size(), ComponentUtil.reset())
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemStack() {
|
||||
return this.stack;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.ticxo.modelengine.core.misc;
|
||||
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.ItemDisplay;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.util.Transformation;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class Alternator {
|
||||
private static final Quaternionf IDENTITY = new Quaternionf();
|
||||
private final int tick;
|
||||
private final ItemDisplay displayA;
|
||||
private final ItemDisplay displayB;
|
||||
private boolean isAVisible;
|
||||
private boolean queueNextTickToggle;
|
||||
private Vector3f position = new Vector3f();
|
||||
private boolean positionStep;
|
||||
private Quaternionf rotation = new Quaternionf();
|
||||
private boolean rotationStep;
|
||||
private Vector3f scale = new Vector3f(1.0F, 1.0F, 1.0F);
|
||||
private boolean scaleStep;
|
||||
|
||||
public Alternator(Location location, int tick) {
|
||||
this.tick = tick;
|
||||
this.displayA = (ItemDisplay)location.getWorld().spawn(location, ItemDisplay.class, itemDisplay -> {
|
||||
itemDisplay.setInterpolationDuration(tick);
|
||||
itemDisplay.setItemStack(new ItemStack(Material.CARVED_PUMPKIN));
|
||||
});
|
||||
this.displayB = (ItemDisplay)location.getWorld().spawn(location, ItemDisplay.class, itemDisplay -> {
|
||||
itemDisplay.setInterpolationDuration(tick);
|
||||
itemDisplay.setItemStack(new ItemStack(Material.FURNACE));
|
||||
itemDisplay.setViewRange(0.0F);
|
||||
});
|
||||
this.isAVisible = true;
|
||||
}
|
||||
|
||||
public void tick() {
|
||||
this.tickSwap();
|
||||
ItemDisplay visible = this.getVisible();
|
||||
ItemDisplay hidden = this.getHidden();
|
||||
if (!this.positionStep && !this.rotationStep && !this.scaleStep) {
|
||||
Transformation transformation = new Transformation(this.position, this.rotation, this.scale, IDENTITY);
|
||||
visible.setTransformation(transformation);
|
||||
visible.setInterpolationDelay(0);
|
||||
visible.setInterpolationDuration(this.tick);
|
||||
} else {
|
||||
Vector3f dPos = this.positionStep ? visible.getTransformation().getTranslation() : this.position;
|
||||
Quaternionf dRot = this.rotationStep ? visible.getTransformation().getLeftRotation() : this.rotation;
|
||||
Vector3f dSca = this.scaleStep ? visible.getTransformation().getScale() : this.scale;
|
||||
Transformation visibleTransform = new Transformation(dPos, dRot, dSca, IDENTITY);
|
||||
Transformation hiddenTransform = new Transformation(this.position, this.rotation, this.scale, IDENTITY);
|
||||
if (!visible.getTransformation().equals(visibleTransform)) {
|
||||
visible.setTransformation(visibleTransform);
|
||||
visible.setInterpolationDelay(0);
|
||||
visible.setInterpolationDuration(this.tick);
|
||||
}
|
||||
|
||||
if (!hidden.getTransformation().equals(hiddenTransform)) {
|
||||
hidden.setTransformation(hiddenTransform);
|
||||
hidden.setInterpolationDelay(0);
|
||||
hidden.setInterpolationDuration(0);
|
||||
}
|
||||
|
||||
this.queueNextTickToggle = true;
|
||||
this.positionStep = false;
|
||||
this.rotationStep = false;
|
||||
this.scaleStep = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void tickSwap() {
|
||||
if (this.queueNextTickToggle) {
|
||||
this.swapVisibility();
|
||||
this.queueNextTickToggle = false;
|
||||
}
|
||||
}
|
||||
|
||||
public ItemDisplay getVisible() {
|
||||
return this.isAVisible ? this.displayA : this.displayB;
|
||||
}
|
||||
|
||||
public ItemDisplay getHidden() {
|
||||
return !this.isAVisible ? this.displayA : this.displayB;
|
||||
}
|
||||
|
||||
public void swapVisibility() {
|
||||
this.getVisible().setViewRange(0.0F);
|
||||
this.getHidden().setViewRange(1.0F);
|
||||
this.isAVisible = !this.isAVisible;
|
||||
}
|
||||
|
||||
public boolean isDead() {
|
||||
return this.displayA.isDead() || this.displayB.isDead();
|
||||
}
|
||||
|
||||
public Alternator lerpPosition(Vector3f position) {
|
||||
this.position = position;
|
||||
this.positionStep = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Alternator lerpRotation(Quaternionf rotation) {
|
||||
this.rotation = rotation;
|
||||
this.rotationStep = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Alternator lerpScale(Vector3f scale) {
|
||||
this.scale = scale;
|
||||
this.scaleStep = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Alternator stepPosition(Vector3f position) {
|
||||
this.position = position;
|
||||
this.positionStep = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Alternator stepRotation(Quaternionf rotation) {
|
||||
this.rotation = rotation;
|
||||
this.rotationStep = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Alternator stepScale(Vector3f scale) {
|
||||
this.scale = scale;
|
||||
this.scaleStep = true;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.ticxo.modelengine.core.misc;
|
||||
|
||||
import org.apache.commons.lang3.tuple.Triple;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public enum Cardinal {
|
||||
Q_001(0, 0, 1),
|
||||
Q_002(0, 0, 2),
|
||||
Q_003(0, 0, 3),
|
||||
Q_010(0, 1, 0),
|
||||
Q_011(0, 1, 1),
|
||||
Q_012(0, 1, 2),
|
||||
Q_013(0, 1, 3),
|
||||
Q_020(0, 2, 0),
|
||||
Q_021(0, 2, 1),
|
||||
Q_022(0, 2, 2),
|
||||
Q_023(0, 2, 3),
|
||||
Q_030(0, 3, 0),
|
||||
Q_031(0, 3, 1),
|
||||
Q_032(0, 3, 2),
|
||||
Q_033(0, 3, 3),
|
||||
Q_100(1, 0, 0),
|
||||
Q_101(1, 0, 1),
|
||||
Q_102(1, 0, 2),
|
||||
Q_103(1, 0, 3),
|
||||
Q_120(1, 2, 0),
|
||||
Q_121(1, 2, 1),
|
||||
Q_122(1, 2, 2),
|
||||
Q_123(1, 2, 3);
|
||||
|
||||
public final Quaternionf rotation;
|
||||
public final Quaternionf inverse;
|
||||
private static final Cardinal[] VALUES = values();
|
||||
|
||||
private Cardinal(int x, int y, int z) {
|
||||
this.rotation = new Quaternionf().rotationXYZ(x * (float) (Math.PI / 2), y * (float) (Math.PI / 2), z * (float) (Math.PI / 2));
|
||||
this.inverse = this.rotation.invert(new Quaternionf());
|
||||
}
|
||||
|
||||
public static Cardinal[] cardinals() {
|
||||
return VALUES;
|
||||
}
|
||||
|
||||
public Triple<Quaternionf, Vector3f, Quaternionf> warpTransform(Quaternionf left, Vector3f scale, Quaternionf right) {
|
||||
Quaternionf nLeft = left.mul(this.rotation, new Quaternionf());
|
||||
Vector3f nScale = scale.rotate(this.inverse, new Vector3f());
|
||||
nScale.x = Math.signum(scale.x) * Math.abs(nScale.x);
|
||||
nScale.y = Math.signum(scale.y) * Math.abs(nScale.y);
|
||||
nScale.z = Math.signum(scale.z) * Math.abs(nScale.z);
|
||||
Quaternionf nRight = right.premul(this.inverse, new Quaternionf());
|
||||
return Triple.of(nLeft, nScale, nRight);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,896 @@
|
||||
package com.ticxo.modelengine.core.model;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.animation.handler.AnimationHandler;
|
||||
import com.ticxo.modelengine.api.entity.Hitbox;
|
||||
import com.ticxo.modelengine.api.entity.data.BukkitEntityData;
|
||||
import com.ticxo.modelengine.api.entity.data.IEntityData;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.api.model.PivotOverride;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager;
|
||||
import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer;
|
||||
import com.ticxo.modelengine.api.model.render.ModelRenderer;
|
||||
import com.ticxo.modelengine.api.utils.callback.Callback;
|
||||
import com.ticxo.modelengine.api.utils.config.ConfigProperty;
|
||||
import com.ticxo.modelengine.api.utils.data.CachedImmutableMap;
|
||||
import com.ticxo.modelengine.api.utils.data.io.SavedData;
|
||||
import com.ticxo.modelengine.api.utils.logger.TLogger;
|
||||
import com.ticxo.modelengine.api.utils.meta.MetadataRegistry;
|
||||
import com.ticxo.modelengine.core.animation.handler.PriorityHandler;
|
||||
import com.ticxo.modelengine.core.animation.handler.StateMachineHandler;
|
||||
import com.ticxo.modelengine.core.model.bone.ModelBoneImpl;
|
||||
import com.ticxo.modelengine.core.model.render.DisplayRendererImpl;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.entity.Display.Billboard;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.joml.Vector3f;
|
||||
import org.joml.Vector3fc;
|
||||
|
||||
public class ActiveModelImpl implements ActiveModel {
|
||||
private final ModelBlueprint blueprint;
|
||||
private final MetadataRegistry metadata = new MetadataRegistry();
|
||||
private final ModelRenderer modelRenderer;
|
||||
private final AnimationHandler animationHandler;
|
||||
private final Map<String, ModelBone> bones = Maps.newConcurrentMap();
|
||||
private final Map<String, ModelBone> roots = Maps.newConcurrentMap();
|
||||
private final Map<BoneBehaviorType<?>, BehaviorManager<?>> behaviorManagers = new LinkedHashMap<>();
|
||||
private final Map<BoneBehaviorType<?>, BehaviorRenderer> behaviorRenderers = new LinkedHashMap<>();
|
||||
private final CachedImmutableMap<String, ModelBone> boneCache = new CachedImmutableMap<>(this.bones);
|
||||
private final CachedImmutableMap<BoneBehaviorType<?>, BehaviorManager<?>> behaviorManagerCache = new CachedImmutableMap<>(this.behaviorManagers);
|
||||
private final CachedImmutableMap<BoneBehaviorType<?>, BehaviorRenderer> behaviorRendererCache = new CachedImmutableMap<>(this.behaviorRenderers);
|
||||
private final Vector3f scale = new Vector3f(1.0F, 1.0F, 1.0F);
|
||||
private final Vector3f hitboxScale = new Vector3f(1.0F, 1.0F, 1.0F);
|
||||
private UUID pivotOverride;
|
||||
private ModeledEntity modeledEntity;
|
||||
private boolean mainHitbox;
|
||||
private boolean generated;
|
||||
private boolean destroyed;
|
||||
private boolean removed;
|
||||
private boolean autoRendererInitialization = true;
|
||||
private boolean hitboxVisible = true;
|
||||
private boolean shadowVisible = true;
|
||||
private float viewRange = 4096.0F;
|
||||
private boolean canHurt = true;
|
||||
private Color defaultTint = Color.fromRGB(16777215);
|
||||
private Color damageTint = Color.fromRGB(16737894);
|
||||
private boolean wasMarkedHurt;
|
||||
private Boolean glowing;
|
||||
private Integer glowColor;
|
||||
private Set<UUID> glowAudience;
|
||||
private int blockLight = -1;
|
||||
private int skyLight = -1;
|
||||
private Billboard billboard = Billboard.FIXED;
|
||||
private Boolean onFire;
|
||||
private Boolean renderFire;
|
||||
private boolean lockPitch;
|
||||
private boolean lockYaw;
|
||||
private float lockedYHeadRot = 0.0F;
|
||||
private float lockedXHeadRot = 0.0F;
|
||||
private float lockedYBodyRot = 0.0F;
|
||||
private Boolean modelRotationLocked;
|
||||
private boolean invisUpdate;
|
||||
private boolean cameraPivot;
|
||||
private final BoneSequencer boneSequencer = new BoneSequencer();
|
||||
private ActiveModelImpl.ResolvedBoneOrder resolvedBoneOrder;
|
||||
private final Callback<ActiveModel.Scale> scaleCallback = new Callback<>(
|
||||
scales -> (model, scale) -> scales.forEach(callback -> callback.onScale(model, scale))
|
||||
);
|
||||
private final Callback<Runnable> preSendCallback = new Callback<>(preSends -> () -> preSends.forEach(Runnable::run));
|
||||
private final Callback<Runnable> postSendCallback = new Callback<>(postSends -> () -> postSends.forEach(Runnable::run));
|
||||
|
||||
public ActiveModelImpl(
|
||||
@NotNull ModelBlueprint blueprint,
|
||||
@Nullable Function<ActiveModel, ModelRenderer> rendererSupplier,
|
||||
@Nullable Function<ActiveModel, AnimationHandler> handlerSupplier
|
||||
) {
|
||||
this.blueprint = blueprint;
|
||||
ModelRenderer renderer = (ModelRenderer)(rendererSupplier == null ? new DisplayRendererImpl(this) : rendererSupplier.apply(this));
|
||||
this.modelRenderer = (ModelRenderer)(renderer == null ? new DisplayRendererImpl(this) : renderer);
|
||||
AnimationHandler handler = handlerSupplier == null ? createDefaultHandler(this) : handlerSupplier.apply(this);
|
||||
this.animationHandler = handler == null ? createDefaultHandler(this) : handler;
|
||||
}
|
||||
|
||||
private static AnimationHandler createDefaultHandler(ActiveModel activeModel) {
|
||||
return (AnimationHandler)(ConfigProperty.USE_STATE_MACHINE.getBoolean() ? new StateMachineHandler(activeModel) : new PriorityHandler(activeModel));
|
||||
}
|
||||
|
||||
public static ActiveModel fromData(SavedData data) {
|
||||
try {
|
||||
return ModelEngineAPI.createActiveModel(
|
||||
data.getString("blueprint"),
|
||||
null,
|
||||
activeModel -> {
|
||||
activeModel.setMainHitbox(data.getBoolean("main_hitbox"));
|
||||
return data.getData("animation_handler")
|
||||
.map(handlerData -> ModelEngineAPI.getAnimationHandlerRegistry().createHandler(activeModel, handlerData))
|
||||
.orElse(null);
|
||||
}
|
||||
);
|
||||
} catch (Exception var2) {
|
||||
var2.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<PivotOverride> getPivotOverride() {
|
||||
return ModelEngineAPI.getPivotOverrideRegistry().get(this.pivotOverride);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPivotOverride(PivotOverride override) {
|
||||
this.modelRenderer.updatePivotOverride(override);
|
||||
this.pivotOverride = override.getUuid();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, ModelBone> getBones() {
|
||||
return this.boneCache.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<BoneBehaviorType<?>, BehaviorManager<?>> getBehaviorManagers() {
|
||||
Map<BoneBehaviorType<?>, BehaviorManager<?>> cached = this.behaviorManagerCache.getIfCached();
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
} else {
|
||||
synchronized (this.behaviorManagers) {
|
||||
return this.behaviorManagerCache.get();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<BoneBehaviorType<?>, BehaviorRenderer> getBehaviorRenderers() {
|
||||
Map<BoneBehaviorType<?>, BehaviorRenderer> cached = this.behaviorRendererCache.getIfCached();
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
} else {
|
||||
synchronized (this.behaviorRenderers) {
|
||||
return this.behaviorRendererCache.get();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3fc getScale() {
|
||||
return this.scale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setScale(double scale) {
|
||||
this.setScale(new Vector3f((float)scale, (float)scale, (float)scale));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setScale(Vector3fc scale) {
|
||||
this.scale.set(scale);
|
||||
this.scaleCallback.invoker().onScale(this, scale.get(scale.maxComponent()));
|
||||
if (this.mainHitbox && this.modeledEntity != null) {
|
||||
Vector3fc scaleVec = this.getScale();
|
||||
Hitbox mainHitbox = this.blueprint.getMainHitbox();
|
||||
Hitbox scaledRenderHitbox = new Hitbox(
|
||||
mainHitbox.getWidth() * scaleVec.x(),
|
||||
mainHitbox.getHeight() * scaleVec.y(),
|
||||
mainHitbox.getDepth() * scaleVec.z(),
|
||||
mainHitbox.getEyeHeight() * scaleVec.y()
|
||||
);
|
||||
this.modeledEntity.getBase().getData().setCullHitbox(scaledRenderHitbox);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3fc getHitboxScale() {
|
||||
return this.hitboxScale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setHitboxScale(double scale) {
|
||||
this.setHitboxScale(new Vector3f((float)scale, (float)scale, (float)scale));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setHitboxScale(Vector3fc scale) {
|
||||
this.hitboxScale.set(scale);
|
||||
if (this.mainHitbox && this.modeledEntity != null) {
|
||||
if (this.modeledEntity.getBase().getData() instanceof BukkitEntityData data) {
|
||||
Vector3fc hitboxScale = this.getHitboxScale();
|
||||
Hitbox mainHitbox = this.blueprint.getMainHitbox();
|
||||
Hitbox scaledHitbox = new Hitbox(
|
||||
mainHitbox.getWidth() * hitboxScale.x(),
|
||||
mainHitbox.getHeight() * hitboxScale.y(),
|
||||
mainHitbox.getDepth() * hitboxScale.z(),
|
||||
mainHitbox.getEyeHeight() * hitboxScale.y()
|
||||
);
|
||||
data.setHitbox(scaledHitbox);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick() {
|
||||
if (!this.isDestroyed()) {
|
||||
if (this.modeledEntity.getBase().getData().hasTracking()) {
|
||||
this.animationHandler.prepare();
|
||||
this.forManagers(BehaviorManager::preScriptTick);
|
||||
this.animationHandler.tickGlobal();
|
||||
this.forManagers(BehaviorManager::postScriptTick);
|
||||
this.forManagers(BehaviorManager::preBoneTick);
|
||||
this.boneSequencer.reorder(this.roots);
|
||||
List<String> boneOrders = this.boneSequencer.getBoneOrders();
|
||||
int index = 0;
|
||||
|
||||
for (String boneId : boneOrders) {
|
||||
Map<String, ModelBone> boneMap = this.getBones();
|
||||
ActiveModelImpl.ResolvedBoneOrder order = this.resolvedBoneOrder;
|
||||
if (order == null || order.source() != boneMap || index >= order.ids().length || order.ids()[index] != boneId) {
|
||||
this.resolvedBoneOrder = order = ActiveModelImpl.ResolvedBoneOrder.resolve(boneMap, boneOrders);
|
||||
}
|
||||
|
||||
ModelBone bone = order.source() == boneMap && index < order.ids().length && order.ids()[index] == boneId
|
||||
? order.bones()[index]
|
||||
: boneMap.get(boneId);
|
||||
index++;
|
||||
if (bone != null) {
|
||||
bone.tick();
|
||||
}
|
||||
}
|
||||
|
||||
this.forManagers(BehaviorManager::postBoneTick);
|
||||
this.modelRenderer.readModelData();
|
||||
this.wasMarkedHurt = this.isMarkedHurt();
|
||||
} else {
|
||||
this.animationHandler.prepare();
|
||||
this.forBones(ModelBone::lazyTick);
|
||||
this.animationHandler.tickGlobal();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
this.forBones(ModelBone::destroy);
|
||||
this.forManagers(BehaviorManager::onDestroy);
|
||||
this.bones.clear();
|
||||
this.boneCache.invalidate();
|
||||
this.behaviorManagerCache.invalidate();
|
||||
this.behaviorRendererCache.invalidate();
|
||||
this.boneSequencer.setDirty(true);
|
||||
this.getData().markModelGlowing(this, false);
|
||||
this.modelRenderer.destroy(ModelEngineAPI.getNMSHandler().getGlobalParsers());
|
||||
this.destroyed = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initializeRenderer() {
|
||||
if (!this.modelRenderer.isInitialized()) {
|
||||
this.modelRenderer.initialize();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void generateModel() {
|
||||
if (!this.generated) {
|
||||
this.generated = true;
|
||||
|
||||
for (Entry<String, BlueprintBone> entry : this.blueprint.getFlatMap().entrySet()) {
|
||||
BlueprintBone blueprint = entry.getValue();
|
||||
ModelBone parent = blueprint.getParent() == null ? null : this.bones.get(blueprint.getParent().getName());
|
||||
ModelBoneImpl bone = new ModelBoneImpl(this, blueprint);
|
||||
this.configureChildBone(blueprint, parent, bone);
|
||||
this.bones.put(bone.getUniqueBoneId(), bone);
|
||||
this.boneCache.invalidate();
|
||||
this.behaviorManagerCache.invalidate();
|
||||
this.behaviorRendererCache.invalidate();
|
||||
this.boneSequencer.setDirty(true);
|
||||
}
|
||||
|
||||
this.bones.forEach((s, bonex) -> bonex.forBehaviors(BoneBehavior::onModelInitialized));
|
||||
if (this.autoRendererInitialization) {
|
||||
this.modelRenderer.initialize();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forceGenerateBone(String parentId, String prefix, final BlueprintBone blueprintBone) {
|
||||
ModelBone parentBone = parentId == null ? null : this.getBone(parentId).orElse(null);
|
||||
HashMap<String, ModelBone> forceBoneMap = new HashMap<>();
|
||||
var queue = new LinkedList<BlueprintBone>() {
|
||||
{
|
||||
this.add(blueprintBone);
|
||||
}
|
||||
};
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
BlueprintBone blueprint = queue.pop();
|
||||
queue.addAll(blueprint.getChildren().values());
|
||||
String name = blueprint.getName();
|
||||
String customId = prefix + name;
|
||||
if (this.bones.containsKey(customId)) {
|
||||
TLogger.error("Unable to force generate custom bone: ID " + customId + " already exists.");
|
||||
} else {
|
||||
ModelBone parent = blueprint.getParent() == null ? parentBone : forceBoneMap.getOrDefault(blueprint.getParent().getName(), parentBone);
|
||||
ModelBoneImpl bone = new ModelBoneImpl(this, blueprint);
|
||||
bone.setCustomId(customId);
|
||||
this.configureChildBone(blueprint, parent, bone);
|
||||
forceBoneMap.put(name, bone);
|
||||
this.bones.put(bone.getUniqueBoneId(), bone);
|
||||
this.boneCache.invalidate();
|
||||
this.behaviorManagerCache.invalidate();
|
||||
this.behaviorRendererCache.invalidate();
|
||||
this.boneSequencer.setDirty(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void configureChildBone(BlueprintBone blueprint, ModelBone parent, ModelBoneImpl bone) {
|
||||
if (parent != null) {
|
||||
bone.setParent(parent);
|
||||
if (parent.isPivotOverride()) {
|
||||
bone.setPivot(parent);
|
||||
} else if (parent.getPivot() != null) {
|
||||
bone.setPivot(parent.getPivot());
|
||||
}
|
||||
} else {
|
||||
this.roots.put(bone.getUniqueBoneId(), bone);
|
||||
}
|
||||
|
||||
for (Entry<BoneBehaviorType<?>, BoneBehaviorType.CachedProvider<?>> behaviorEntry : blueprint.getCachedBehaviorProvider().entrySet()) {
|
||||
BoneBehaviorType<?> type = behaviorEntry.getKey();
|
||||
BoneBehaviorType.CachedProvider<?> provider = behaviorEntry.getValue();
|
||||
this.getBehaviorManager(type);
|
||||
this.getBehaviorRenderer(type);
|
||||
bone.addBoneBehavior(provider.create(bone));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeBone(String bone) {
|
||||
ModelBone removed = this.bones.remove(bone);
|
||||
if (removed != null) {
|
||||
removed.setParent(null);
|
||||
this.roots.remove(bone);
|
||||
this.boneCache.invalidate();
|
||||
this.boneSequencer.setDirty(true);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canHurt() {
|
||||
return this.canHurt;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean wasMarkedHurt() {
|
||||
return this.wasMarkedHurt;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isMarkedHurt() {
|
||||
return this.canHurt && this.modeledEntity != null && this.modeledEntity.getHurtTick() > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isGlowing() {
|
||||
return this.glowing == null ? this.modeledEntity.isGlowing() : this.glowing;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setGlowing(@Nullable Boolean flag) {
|
||||
this.glowing = flag;
|
||||
this.getData().markModelGlowing(this, this.glowing != null && this.glowing);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getGlowColor() {
|
||||
return this.glowColor == null ? this.modeledEntity.getGlowColor() : this.glowColor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<UUID> getGlowAudience() {
|
||||
return this.glowAudience;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOnFire() {
|
||||
return this.onFire == null ? this.modeledEntity.getBase().isOnFire() : this.onFire;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canRenderFire() {
|
||||
return this.renderFire == null ? ModelEngineAPI.getConfigCache().isRenderFire() : this.renderFire;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getXHeadRot() {
|
||||
return this.useLock() ? this.lockedXHeadRot : (this.lockPitch ? 0.0F : this.modeledEntity.getXHeadRot());
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getYHeadRot() {
|
||||
return this.useLock() ? this.lockedYHeadRot : (this.lockYaw ? this.modeledEntity.getYBodyRot() : this.modeledEntity.getYHeadRot());
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getYBodyRot() {
|
||||
return this.useLock() ? this.lockedYBodyRot : this.modeledEntity.getYBodyRot();
|
||||
}
|
||||
|
||||
private boolean useLock() {
|
||||
return this.modelRotationLocked != null && this.modelRotationLocked;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isModelRotationLocked() {
|
||||
return this.modelRotationLocked == null ? this.modeledEntity.isModelRotationLocked() : this.modelRotationLocked;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setModelRotationLocked(Boolean flag) {
|
||||
if (this.modelRotationLocked != flag) {
|
||||
this.modelRotationLocked = flag;
|
||||
if (this.modelRotationLocked) {
|
||||
this.lockedYHeadRot = this.modeledEntity.getYHeadRot();
|
||||
this.lockedXHeadRot = this.modeledEntity.getXHeadRot();
|
||||
this.lockedYBodyRot = this.modeledEntity.getYBodyRot();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends BoneBehavior> Optional<BehaviorManager<T>> getBehaviorManager(BoneBehaviorType<T> type) {
|
||||
BoneBehaviorType.BehaviorManagerProvider<T> provider = type.getBehaviorManagerProvider();
|
||||
if (provider == null) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
synchronized (this.behaviorManagers) {
|
||||
BehaviorManager<T> existing = (BehaviorManager<T>)this.behaviorManagers.get(type);
|
||||
return existing != null
|
||||
? Optional.of(existing)
|
||||
: Optional.ofNullable((BehaviorManager<T>)this.behaviorManagers.computeIfAbsent(type, boneBehaviorType -> {
|
||||
BehaviorManager<T> manager = provider.create(this, type);
|
||||
if (manager == null) {
|
||||
return null;
|
||||
} else {
|
||||
manager.onCreate();
|
||||
return manager;
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<BehaviorRenderer> getBehaviorRenderer(BoneBehaviorType<?> type) {
|
||||
synchronized (this.behaviorRenderers) {
|
||||
BehaviorRenderer renderer = this.behaviorRenderers.get(type);
|
||||
if (renderer != null) {
|
||||
return Optional.of(renderer);
|
||||
} else {
|
||||
renderer = type.getRenderType().createBehaviorRenderer(this);
|
||||
if (renderer != null) {
|
||||
this.behaviorRenderers.put(type, renderer);
|
||||
}
|
||||
|
||||
return Optional.ofNullable(renderer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void forBones(Consumer<ModelBone> consumer) {
|
||||
for (ModelBone bone : this.roots.values()) {
|
||||
consumer.accept(bone);
|
||||
}
|
||||
}
|
||||
|
||||
private void forManagers(Consumer<BehaviorManager<?>> consumer) {
|
||||
synchronized (this.behaviorManagers) {
|
||||
for (BehaviorManager<?> manager : this.behaviorManagers.values()) {
|
||||
consumer.accept(manager);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(SavedData data) {
|
||||
data.putString("blueprint", this.blueprint.getName());
|
||||
data.putFloat("render_scale", this.getScale().x());
|
||||
data.putFloat("hitbox_scale", this.getHitboxScale().x());
|
||||
data.putBoolean("can_hurt", this.canHurt());
|
||||
data.putInt("default_tint", this.defaultTint.asRGB());
|
||||
data.putInt("damage_tint", this.damageTint.asRGB());
|
||||
data.putBoolean("lock_pitch", this.lockPitch);
|
||||
data.putBoolean("lock_yaw", this.lockYaw);
|
||||
data.putBoolean("hitbox_visible", this.hitboxVisible);
|
||||
data.putBoolean("shadow_visible", this.shadowVisible);
|
||||
data.putBoolean("main_hitbox", this.mainHitbox);
|
||||
data.putBoolean("glowing", this.glowing);
|
||||
data.putInt("glow_color", this.glowColor);
|
||||
data.putInt("block_light", this.blockLight);
|
||||
data.putInt("sky_light", this.skyLight);
|
||||
HashSet<String> removed = new HashSet<>();
|
||||
SavedData boneDataMap = new SavedData();
|
||||
|
||||
for (String boneId : this.blueprint.getFlatMap().keySet()) {
|
||||
ModelBone bone = this.bones.get(boneId);
|
||||
if (bone == null) {
|
||||
removed.add(boneId);
|
||||
} else {
|
||||
bone.save().ifPresent(boneData -> boneDataMap.putData(boneId, boneData));
|
||||
}
|
||||
}
|
||||
|
||||
data.putList("removed", removed);
|
||||
data.putData("default_bones", boneDataMap);
|
||||
this.animationHandler.save().ifPresent(animationData -> data.putData("animation_handler", animationData));
|
||||
Map<BoneBehaviorType<?>, BehaviorManager<?>> managers = this.getBehaviorManagers();
|
||||
if (!managers.isEmpty()) {
|
||||
SavedData managerData = new SavedData();
|
||||
managers.forEach((boneBehaviorType, manager) -> manager.save().ifPresent(savedData -> managerData.putData(boneBehaviorType.getId(), savedData)));
|
||||
data.putData("managers", managerData);
|
||||
}
|
||||
|
||||
Map<BoneBehaviorType<?>, BehaviorRenderer> renderers = this.getBehaviorRenderers();
|
||||
if (!renderers.isEmpty()) {
|
||||
SavedData rendererData = new SavedData();
|
||||
renderers.forEach((boneBehaviorType, renderer) -> renderer.save().ifPresent(savedData -> rendererData.putData(boneBehaviorType.getId(), savedData)));
|
||||
data.putData("renderers", rendererData);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(SavedData data) {
|
||||
this.setScale(data.getFloat("render_scale").floatValue());
|
||||
this.setHitboxScale(data.getFloat("hitbox_scale").floatValue());
|
||||
this.setCanHurt(data.getBoolean("can_hurt"));
|
||||
this.setDefaultTint(Color.fromRGB(data.getInt("default_tint")));
|
||||
this.setDamageTint(Color.fromRGB(data.getInt("damage_tint")));
|
||||
this.setLockPitch(data.getBoolean("lock_pitch"));
|
||||
this.setLockYaw(data.getBoolean("lock_yaw"));
|
||||
this.setHitboxVisible(data.getBoolean("hitbox_visible"));
|
||||
this.setShadowVisible(data.getBoolean("shadow_visible"));
|
||||
this.setGlowing(data.getBoolean("glowing"));
|
||||
this.setGlowColor(data.getInt("glow_color"));
|
||||
this.setBlockLight(data.getInt("block_light", -1));
|
||||
this.setSkyLight(data.getInt("sky_light", -1));
|
||||
|
||||
for (Object remove : data.getList("removed")) {
|
||||
this.removeBone((String)remove);
|
||||
}
|
||||
|
||||
data.getData("default_bones").ifPresent(boneDataMap -> {
|
||||
for (String key : boneDataMap.keySet()) {
|
||||
this.getBone(key).ifPresent(modelBone -> boneDataMap.getData(key).ifPresent(modelBone::load));
|
||||
}
|
||||
});
|
||||
Optional<SavedData> managerData = data.getData("managers");
|
||||
managerData.ifPresent(
|
||||
savedData -> this.getBehaviorManagers().forEach((boneBehaviorType, manager) -> savedData.getData(boneBehaviorType.getId()).ifPresent(manager::load))
|
||||
);
|
||||
Optional<SavedData> renderersData = data.getData("renderers");
|
||||
renderersData.ifPresent(
|
||||
savedData -> this.getBehaviorRenderers()
|
||||
.forEach((boneBehaviorType, renderer) -> savedData.getData(boneBehaviorType.getId()).ifPresent(renderer::load))
|
||||
);
|
||||
}
|
||||
|
||||
private IEntityData getData() {
|
||||
return this.modeledEntity.getBase().getData();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModelBlueprint getBlueprint() {
|
||||
return this.blueprint;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MetadataRegistry getMetadata() {
|
||||
return this.metadata;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModelRenderer getModelRenderer() {
|
||||
return this.modelRenderer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AnimationHandler getAnimationHandler() {
|
||||
return this.animationHandler;
|
||||
}
|
||||
|
||||
public CachedImmutableMap<String, ModelBone> getBoneCache() {
|
||||
return this.boneCache;
|
||||
}
|
||||
|
||||
public CachedImmutableMap<BoneBehaviorType<?>, BehaviorManager<?>> getBehaviorManagerCache() {
|
||||
return this.behaviorManagerCache;
|
||||
}
|
||||
|
||||
public CachedImmutableMap<BoneBehaviorType<?>, BehaviorRenderer> getBehaviorRendererCache() {
|
||||
return this.behaviorRendererCache;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModeledEntity getModeledEntity() {
|
||||
return this.modeledEntity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isMainHitbox() {
|
||||
return this.mainHitbox;
|
||||
}
|
||||
|
||||
public boolean isGenerated() {
|
||||
return this.generated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDestroyed() {
|
||||
return this.destroyed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRemoved() {
|
||||
return this.removed;
|
||||
}
|
||||
|
||||
public boolean isAutoRendererInitialization() {
|
||||
return this.autoRendererInitialization;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHitboxVisible() {
|
||||
return this.hitboxVisible;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isShadowVisible() {
|
||||
return this.shadowVisible;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getViewRange() {
|
||||
return this.viewRange;
|
||||
}
|
||||
|
||||
public boolean isCanHurt() {
|
||||
return this.canHurt;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Color getDefaultTint() {
|
||||
return this.defaultTint;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Color getDamageTint() {
|
||||
return this.damageTint;
|
||||
}
|
||||
|
||||
public boolean isWasMarkedHurt() {
|
||||
return this.wasMarkedHurt;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getBlockLight() {
|
||||
return this.blockLight;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getSkyLight() {
|
||||
return this.skyLight;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Billboard getBillboard() {
|
||||
return this.billboard;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLockPitch() {
|
||||
return this.lockPitch;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLockYaw() {
|
||||
return this.lockYaw;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getLockedYHeadRot() {
|
||||
return this.lockedYHeadRot;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getLockedXHeadRot() {
|
||||
return this.lockedXHeadRot;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getLockedYBodyRot() {
|
||||
return this.lockedYBodyRot;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInvisUpdate() {
|
||||
return this.invisUpdate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCameraPivot() {
|
||||
return this.cameraPivot;
|
||||
}
|
||||
|
||||
public BoneSequencer getBoneSequencer() {
|
||||
return this.boneSequencer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Callback<ActiveModel.Scale> getScaleCallback() {
|
||||
return this.scaleCallback;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Callback<Runnable> getPreSendCallback() {
|
||||
return this.preSendCallback;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Callback<Runnable> getPostSendCallback() {
|
||||
return this.postSendCallback;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setModeledEntity(ModeledEntity modeledEntity) {
|
||||
this.modeledEntity = modeledEntity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMainHitbox(boolean mainHitbox) {
|
||||
this.mainHitbox = mainHitbox;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRemoved(boolean removed) {
|
||||
this.removed = removed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAutoRendererInitialization(boolean autoRendererInitialization) {
|
||||
this.autoRendererInitialization = autoRendererInitialization;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setHitboxVisible(boolean hitboxVisible) {
|
||||
this.hitboxVisible = hitboxVisible;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setShadowVisible(boolean shadowVisible) {
|
||||
this.shadowVisible = shadowVisible;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setViewRange(float viewRange) {
|
||||
this.viewRange = viewRange;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCanHurt(boolean canHurt) {
|
||||
this.canHurt = canHurt;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDefaultTint(Color defaultTint) {
|
||||
this.defaultTint = defaultTint;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDamageTint(Color damageTint) {
|
||||
this.damageTint = damageTint;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setGlowColor(Integer glowColor) {
|
||||
this.glowColor = glowColor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setGlowAudience(Set<UUID> glowAudience) {
|
||||
this.glowAudience = glowAudience;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBlockLight(int blockLight) {
|
||||
this.blockLight = blockLight;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSkyLight(int skyLight) {
|
||||
this.skyLight = skyLight;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBillboard(Billboard billboard) {
|
||||
this.billboard = billboard;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setOnFire(Boolean onFire) {
|
||||
this.onFire = onFire;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRenderFire(Boolean renderFire) {
|
||||
this.renderFire = renderFire;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLockPitch(boolean lockPitch) {
|
||||
this.lockPitch = lockPitch;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLockYaw(boolean lockYaw) {
|
||||
this.lockYaw = lockYaw;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLockedYHeadRot(float lockedYHeadRot) {
|
||||
this.lockedYHeadRot = lockedYHeadRot;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLockedXHeadRot(float lockedXHeadRot) {
|
||||
this.lockedXHeadRot = lockedXHeadRot;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLockedYBodyRot(float lockedYBodyRot) {
|
||||
this.lockedYBodyRot = lockedYBodyRot;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setInvisUpdate(boolean invisUpdate) {
|
||||
this.invisUpdate = invisUpdate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCameraPivot(boolean cameraPivot) {
|
||||
this.cameraPivot = cameraPivot;
|
||||
}
|
||||
|
||||
private record ResolvedBoneOrder(Map<String, ModelBone> source, String[] ids, ModelBone[] bones) {
|
||||
private static ActiveModelImpl.ResolvedBoneOrder resolve(Map<String, ModelBone> source, List<String> boneOrders) {
|
||||
String[] ids = boneOrders.toArray(new String[0]);
|
||||
ModelBone[] bones = new ModelBone[ids.length];
|
||||
|
||||
for (int i = 0; i < ids.length; i++) {
|
||||
bones[i] = source.get(ids[i]);
|
||||
}
|
||||
|
||||
return new ActiveModelImpl.ResolvedBoneOrder(source, ids, bones);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.ticxo.modelengine.core.model;
|
||||
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class BoneSequencer {
|
||||
private final Set<String> processedBones = new HashSet<>();
|
||||
private final List<String> boneOrders = new ArrayList<>();
|
||||
private volatile boolean dirty = true;
|
||||
|
||||
protected void reorder(Map<String, ModelBone> roots) {
|
||||
if (this.dirty) {
|
||||
this.dirty = false;
|
||||
this.processedBones.clear();
|
||||
this.boneOrders.clear();
|
||||
|
||||
int size;
|
||||
do {
|
||||
size = this.boneOrders.size();
|
||||
this.order(roots);
|
||||
} while (size != this.boneOrders.size());
|
||||
}
|
||||
}
|
||||
|
||||
private void order(Map<String, ModelBone> roots) {
|
||||
for (ModelBone bone : roots.values()) {
|
||||
if (this.processedBones.contains(bone.getBoneId())) {
|
||||
this.order(bone.getChildren());
|
||||
} else if (bone.getTickDependencies().isEmpty() || this.processedBones.containsAll(bone.getTickDependencies())) {
|
||||
this.boneOrders.add(bone.getBoneId());
|
||||
this.processedBones.add(bone.getBoneId());
|
||||
this.order(bone.getChildren());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> getBoneOrders() {
|
||||
return this.boneOrders;
|
||||
}
|
||||
|
||||
public void setDirty(boolean dirty) {
|
||||
this.dirty = dirty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,624 @@
|
||||
package com.ticxo.modelengine.core.model;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.animation.rootmotion.RootMotionHandler;
|
||||
import com.ticxo.modelengine.api.entity.BaseEntity;
|
||||
import com.ticxo.modelengine.api.entity.Hitbox;
|
||||
import com.ticxo.modelengine.api.entity.data.BukkitEntityData;
|
||||
import com.ticxo.modelengine.api.events.AddModelEvent;
|
||||
import com.ticxo.modelengine.api.events.ModelSetupEvent;
|
||||
import com.ticxo.modelengine.api.events.RemoveModelEvent;
|
||||
import com.ticxo.modelengine.api.lod.AnimationLODHandler;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.MountData;
|
||||
import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController;
|
||||
import com.ticxo.modelengine.api.utils.callback.Callback;
|
||||
import com.ticxo.modelengine.api.utils.data.io.SavedData;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.FloatDataTracker;
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import com.ticxo.modelengine.api.utils.meta.MetadataRegistry;
|
||||
import com.ticxo.modelengine.core.model.bone.manager.MountDataImpl;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.joml.Vector3fc;
|
||||
|
||||
public class ModeledEntityImpl implements ModeledEntity {
|
||||
private final BaseEntity<?> base;
|
||||
private final MetadataRegistry metadata = new MetadataRegistry();
|
||||
private final AnimationLODHandler animationLodHandler;
|
||||
private final Map<String, ActiveModel> models = Maps.newConcurrentMap();
|
||||
private final Map<BoneBehaviorType<?>, GlobalBehaviorData> data = Maps.newConcurrentMap();
|
||||
private final Map<ModeledEntity.Phase, Map<UUID, Function<ModeledEntity, Boolean>>> tickTasks = Maps.newConcurrentMap();
|
||||
private final Callback<Runnable> destroyCallback = new Callback<>(runs -> () -> runs.forEach(Runnable::run));
|
||||
private volatile Map<String, ActiveModel> cachedModels;
|
||||
private final boolean initialized;
|
||||
private final List<Runnable> queuedTask = new ArrayList<>();
|
||||
private final FloatDataTracker trueYHeadRot = new FloatDataTracker(0.0F);
|
||||
private final FloatDataTracker trueXHeadRot = new FloatDataTracker(0.0F);
|
||||
private final FloatDataTracker trueYBodyRot = new FloatDataTracker(0.0F);
|
||||
private final RootMotionHandler rootMotionHandler = new RootMotionHandler(this);
|
||||
private int tick;
|
||||
private boolean isBaseEntityVisible = true;
|
||||
private boolean destroyed;
|
||||
private boolean removed;
|
||||
private int hurtTick = 0;
|
||||
private boolean isModelRotationLocked;
|
||||
private int rotationTick = -1;
|
||||
private float yHeadRot = 0.0F;
|
||||
private float xHeadRot = 0.0F;
|
||||
private float yBodyRot = 0.0F;
|
||||
private boolean shouldSave = true;
|
||||
private volatile String cachedSaveJson;
|
||||
private ActiveModel lastHitboxOverride = null;
|
||||
|
||||
public ModeledEntityImpl(@NotNull BaseEntity<?> base, @Nullable Consumer<ModeledEntity> consumer) {
|
||||
this.base = base;
|
||||
this.animationLodHandler = new AnimationLODHandler(this);
|
||||
if (consumer != null) {
|
||||
consumer.accept(this);
|
||||
}
|
||||
|
||||
synchronized (this.queuedTask) {
|
||||
this.queuedTask.forEach(Runnable::run);
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
this.registerSelf();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean tick() {
|
||||
if (!this.initialized) {
|
||||
return true;
|
||||
} else {
|
||||
if (this.hurtTick > 0) {
|
||||
this.hurtTick--;
|
||||
}
|
||||
|
||||
if (this.base.isAlive()) {
|
||||
if (!this.isModelRotationLocked) {
|
||||
BodyRotationController bodyRotationController = this.base.getBodyRotationController();
|
||||
bodyRotationController.tick();
|
||||
this.trueYHeadRot.set(bodyRotationController.getYHeadRot());
|
||||
this.trueXHeadRot.set(bodyRotationController.getXHeadRot());
|
||||
this.trueYBodyRot.set(bodyRotationController.getYBodyRot());
|
||||
}
|
||||
|
||||
if (this.rotationTick == -1) {
|
||||
this.yHeadRot = this.trueYHeadRot.get();
|
||||
this.xHeadRot = this.trueXHeadRot.get();
|
||||
this.yBodyRot = this.trueYBodyRot.get();
|
||||
this.trueYHeadRot.clearDirty();
|
||||
this.trueXHeadRot.clearDirty();
|
||||
this.trueYBodyRot.clearDirty();
|
||||
this.rotationTick = 0;
|
||||
}
|
||||
|
||||
if (!this.base.isWalking()) {
|
||||
this.yBodyRot = this.trueYBodyRot.get();
|
||||
}
|
||||
|
||||
if (this.trueYHeadRot.isDirty() || this.trueXHeadRot.isDirty() || this.trueYBodyRot.isDirty()) {
|
||||
this.rotationTick = 3;
|
||||
this.trueYHeadRot.clearDirty();
|
||||
this.trueXHeadRot.clearDirty();
|
||||
this.trueYBodyRot.clearDirty();
|
||||
}
|
||||
|
||||
if (this.rotationTick > 0) {
|
||||
this.yHeadRot = TMath.rotLerp(this.yHeadRot, this.trueYHeadRot.get(), (double)(1.0F / this.rotationTick));
|
||||
this.xHeadRot = TMath.rotLerp(this.xHeadRot, this.trueXHeadRot.get(), (double)(1.0F / this.rotationTick));
|
||||
this.yBodyRot = TMath.rotLerp(this.yBodyRot, this.trueYBodyRot.get(), (double)(1.0F / this.rotationTick));
|
||||
this.rotationTick--;
|
||||
}
|
||||
}
|
||||
|
||||
this.validateYaws();
|
||||
this.tick++;
|
||||
if (this.removed || this.base.isRemoved()) {
|
||||
return false;
|
||||
} else if (this.base.isAlive()) {
|
||||
for (ActiveModel model : this.models.values()) {
|
||||
model.tick();
|
||||
}
|
||||
|
||||
return true;
|
||||
} else {
|
||||
boolean hasFinished = true;
|
||||
|
||||
for (ActiveModel model : this.models.values()) {
|
||||
model.tick();
|
||||
if (hasFinished) {
|
||||
hasFinished = model.getAnimationHandler().hasFinishedAllAnimations();
|
||||
}
|
||||
}
|
||||
|
||||
this.base.setForcedAlive(!hasFinished);
|
||||
return !hasFinished && !this.base.getData().getTracking().isEmpty();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateYaws() {
|
||||
if (Float.isNaN(this.trueYHeadRot.get())) {
|
||||
this.trueYHeadRot.set(0.0F);
|
||||
}
|
||||
|
||||
if (Float.isNaN(this.trueXHeadRot.get())) {
|
||||
this.trueXHeadRot.set(0.0F);
|
||||
}
|
||||
|
||||
if (Float.isNaN(this.trueYBodyRot.get())) {
|
||||
this.trueYBodyRot.set(0.0F);
|
||||
}
|
||||
|
||||
this.yHeadRot = Float.isNaN(this.yHeadRot) ? 0.0F : this.yHeadRot;
|
||||
this.xHeadRot = Float.isNaN(this.xHeadRot) ? 0.0F : this.xHeadRot;
|
||||
this.yBodyRot = Float.isNaN(this.yBodyRot) ? 0.0F : this.yBodyRot;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
this.destroyCallback.invoker().run();
|
||||
this.destroyed = true;
|
||||
this.animationLodHandler.destroy();
|
||||
this.models.forEach((s, model) -> model.destroy());
|
||||
this.models.clear();
|
||||
this.cachedModels = null;
|
||||
if (this.base.getOriginal() instanceof Entity entity && !(entity instanceof Player)) {
|
||||
ModelEngineAPI.getPivotOverrideRegistry().remove(entity.getUniqueId());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markRemoved() {
|
||||
this.removed = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void restore() {
|
||||
this.removed = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void queuePostInitTask(Runnable runnable) {
|
||||
synchronized (this.queuedTask) {
|
||||
if (this.initialized) {
|
||||
runnable.run();
|
||||
} else {
|
||||
this.queuedTask.add(runnable);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBaseEntityVisible(boolean flag) {
|
||||
if (this.isBaseEntityVisible() != flag) {
|
||||
this.isBaseEntityVisible = flag;
|
||||
this.base.setVisible(this.isBaseEntityVisible);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markHurt() {
|
||||
this.hurtTick = 10;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldBeSaved() {
|
||||
return this.shouldSave;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSaved(boolean flag) {
|
||||
this.shouldSave = flag;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getCachedSaveJson() {
|
||||
return this.cachedSaveJson;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateSaveCache() {
|
||||
try {
|
||||
this.save().ifPresentOrElse(data -> this.cachedSaveJson = data.toString(), () -> this.cachedSaveJson = null);
|
||||
} catch (Throwable var2) {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isGlowing() {
|
||||
return this.base.isGlowing();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getGlowColor() {
|
||||
return this.base.getGlowColor();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setYHeadRot(float rotation) {
|
||||
this.trueYHeadRot.set(rotation);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setXHeadRot(float rotation) {
|
||||
this.trueXHeadRot.set(rotation);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setYBodyRot(float rotation) {
|
||||
this.trueYBodyRot.set(rotation);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setYHeadRotImmediately(float rotation) {
|
||||
this.trueYHeadRot.set(rotation);
|
||||
this.yHeadRot = rotation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setXHeadRotImmediately(float rotation) {
|
||||
this.trueXHeadRot.set(rotation);
|
||||
this.xHeadRot = rotation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setYBodyRotImmediately(float rotation) {
|
||||
this.trueYBodyRot.set(rotation);
|
||||
this.yBodyRot = rotation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRotationTick(int rotationTick) {
|
||||
this.rotationTick = rotationTick;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ActiveModel> addModel(@NotNull ActiveModel model, boolean overrideHitbox) {
|
||||
assert !this.isDestroyed() : "Modeled Entity has been destroyed!";
|
||||
|
||||
assert model.getModeledEntity() == null || model.isRemoved() : "Active Model already belongs to a different Modeled Entity";
|
||||
|
||||
AddModelEvent event = new AddModelEvent(this, model);
|
||||
event.setOverrideHitbox(overrideHitbox);
|
||||
ModelEngineAPI.callEvent(event);
|
||||
if (event.isCancelled()) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
model.setRemoved(false);
|
||||
model.setModeledEntity(this);
|
||||
model.generateModel();
|
||||
Optional<ActiveModel> previous = this.removeModel(model.getBlueprint().getName());
|
||||
this.models.put(model.getBlueprint().getName(), model);
|
||||
this.cachedModels = null;
|
||||
model.getMountManager().ifPresent(mountManager -> {
|
||||
GlobalBehaviorData mountData = this.getMountData();
|
||||
if (((MountData)mountData).getMainMountManager() == null) {
|
||||
((MountData)mountData).setMainMountManager(mountManager);
|
||||
}
|
||||
});
|
||||
if (overrideHitbox) {
|
||||
if (this.lastHitboxOverride != null) {
|
||||
this.lastHitboxOverride.setMainHitbox(false);
|
||||
}
|
||||
|
||||
model.setMainHitbox(true);
|
||||
this.lastHitboxOverride = model;
|
||||
Hitbox mainHitbox = model.getBlueprint().getMainHitbox();
|
||||
Vector3fc scale = model.getScale();
|
||||
Hitbox scaledRenderHitbox = new Hitbox(
|
||||
mainHitbox.getWidth() * scale.x(), mainHitbox.getHeight() * scale.y(), mainHitbox.getDepth() * scale.z(), mainHitbox.getEyeHeight() * scale.y()
|
||||
);
|
||||
this.base.getData().setCullHitbox(scaledRenderHitbox);
|
||||
if (this.base.getData() instanceof BukkitEntityData data) {
|
||||
Vector3fc hitboxScale = model.getHitboxScale();
|
||||
Hitbox scaledHitbox = new Hitbox(
|
||||
mainHitbox.getWidth() * hitboxScale.x(),
|
||||
mainHitbox.getHeight() * hitboxScale.y(),
|
||||
mainHitbox.getDepth() * hitboxScale.z(),
|
||||
mainHitbox.getEyeHeight() * hitboxScale.y()
|
||||
);
|
||||
data.setHitbox(scaledHitbox);
|
||||
}
|
||||
}
|
||||
|
||||
ModelEngineAPI.callEvent(new ModelSetupEvent(this, model));
|
||||
return previous;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ActiveModel> removeModel(String id) {
|
||||
assert !this.isDestroyed() : "Modeled Entity has been destroyed!";
|
||||
|
||||
ActiveModel model = this.models.get(id);
|
||||
if (model == null) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
RemoveModelEvent event = new RemoveModelEvent(this, model);
|
||||
ModelEngineAPI.callEvent(event);
|
||||
if (event.isCancelled()) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
this.models.remove(id);
|
||||
this.cachedModels = null;
|
||||
model.setRemoved(true);
|
||||
return Optional.of(model);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ActiveModel> getModel(@Nullable String id) {
|
||||
return Optional.ofNullable(id == null ? null : this.models.get(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, ActiveModel> getModels() {
|
||||
if (this.cachedModels == null) {
|
||||
this.cachedModels = ImmutableMap.copyOf(this.models);
|
||||
}
|
||||
|
||||
return this.cachedModels;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends BoneBehavior> GlobalBehaviorData getOrCreateGlobalBehaviorData(BoneBehaviorType<T> type, Supplier<GlobalBehaviorData> supplier) {
|
||||
GlobalBehaviorData existing = this.data.get(type);
|
||||
return existing != null ? existing : this.data.computeIfAbsent(type, boneBehaviorType -> supplier.get());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends BoneBehavior> GlobalBehaviorData getGlobalBehaviorData(BoneBehaviorType<T> type) {
|
||||
return this.data.get(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends BoneBehavior> GlobalBehaviorData removeGlobalBehaviorData(BoneBehaviorType<T> type) {
|
||||
return this.data.remove(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<BoneBehaviorType<?>, GlobalBehaviorData> getAllGlobalBehaviorData(BoneBehaviorType<?> type) {
|
||||
return ImmutableMap.copyOf(this.data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends GlobalBehaviorData & MountData> T getMountData() {
|
||||
return (T)this.getOrCreateGlobalBehaviorData(BoneBehaviorTypes.MOUNT, MountDataImpl::new);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPivotOverride(int id) {
|
||||
return this.models.values().stream().anyMatch(model -> model.getPivotOverride().map(override -> override.getId() == id).orElse(false));
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID registerTickTask(ModeledEntity.Phase phase, Function<ModeledEntity, Boolean> function) {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
this.tickTasks.computeIfAbsent(phase, phase1 -> Maps.newConcurrentMap()).put(uuid, function);
|
||||
return uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID registerTickTask(ModeledEntity.Phase phase, Consumer<ModeledEntity> consumer) {
|
||||
return this.registerTickTask(phase, modeledEntity -> {
|
||||
consumer.accept(modeledEntity);
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTickTask(UUID uuid) {
|
||||
for (Entry<ModeledEntity.Phase, Map<UUID, Function<ModeledEntity, Boolean>>> entry : this.tickTasks.entrySet()) {
|
||||
if (entry.getValue().remove(uuid) != null) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void runTickTasks(ModeledEntity.Phase phase) {
|
||||
Map<UUID, Function<ModeledEntity, Boolean>> tasks = this.tickTasks.get(phase);
|
||||
if (tasks != null) {
|
||||
HashSet<UUID> remover = null;
|
||||
|
||||
for (Entry<UUID, Function<ModeledEntity, Boolean>> entry : tasks.entrySet()) {
|
||||
if (entry.getValue().apply(this)) {
|
||||
if (remover == null) {
|
||||
remover = new HashSet<>();
|
||||
}
|
||||
|
||||
remover.add(entry.getKey());
|
||||
}
|
||||
}
|
||||
|
||||
if (remover != null) {
|
||||
remover.forEach(tasks::remove);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(SavedData data) {
|
||||
data.putString("version", "R4.0.3");
|
||||
data.putBoolean("base_visible", this.isBaseEntityVisible());
|
||||
data.putBoolean("rotation_locked", this.isModelRotationLocked());
|
||||
data.putFloat("head_y", this.trueYHeadRot.get());
|
||||
data.putFloat("head_x", this.trueXHeadRot.get());
|
||||
data.putFloat("body_y", this.trueYBodyRot.get());
|
||||
ArrayList<SavedData> list = new ArrayList<>();
|
||||
|
||||
for (ActiveModel activeModel : this.models.values()) {
|
||||
activeModel.save().ifPresent(list::add);
|
||||
}
|
||||
|
||||
data.putList("models", list);
|
||||
this.base.save().ifPresent(entityData -> data.putData("base_entity", entityData));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(SavedData data) {
|
||||
this.setBaseEntityVisible(data.getBoolean("base_visible"));
|
||||
this.setModelRotationLocked(data.getBoolean("rotation_locked"));
|
||||
this.trueYHeadRot.set(this.yHeadRot = data.getFloat("head_y", 0.0F));
|
||||
this.trueXHeadRot.set(this.xHeadRot = data.getFloat("head_x", 0.0F));
|
||||
this.trueYBodyRot.set(this.yBodyRot = data.getFloat("body_y", 0.0F));
|
||||
this.trueYHeadRot.clearDirty();
|
||||
this.trueXHeadRot.clearDirty();
|
||||
this.trueYBodyRot.clearDirty();
|
||||
this.base.getBodyRotationController().setYBodyRot(this.yBodyRot);
|
||||
|
||||
for (SavedData modelData : data.getList("models", SavedData.class)) {
|
||||
ActiveModel model = ActiveModelImpl.fromData(modelData);
|
||||
if (model != null) {
|
||||
model.setAutoRendererInitialization(false);
|
||||
this.addModel(model, model.isMainHitbox()).ifPresent(ActiveModel::destroy);
|
||||
model.load(modelData);
|
||||
model.initializeRenderer();
|
||||
}
|
||||
}
|
||||
|
||||
data.getData("base_entity").ifPresent(this.base::load);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BaseEntity<?> getBase() {
|
||||
return this.base;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MetadataRegistry getMetadata() {
|
||||
return this.metadata;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AnimationLODHandler getAnimationLodHandler() {
|
||||
return this.animationLodHandler;
|
||||
}
|
||||
|
||||
public Map<BoneBehaviorType<?>, GlobalBehaviorData> getData() {
|
||||
return this.data;
|
||||
}
|
||||
|
||||
public Map<ModeledEntity.Phase, Map<UUID, Function<ModeledEntity, Boolean>>> getTickTasks() {
|
||||
return this.tickTasks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Callback<Runnable> getDestroyCallback() {
|
||||
return this.destroyCallback;
|
||||
}
|
||||
|
||||
public Map<String, ActiveModel> getCachedModels() {
|
||||
return this.cachedModels;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInitialized() {
|
||||
return this.initialized;
|
||||
}
|
||||
|
||||
public List<Runnable> getQueuedTask() {
|
||||
return this.queuedTask;
|
||||
}
|
||||
|
||||
public FloatDataTracker getTrueYHeadRot() {
|
||||
return this.trueYHeadRot;
|
||||
}
|
||||
|
||||
public FloatDataTracker getTrueXHeadRot() {
|
||||
return this.trueXHeadRot;
|
||||
}
|
||||
|
||||
public FloatDataTracker getTrueYBodyRot() {
|
||||
return this.trueYBodyRot;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RootMotionHandler getRootMotionHandler() {
|
||||
return this.rootMotionHandler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTick() {
|
||||
return this.tick;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isBaseEntityVisible() {
|
||||
return this.isBaseEntityVisible;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDestroyed() {
|
||||
return this.destroyed;
|
||||
}
|
||||
|
||||
public boolean isRemoved() {
|
||||
return this.removed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHurtTick() {
|
||||
return this.hurtTick;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isModelRotationLocked() {
|
||||
return this.isModelRotationLocked;
|
||||
}
|
||||
|
||||
public int getRotationTick() {
|
||||
return this.rotationTick;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getYHeadRot() {
|
||||
return this.yHeadRot;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getXHeadRot() {
|
||||
return this.xHeadRot;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getYBodyRot() {
|
||||
return this.yBodyRot;
|
||||
}
|
||||
|
||||
public boolean isShouldSave() {
|
||||
return this.shouldSave;
|
||||
}
|
||||
|
||||
public ActiveModel getLastHitboxOverride() {
|
||||
return this.lastHitboxOverride;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setModelRotationLocked(boolean isModelRotationLocked) {
|
||||
this.isModelRotationLocked = isModelRotationLocked;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+354
@@ -0,0 +1,354 @@
|
||||
package com.ticxo.modelengine.core.model.bone.behavior;
|
||||
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.model.bone.type.Segment;
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import org.joml.AxisAngle4f;
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
import org.joml.Vector3fc;
|
||||
|
||||
public class AbstractSegmentImpl<T extends BoneBehavior> extends AbstractBoneBehavior<T> implements Segment {
|
||||
protected final boolean backPivot;
|
||||
protected boolean bounded;
|
||||
protected float minX;
|
||||
protected float maxX;
|
||||
protected float minY;
|
||||
protected float maxY;
|
||||
protected float minZ;
|
||||
protected float maxZ;
|
||||
protected float alignRate;
|
||||
protected float elasticity;
|
||||
protected final Vector3f delta = new Vector3f();
|
||||
protected final Vector3f deltaNorm = new Vector3f();
|
||||
protected final Vector3f worldLocation = new Vector3f();
|
||||
protected UUID scaleCallback;
|
||||
protected float boneLength;
|
||||
protected float modelScale = 1.0F;
|
||||
|
||||
public AbstractSegmentImpl(ModelBone bone, BoneBehaviorType<T> type, BoneBehaviorData data) {
|
||||
super(bone, type, data);
|
||||
this.backPivot = data.get("back_pivot", true);
|
||||
this.bounded = data.get("bounded", true);
|
||||
this.minX = data.get("min_x", -50.0F);
|
||||
this.maxX = data.get("max_x", 50.0F);
|
||||
this.minY = data.get("min_y", -50.0F);
|
||||
this.maxY = data.get("max_y", 50.0F);
|
||||
this.minZ = data.get("min_z", -50.0F);
|
||||
this.maxZ = data.get("max_z", 50.0F);
|
||||
this.alignRate = data.get("align_rate", 0.25F);
|
||||
this.elasticity = data.get("elasticity", 0.0F);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onApply() {
|
||||
if (this.backPivot) {
|
||||
this.delta.set(this.bone.getBlueprintBone().getLocalPosition());
|
||||
this.delta.normalize(this.deltaNorm);
|
||||
this.boneLength = this.delta.length();
|
||||
Vector3fc scale = this.bone.getActiveModel().getScale();
|
||||
this.modelScale = scale.get(scale.maxComponent());
|
||||
this.scaleCallback = this.bone.getActiveModel().getScaleCallback().subscribe((model, s) -> this.modelScale = (float)s);
|
||||
this.worldLocation.set(this.bone.getLocation().toVector().toVector3f());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onModelInitialized() {
|
||||
if (!this.backPivot) {
|
||||
Optional<ModelBone> maybeControlBone = this.getControlBone();
|
||||
if (maybeControlBone.isEmpty()) {
|
||||
throw new RuntimeException("Missing control bone for: " + this.bone.getBoneId());
|
||||
} else {
|
||||
ModelBone controlBone = maybeControlBone.get();
|
||||
this.delta.set(controlBone.getBlueprintBone().getLocalPosition());
|
||||
this.delta.normalize(this.deltaNorm);
|
||||
this.boneLength = this.delta.length();
|
||||
Vector3fc scale = this.bone.getActiveModel().getScale();
|
||||
this.modelScale = scale.get(scale.maxComponent());
|
||||
this.scaleCallback = this.bone.getActiveModel().getScaleCallback().subscribe((model, s) -> this.modelScale = (float)s);
|
||||
this.worldLocation.set(controlBone.getLocation().toVector().toVector3f());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<ModelBone> getControlBone() {
|
||||
Map<String, ModelBone> children = this.bone.getChildren();
|
||||
if (children.isEmpty()) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
return children.size() == 1 ? children.values().stream().findFirst() : Optional.ofNullable(children.get(this.bone.getBoneId() + "_ctrl"));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onRemove() {
|
||||
this.bone.getActiveModel().getScaleCallback().unsubscribe(this.scaleCallback);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postGlobalCalculation() {
|
||||
if (this.modelScale != 0.0F) {
|
||||
if (this.backPivot) {
|
||||
this.backPivotCalculation();
|
||||
} else {
|
||||
this.frontPivotCalculation();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void frontPivotCalculation() {
|
||||
Matrix4f parentTransform = this.getParent(parent -> new Matrix4f(parent.getTransformMatrix()), new Matrix4f());
|
||||
if (parentTransform.determinant() != 0.0F) {
|
||||
parentTransform.translate(this.bone.getLocalTransform().getPosition()).rotate(this.bone.getBlueprintBone().getLocalQuaternion());
|
||||
Matrix4f invParentTransform = parentTransform.invert(new Matrix4f());
|
||||
Vector3f pivotLocation = this.bone.calculatePivotLocation().toVector().toVector3f();
|
||||
Vector3f parentLocation = TMath.transform(this.bone.getTransformMatrix(), new Vector3f())
|
||||
.rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0))
|
||||
.mul(this.modelScale)
|
||||
.add(pivotLocation);
|
||||
Matrix4f transformMatrix = this.bone.getTransformMatrix();
|
||||
Vector3f originPosition = TMath.transform(transformMatrix, this.delta)
|
||||
.rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0))
|
||||
.mul(this.modelScale)
|
||||
.add(pivotLocation);
|
||||
float animatedBoneLength = originPosition.distance(parentLocation);
|
||||
float finalBoneLength = TMath.lerp(this.boneLength * this.modelScale, animatedBoneLength, this.elasticity);
|
||||
this.worldLocation.lerp(originPosition, this.alignRate).sub(parentLocation);
|
||||
if (this.worldLocation.lengthSquared() > 1.0E-6F) {
|
||||
this.worldLocation.normalize(finalBoneLength);
|
||||
}
|
||||
|
||||
this.worldLocation.add(parentLocation);
|
||||
Vector3f globalPosition = this.worldLocation
|
||||
.sub(pivotLocation, new Vector3f())
|
||||
.mul(1.0F / this.modelScale)
|
||||
.rotateY(this.bone.getYaw() * (float) (Math.PI / 180.0));
|
||||
Vector3f localPosition = TMath.transform(invParentTransform, globalPosition);
|
||||
Quaternionf q = new Quaternionf();
|
||||
if (this.bounded) {
|
||||
Vector3f normLocalPosition = localPosition.normalize(new Vector3f());
|
||||
Vector3f axis = this.deltaNorm.cross(normLocalPosition, new Vector3f()).normalize();
|
||||
float angle = (float)Math.acos(this.deltaNorm.dot(normLocalPosition));
|
||||
q.set(new AxisAngle4f(angle, axis));
|
||||
if (!q.isFinite()) {
|
||||
this.deltaNorm.rotationTo(localPosition, q);
|
||||
} else {
|
||||
Vector3f euler = TMath.toEulerZYX(q, new Vector3f());
|
||||
euler.x = TMath.clamp(euler.x, this.minX, this.maxX) * (float) (Math.PI / 180.0);
|
||||
euler.y = TMath.clamp(euler.y, this.minY, this.maxY) * (float) (Math.PI / 180.0);
|
||||
euler.z = TMath.clamp(euler.z, this.minZ, this.maxZ) * (float) (Math.PI / 180.0);
|
||||
TMath.toQuaternion(euler, q);
|
||||
this.deltaNorm.rotate(q, localPosition).mul(finalBoneLength / this.modelScale);
|
||||
}
|
||||
} else {
|
||||
this.deltaNorm.rotationTo(localPosition, q);
|
||||
}
|
||||
|
||||
transformMatrix.set(parentTransform);
|
||||
this.worldLocation
|
||||
.set(TMath.transform(transformMatrix, localPosition))
|
||||
.rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0))
|
||||
.mul(this.modelScale)
|
||||
.add(pivotLocation);
|
||||
transformMatrix.rotate(q);
|
||||
}
|
||||
}
|
||||
|
||||
private void backPivotCalculation() {
|
||||
Matrix4f parentTransform = this.getParent(ModelBone::getTransformMatrix, new Matrix4f());
|
||||
Matrix4f invParentTransform = parentTransform.invert(new Matrix4f());
|
||||
Vector3f pivotLocation = this.bone.calculatePivotLocation().toVector().toVector3f();
|
||||
Vector3f parentLocation = this.getParent(parent -> parent.getLocationUnsafe().toVector().toVector3f(), pivotLocation);
|
||||
Matrix4f transformMatrix = this.bone.getTransformMatrix();
|
||||
Vector3f originPosition = TMath.transform(transformMatrix, new Vector3f())
|
||||
.rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0))
|
||||
.mul(this.modelScale)
|
||||
.add(pivotLocation);
|
||||
float animatedBoneLength = originPosition.distance(parentLocation);
|
||||
float finalBoneLength = TMath.lerp(this.boneLength * this.modelScale, animatedBoneLength, this.elasticity);
|
||||
this.worldLocation.lerp(originPosition, this.alignRate).sub(parentLocation);
|
||||
if (this.worldLocation.lengthSquared() > 1.0E-6F) {
|
||||
this.worldLocation.normalize(finalBoneLength);
|
||||
}
|
||||
|
||||
this.worldLocation.add(parentLocation);
|
||||
Vector3f globalPosition = this.worldLocation
|
||||
.sub(pivotLocation, new Vector3f())
|
||||
.mul(1.0F / this.modelScale)
|
||||
.rotateY(this.bone.getYaw() * (float) (Math.PI / 180.0));
|
||||
Vector3f localPosition = TMath.transform(invParentTransform, globalPosition);
|
||||
Quaternionf q = new Quaternionf();
|
||||
if (this.bounded) {
|
||||
Vector3f normLocalPosition = localPosition.normalize(new Vector3f());
|
||||
Vector3f axis = this.deltaNorm.cross(normLocalPosition, new Vector3f()).normalize();
|
||||
float angle = (float)Math.acos(this.deltaNorm.dot(normLocalPosition));
|
||||
q.set(new AxisAngle4f(angle, axis));
|
||||
if (!q.isFinite()) {
|
||||
this.deltaNorm.rotationTo(localPosition, q);
|
||||
} else {
|
||||
Vector3f euler = TMath.toEulerZYX(q, new Vector3f());
|
||||
euler.x = TMath.clamp(euler.x, this.minX, this.maxX) * (float) (Math.PI / 180.0);
|
||||
euler.y = TMath.clamp(euler.y, this.minY, this.maxY) * (float) (Math.PI / 180.0);
|
||||
euler.z = TMath.clamp(euler.z, this.minZ, this.maxZ) * (float) (Math.PI / 180.0);
|
||||
TMath.toQuaternion(euler, q);
|
||||
this.deltaNorm.rotate(q, localPosition).mul(finalBoneLength / this.modelScale);
|
||||
}
|
||||
} else {
|
||||
this.deltaNorm.rotationTo(localPosition, q);
|
||||
}
|
||||
|
||||
transformMatrix.set(parentTransform).translate(localPosition);
|
||||
this.worldLocation
|
||||
.set(TMath.transform(transformMatrix, new Vector3f()))
|
||||
.rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0))
|
||||
.mul(this.modelScale)
|
||||
.add(pivotLocation);
|
||||
transformMatrix.rotate(q).rotate(this.bone.getBlueprintBone().getLocalQuaternion());
|
||||
}
|
||||
|
||||
private <R> R getParent(Function<ModelBone, R> function, R def) {
|
||||
return this.bone.getParent() == null ? def : function.apply(this.bone.getParent());
|
||||
}
|
||||
|
||||
public boolean isBackPivot() {
|
||||
return this.backPivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isBounded() {
|
||||
return this.bounded;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getMinX() {
|
||||
return this.minX;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getMaxX() {
|
||||
return this.maxX;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getMinY() {
|
||||
return this.minY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getMaxY() {
|
||||
return this.maxY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getMinZ() {
|
||||
return this.minZ;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getMaxZ() {
|
||||
return this.maxZ;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getAlignRate() {
|
||||
return this.alignRate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getElasticity() {
|
||||
return this.elasticity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3f getDelta() {
|
||||
return this.delta;
|
||||
}
|
||||
|
||||
public Vector3f getDeltaNorm() {
|
||||
return this.deltaNorm;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3f getWorldLocation() {
|
||||
return this.worldLocation;
|
||||
}
|
||||
|
||||
public UUID getScaleCallback() {
|
||||
return this.scaleCallback;
|
||||
}
|
||||
|
||||
public float getBoneLength() {
|
||||
return this.boneLength;
|
||||
}
|
||||
|
||||
public float getModelScale() {
|
||||
return this.modelScale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBounded(boolean bounded) {
|
||||
this.bounded = bounded;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMinX(float minX) {
|
||||
this.minX = minX;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMaxX(float maxX) {
|
||||
this.maxX = maxX;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMinY(float minY) {
|
||||
this.minY = minY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMaxY(float maxY) {
|
||||
this.maxY = maxY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMinZ(float minZ) {
|
||||
this.minZ = minZ;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMaxZ(float maxZ) {
|
||||
this.maxZ = maxZ;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAlignRate(float alignRate) {
|
||||
this.alignRate = alignRate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setElasticity(float elasticity) {
|
||||
this.elasticity = elasticity;
|
||||
}
|
||||
|
||||
public void setScaleCallback(UUID scaleCallback) {
|
||||
this.scaleCallback = scaleCallback;
|
||||
}
|
||||
|
||||
public void setBoneLength(float boneLength) {
|
||||
this.boneLength = boneLength;
|
||||
}
|
||||
|
||||
public void setModelScale(float modelScale) {
|
||||
this.modelScale = modelScale;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.ticxo.modelengine.core.model.bone.behavior;
|
||||
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
|
||||
public class Dummy extends AbstractBoneBehavior<Dummy> {
|
||||
public Dummy(ModelBone bone, BoneBehaviorType<Dummy> type, BoneBehaviorData data) {
|
||||
super(bone, type, data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.ticxo.modelengine.core.model.bone.behavior;
|
||||
|
||||
import com.ticxo.modelengine.api.model.bone.BoneItems;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.model.bone.type.Ghost;
|
||||
|
||||
public class GhostImpl extends AbstractBoneBehavior<GhostImpl> implements Ghost {
|
||||
public GhostImpl(ModelBone bone, BoneBehaviorType<GhostImpl> type, BoneBehaviorData data) {
|
||||
super(bone, type, data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onApply() {
|
||||
this.bone.setRenderer(true);
|
||||
this.bone.clearModel();
|
||||
}
|
||||
|
||||
@Override
|
||||
public BoneItems getModel() {
|
||||
return this.bone.getModels();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.ticxo.modelengine.core.model.bone.behavior;
|
||||
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import java.util.Optional;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.joml.Quaternionf;
|
||||
|
||||
public class HeadForcedImpl extends HeadImpl {
|
||||
protected boolean inherited;
|
||||
|
||||
public HeadForcedImpl(ModelBone bone, BoneBehaviorType<HeadImpl> type, BoneBehaviorData data) {
|
||||
super(bone, type, data);
|
||||
this.onParentSwap(bone.getParent());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onParentSwap(@Nullable ModelBone parent) {
|
||||
this.shouldRotate = false;
|
||||
if (parent != null) {
|
||||
Optional<HeadImpl> maybeBehavior = parent.getBoneBehavior(this.type);
|
||||
maybeBehavior.ifPresent(head -> {
|
||||
this.inherited = head.inherited;
|
||||
if (!this.inherited && !(head instanceof HeadForcedImpl)) {
|
||||
this.shouldRotate = true;
|
||||
this.local = head.isLocal();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void preGlobalRotate() {
|
||||
if (this.shouldRotate && !this.local) {
|
||||
this.rotate();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postGlobalRotate() {
|
||||
if (this.shouldRotate && this.local) {
|
||||
this.rotate();
|
||||
}
|
||||
}
|
||||
|
||||
private void rotate() {
|
||||
ActiveModel activeModel = this.bone.getActiveModel();
|
||||
float yaw = -TMath.degreeDifference(activeModel.getYBodyRot(), activeModel.getYHeadRot());
|
||||
float pitch = -activeModel.getXHeadRot();
|
||||
Quaternionf q = new Quaternionf().rotateX(pitch * (float) (Math.PI / 180.0)).rotateY(-yaw * (float) (Math.PI / 180.0));
|
||||
this.bone.getTransformMatrix().rotate(q);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHidden() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInherited() {
|
||||
return this.inherited;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setInherited(boolean inherited) {
|
||||
this.inherited = inherited;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.ticxo.modelengine.core.model.bone.behavior;
|
||||
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.model.bone.type.Head;
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import java.util.Optional;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class HeadImpl extends AbstractBoneBehavior<HeadImpl> implements Head {
|
||||
protected boolean shouldRotate;
|
||||
protected boolean inherited;
|
||||
protected boolean local;
|
||||
private final Vector3f pivot = new Vector3f();
|
||||
|
||||
public HeadImpl(ModelBone bone, BoneBehaviorType<HeadImpl> type, BoneBehaviorData data) {
|
||||
super(bone, type, data);
|
||||
this.onParentSwap(bone.getParent());
|
||||
this.local = data.get("local", false);
|
||||
this.inherited = data.get("inherited", false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onParentSwap(@Nullable ModelBone parent) {
|
||||
this.shouldRotate = true;
|
||||
|
||||
while (parent != null) {
|
||||
Optional<HeadImpl> maybeBehavior = parent.getBoneBehavior(this.type);
|
||||
this.shouldRotate = maybeBehavior.isEmpty() || maybeBehavior.get() instanceof HeadForcedImpl;
|
||||
if (!this.shouldRotate) {
|
||||
return;
|
||||
}
|
||||
|
||||
parent = parent.getParent();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postGlobalTranslate() {
|
||||
this.bone.getTransformMatrix().getTranslation(this.pivot);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postTransformDecompose() {
|
||||
if (this.shouldRotate && !this.local) {
|
||||
Quaternionf rotation = this.getRotation();
|
||||
this.bone.getGlobalTransform().mutatePosition(vector3f -> vector3f.sub(this.pivot).rotate(rotation).add(this.pivot));
|
||||
this.bone.getGlobalTransform().mutateLeftQuaternion(quaternionf -> quaternionf.premul(rotation));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postGlobalRotate() {
|
||||
if (this.shouldRotate && this.local) {
|
||||
this.bone.getTransformMatrix().rotate(this.getRotation());
|
||||
}
|
||||
}
|
||||
|
||||
private Quaternionf getRotation() {
|
||||
ActiveModel activeModel = this.bone.getActiveModel();
|
||||
float yaw = TMath.degreeDifference(activeModel.getYBodyRot(), activeModel.getYHeadRot());
|
||||
float pitch = activeModel.getXHeadRot();
|
||||
return new Quaternionf().rotateY(-yaw * (float) (Math.PI / 180.0)).rotateX(pitch * (float) (Math.PI / 180.0));
|
||||
}
|
||||
|
||||
public boolean isInherited() {
|
||||
return this.inherited;
|
||||
}
|
||||
|
||||
public void setInherited(boolean inherited) {
|
||||
this.inherited = inherited;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLocal() {
|
||||
return this.local;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLocal(boolean local) {
|
||||
this.local = local;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.ticxo.modelengine.core.model.bone.behavior;
|
||||
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.model.bone.type.HeldItem;
|
||||
import com.ticxo.modelengine.api.model.render.DisplayRenderer;
|
||||
import com.ticxo.modelengine.api.utils.data.io.SavedData;
|
||||
import java.util.function.Supplier;
|
||||
import org.bukkit.entity.ItemDisplay.ItemDisplayTransform;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class HeldItemImpl extends AbstractBoneBehavior<HeldItemImpl> implements HeldItem {
|
||||
private final Vector3f location = new Vector3f();
|
||||
private final Quaternionf rotation = new Quaternionf();
|
||||
private ItemDisplayTransform display;
|
||||
private HeldItem.ItemStackSupplier itemProvider;
|
||||
|
||||
public HeldItemImpl(ModelBone bone, BoneBehaviorType<HeldItemImpl> type, BoneBehaviorData data) {
|
||||
super(bone, type, data);
|
||||
this.display = data.get("display");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onApply() {
|
||||
if (this.bone.getActiveModel().getModelRenderer() instanceof DisplayRenderer) {
|
||||
this.bone.setRenderer(true);
|
||||
this.bone.setModel(EMPTY);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFinalize() {
|
||||
float yaw = -this.bone.getYaw() * (float) (Math.PI / 180.0);
|
||||
this.bone.getGlobalTransform().mutatePosition(pos -> pos.rotateY(yaw, this.location));
|
||||
this.bone.getGlobalTransform().mutateLeftQuaternion(q -> q.premul(this.rotation.rotationZYX(0.0F, yaw, 0.0F), this.rotation));
|
||||
if (this.itemProvider == null) {
|
||||
this.bone.setModel(EMPTY);
|
||||
} else {
|
||||
this.bone.setModel(this.itemProvider.supply());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(SavedData data) {
|
||||
if (this.itemProvider != null) {
|
||||
this.itemProvider.save().ifPresent(data1 -> data.putData("supplier", data1));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(SavedData data) {
|
||||
data.getData("supplier").ifPresent(data1 -> {
|
||||
String var2 = data1.getString("type", "");
|
||||
|
||||
this.itemProvider = (HeldItem.ItemStackSupplier)(switch (var2) {
|
||||
case "static" -> new HeldItem.StaticItemStackSupplier();
|
||||
case "equipment" -> new HeldItem.EquipmentSupplier();
|
||||
default -> null;
|
||||
});
|
||||
if (this.itemProvider != null) {
|
||||
this.itemProvider.load(data1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearItemProvider() {
|
||||
this.itemProvider = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setItemProvider(Supplier<ItemStack> stackSupplier) {
|
||||
this.setItemProvider(new HeldItem.TemporaryItemStackSupplier(stackSupplier));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setItemProvider(HeldItem.ItemStackSupplier stackSupplier) {
|
||||
this.itemProvider = stackSupplier;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItem() {
|
||||
return this.bone.getModel();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3f getLocation() {
|
||||
return this.location;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Quaternionf getRotation() {
|
||||
return this.rotation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemDisplayTransform getDisplay() {
|
||||
return this.display;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDisplay(ItemDisplayTransform display) {
|
||||
this.display = display;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HeldItem.ItemStackSupplier getItemProvider() {
|
||||
return this.itemProvider;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.ticxo.modelengine.core.model.bone.behavior;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.LeashManager;
|
||||
import com.ticxo.modelengine.api.model.bone.type.Leash;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class LeashImpl extends AbstractBoneBehavior<LeashImpl> implements Leash {
|
||||
private final boolean mainLeash;
|
||||
private final int id;
|
||||
private final Vector3f location = new Vector3f();
|
||||
private Entity connectedEntity;
|
||||
private Leash connectedLeash;
|
||||
|
||||
public LeashImpl(ModelBone bone, BoneBehaviorType<LeashImpl> type, BoneBehaviorData data) {
|
||||
super(bone, type, data);
|
||||
this.mainLeash = data.get("main", false);
|
||||
this.id = ModelEngineAPI.getEntityHandler().getNextEntityId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onApply() {
|
||||
this.bone.getActiveModel().getLeashManager().ifPresent(leashManager -> ((LeashManager)leashManager).registerLeash(this));
|
||||
Location baseLocation = this.bone.calculatePivotLocation();
|
||||
this.bone
|
||||
.getBlueprintBone()
|
||||
.getLocalPosition()
|
||||
.rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0), this.location)
|
||||
.add((float)baseLocation.getX(), (float)baseLocation.getY(), (float)baseLocation.getZ());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFinalize() {
|
||||
Location baseLocation = this.bone.calculatePivotLocation();
|
||||
this.bone
|
||||
.getGlobalTransform()
|
||||
.mutatePosition(
|
||||
vector3f -> vector3f.rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0), this.location)
|
||||
.add((float)baseLocation.getX(), (float)baseLocation.getY(), (float)baseLocation.getZ())
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connect(Entity entity) {
|
||||
this.connectedEntity = entity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Leash & BoneBehavior> void connect(T leash) {
|
||||
if (leash != this) {
|
||||
this.connectedLeash = leash;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnect() {
|
||||
this.connectedEntity = null;
|
||||
this.connectedLeash = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Leash & BoneBehavior> T getConnectedLeash() {
|
||||
return (T)this.connectedLeash;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isMainLeash() {
|
||||
return this.mainLeash;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3f getLocation() {
|
||||
return this.location;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Entity getConnectedEntity() {
|
||||
return this.connectedEntity;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.ticxo.modelengine.core.model.bone.behavior;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Sets;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.ServerInfo;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.MountManager;
|
||||
import com.ticxo.modelengine.api.model.bone.type.Mount;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class MountImpl extends AbstractBoneBehavior<MountImpl> implements Mount {
|
||||
private final boolean driver;
|
||||
private final Vector3f location = new Vector3f();
|
||||
private final Vector3f globalLocation = new Vector3f();
|
||||
private final Set<Entity> passengers = Sets.newConcurrentHashSet();
|
||||
private final Map<Entity, Integer> entityIdCache = new ConcurrentHashMap<>();
|
||||
|
||||
public MountImpl(ModelBone bone, BoneBehaviorType<MountImpl> type, BoneBehaviorData data) {
|
||||
super(bone, type, data);
|
||||
this.driver = data.get("driver", false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onApply() {
|
||||
this.bone.getActiveModel().getMountManager().ifPresent(mountManager -> {
|
||||
if (this.driver) {
|
||||
((MountManager)mountManager).setDriverBone(this);
|
||||
} else {
|
||||
((MountManager)mountManager).registerSeat(this);
|
||||
}
|
||||
});
|
||||
this.bone.getBlueprintBone().getLocalPosition().rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0), this.location);
|
||||
Location baseLocation = this.bone.calculatePivotLocation();
|
||||
this.globalLocation.set(this.location).add((float)baseLocation.getX(), (float)baseLocation.getY(), (float)baseLocation.getZ());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFinalize() {
|
||||
this.bone.getGlobalTransform().mutatePosition(pos -> pos.rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0), this.location));
|
||||
Location baseLocation = this.bone.calculatePivotLocation();
|
||||
this.globalLocation.set(this.location).add((float)baseLocation.getX(), (float)baseLocation.getY(), (float)baseLocation.getZ());
|
||||
this.passengers.removeIf(entity -> ModelEngineAPI.getEntityHandler().isRemoved(entity));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addPassenger(Entity entity) {
|
||||
if (this.canMountMore()) {
|
||||
this.passengers.add(entity);
|
||||
if (ServerInfo.IS_FOLIA) {
|
||||
this.entityIdCache.put(entity, entity.getEntityId());
|
||||
}
|
||||
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addPassengers(Collection<Entity> entities) {
|
||||
for (Entity entity : entities) {
|
||||
if (!this.canMountMore()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.passengers.add(entity);
|
||||
if (ServerInfo.IS_FOLIA) {
|
||||
this.entityIdCache.put(entity, entity.getEntityId());
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removePassenger(Entity entity) {
|
||||
this.passengers.remove(entity);
|
||||
if (ServerInfo.IS_FOLIA) {
|
||||
this.entityIdCache.remove(entity);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removePassengers(Collection<Entity> entities) {
|
||||
this.passengers.removeAll(entities);
|
||||
if (ServerInfo.IS_FOLIA) {
|
||||
entities.forEach(this.entityIdCache::remove);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Entity> clearPassengers() {
|
||||
HashSet<Entity> set = new HashSet<>(this.passengers);
|
||||
this.passengers.clear();
|
||||
if (ServerInfo.IS_FOLIA) {
|
||||
this.entityIdCache.clear();
|
||||
}
|
||||
|
||||
return set;
|
||||
}
|
||||
|
||||
public Collection<Integer> getPassengerEntityIds() {
|
||||
return Collections.unmodifiableCollection(this.entityIdCache.values());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Entity> getPassengers() {
|
||||
return ImmutableSet.copyOf(this.passengers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canMountMore() {
|
||||
return !this.isDriver() || this.passengers.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDriver() {
|
||||
return this.driver;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3f getLocation() {
|
||||
return this.location;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3f getGlobalLocation() {
|
||||
return this.globalLocation;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package com.ticxo.modelengine.core.model.bone.behavior;
|
||||
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.model.bone.type.NameTag;
|
||||
import java.util.function.Supplier;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Display.Billboard;
|
||||
import org.bukkit.entity.TextDisplay.TextAlignment;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class NameTagImpl extends AbstractBoneBehavior<NameTagImpl> implements NameTag {
|
||||
private static final String EMPTY_STRING = "{\"text\":\"\"}";
|
||||
private final Vector3f location = new Vector3f();
|
||||
private String jsonString = "{\"text\":\"\"}";
|
||||
private Supplier<String> jsonStringSupplier;
|
||||
private boolean visible;
|
||||
private int backgroundColor = 1073741824;
|
||||
private boolean useDefaultBackgroundColor = true;
|
||||
private TextAlignment alignment = TextAlignment.CENTER;
|
||||
private int lineWidth = 200;
|
||||
private byte textOpacity = -1;
|
||||
private boolean shadow = false;
|
||||
private boolean seeThrough = true;
|
||||
private Billboard billboard = Billboard.CENTER;
|
||||
private Vector3f scale = new Vector3f(1.0F);
|
||||
private Vector3f position = new Vector3f(0.0F);
|
||||
|
||||
public NameTagImpl(ModelBone bone, BoneBehaviorType<NameTagImpl> type, BoneBehaviorData data) {
|
||||
super(bone, type, data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onApply() {
|
||||
Location baseLocation = this.bone.calculatePivotLocation();
|
||||
this.bone
|
||||
.getBlueprintBone()
|
||||
.getLocalPosition()
|
||||
.rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0), this.location)
|
||||
.add((float)baseLocation.getX(), (float)baseLocation.getY(), (float)baseLocation.getZ());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFinalize() {
|
||||
if (this.jsonStringSupplier != null) {
|
||||
this.setJsonString(this.jsonStringSupplier.get());
|
||||
}
|
||||
|
||||
Location baseLocation = this.bone.calculatePivotLocation();
|
||||
this.bone
|
||||
.getGlobalTransform()
|
||||
.mutatePosition(
|
||||
vector3f -> vector3f.rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0), this.location)
|
||||
.add((float)baseLocation.getX(), (float)baseLocation.getY(), (float)baseLocation.getZ())
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setString(String name) {
|
||||
this.setComponent(Component.text(name));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setComponent(Component component) {
|
||||
this.setJsonString((String)GsonComponentSerializer.gson().serialize(component));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setJsonString(String json) {
|
||||
this.jsonString = json != null ? json : "{\"text\":\"\"}";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setComponentSupplier(@Nullable Supplier<Component> component) {
|
||||
this.jsonStringSupplier = component == null ? null : () -> (String)GsonComponentSerializer.gson().serialize(component.get());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setUseDefaultBackgroundColor(boolean bool) {
|
||||
this.useDefaultBackgroundColor = bool;
|
||||
if (bool) {
|
||||
this.backgroundColor = 1073741824;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3f getLocation() {
|
||||
return this.location;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getJsonString() {
|
||||
return this.jsonString;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Supplier<String> getJsonStringSupplier() {
|
||||
return this.jsonStringSupplier;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setJsonStringSupplier(Supplier<String> jsonStringSupplier) {
|
||||
this.jsonStringSupplier = jsonStringSupplier;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVisible() {
|
||||
return this.visible;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVisible(boolean visible) {
|
||||
this.visible = visible;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getBackgroundColor() {
|
||||
return this.backgroundColor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBackgroundColor(int backgroundColor) {
|
||||
this.backgroundColor = backgroundColor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUseDefaultBackgroundColor() {
|
||||
return this.useDefaultBackgroundColor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TextAlignment getAlignment() {
|
||||
return this.alignment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAlignment(TextAlignment alignment) {
|
||||
this.alignment = alignment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getLineWidth() {
|
||||
return this.lineWidth;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLineWidth(int lineWidth) {
|
||||
this.lineWidth = lineWidth;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte getTextOpacity() {
|
||||
return this.textOpacity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTextOpacity(byte textOpacity) {
|
||||
this.textOpacity = textOpacity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isShadow() {
|
||||
return this.shadow;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setShadow(boolean shadow) {
|
||||
this.shadow = shadow;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSeeThrough() {
|
||||
return this.seeThrough;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSeeThrough(boolean seeThrough) {
|
||||
this.seeThrough = seeThrough;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Billboard getBillboard() {
|
||||
return this.billboard;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBillboard(Billboard billboard) {
|
||||
this.billboard = billboard;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3f getScale() {
|
||||
return this.scale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setScale(Vector3f scale) {
|
||||
this.scale = scale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3f getPosition() {
|
||||
return this.position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPosition(Vector3f position) {
|
||||
this.position = position;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.ticxo.modelengine.core.model.bone.behavior;
|
||||
|
||||
import com.destroystokyo.paper.profile.PlayerProfile;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.events.BoneTransformReadEvent;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.model.bone.type.PlayerLimb;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.inventory.meta.SkullMeta;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class PlayerLimbImpl extends AbstractBoneBehavior<PlayerLimbImpl> implements PlayerLimb {
|
||||
private final PlayerLimb.Limb limbType;
|
||||
private boolean isSlim;
|
||||
|
||||
public PlayerLimbImpl(ModelBone bone, BoneBehaviorType<PlayerLimbImpl> type, BoneBehaviorData data) {
|
||||
super(bone, type, data);
|
||||
this.limbType = data.get("limb");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onApply() {
|
||||
this.bone.setRenderer(true);
|
||||
this.bone.setModel(new ItemStack(Material.AIR));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void modifyTransform(BoneTransformReadEvent event) {
|
||||
event.getPosition().add(0.0F, this.isSlim ? this.limbType.slimYOffset : this.limbType.defaultYOffset, 0.0F);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTexture(@Nullable Player player) {
|
||||
if (player == null) {
|
||||
this.bone.setModel(new ItemStack(Material.AIR));
|
||||
} else {
|
||||
this.setTexture(player.getPlayerProfile());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTexture(@Nullable PlayerProfile profile) {
|
||||
if (profile == null) {
|
||||
this.bone.setModel(new ItemStack(Material.AIR));
|
||||
} else {
|
||||
ItemStack playerHead = new ItemStack(Material.PLAYER_HEAD);
|
||||
ItemMeta meta = playerHead.getItemMeta();
|
||||
((SkullMeta)meta).setPlayerProfile(profile);
|
||||
|
||||
meta.setCustomModelData(switch (profile.getTextures().getSkinModel()) {
|
||||
case CLASSIC -> {
|
||||
this.isSlim = false;
|
||||
yield this.limbType.defaultId;
|
||||
}
|
||||
case SLIM -> {
|
||||
this.isSlim = true;
|
||||
yield this.limbType.slimId;
|
||||
}
|
||||
default -> throw new IncompatibleClassChangeError();
|
||||
});
|
||||
playerHead.setItemMeta(meta);
|
||||
ModelEngineAPI.getNMSHandler().applyPlayerHeadItemModel(playerHead);
|
||||
this.bone.setModel(playerHead);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerLimb.Limb getLimbType() {
|
||||
return this.limbType;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.ticxo.modelengine.core.model.bone.behavior;
|
||||
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.utils.math.SafeTransform;
|
||||
import org.bukkit.Location;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class SegmentImpl extends AbstractSegmentImpl<SegmentImpl> {
|
||||
public SegmentImpl(ModelBone bone, BoneBehaviorType<SegmentImpl> type, BoneBehaviorData data) {
|
||||
super(bone, type, data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onApply() {
|
||||
super.onApply();
|
||||
if (this.backPivot) {
|
||||
this.resetPivot();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onModelInitialized() {
|
||||
super.onModelInitialized();
|
||||
if (!this.backPivot) {
|
||||
this.resetPivot();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postGlobalCalculation() {
|
||||
super.postGlobalCalculation();
|
||||
this.resetPivot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postTransformDecompose() {
|
||||
SafeTransform global = this.bone.getGlobalTransform();
|
||||
this.bone.getTransformMatrix().identity().rotate(global.getLeftQuaternion()).scale(global.getScale()).rotate(global.getRightQuaternion());
|
||||
global.mutatePosition(Vector3f::zero);
|
||||
}
|
||||
|
||||
private void resetPivot() {
|
||||
this.bone.setPivotLocation(this.toLocation(this.worldLocation));
|
||||
}
|
||||
|
||||
private Location toLocation(Vector3f vec) {
|
||||
return this.bone.getBaseLocation().clone().set(vec.x, vec.y, vec.z);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package com.ticxo.modelengine.core.model.bone.behavior;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.entity.Hitbox;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.model.bone.type.SubHitbox;
|
||||
import com.ticxo.modelengine.api.nms.entity.HitboxEntity;
|
||||
import com.ticxo.modelengine.api.utils.config.DebugToggle;
|
||||
import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox;
|
||||
import com.ticxo.modelengine.api.utils.math.SafeTransform;
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import com.ticxo.modelengine.api.utils.ticker.DualTicker;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class SubHitboxImpl extends AbstractBoneBehavior<SubHitboxImpl> implements SubHitbox {
|
||||
private final boolean isOBB;
|
||||
private final Vector3f fixedDimension = new Vector3f();
|
||||
private final Vector3f origin = new Vector3f();
|
||||
private final Vector3f cubeRotation = new Vector3f();
|
||||
private final Vector3f cubeOrigin = new Vector3f();
|
||||
private final Vector3f scaledOrigin = new Vector3f();
|
||||
private final int hitboxId;
|
||||
private final Vector3f dimension = new Vector3f();
|
||||
private final Vector3f location = new Vector3f();
|
||||
private final Quaternionf rotation = new Quaternionf();
|
||||
private final Map<UUID, Entity> boundEntities = Maps.newConcurrentMap();
|
||||
private float yaw;
|
||||
private HitboxEntity hitboxEntity;
|
||||
private float damageMultiplier = 1.0F;
|
||||
private boolean canBeHitByProjectile = true;
|
||||
|
||||
public SubHitboxImpl(ModelBone bone, BoneBehaviorType<SubHitboxImpl> type, BoneBehaviorData data) {
|
||||
super(bone, type, data);
|
||||
Hitbox hitbox = data.get("dimension");
|
||||
if (hitbox == null) {
|
||||
throw new RuntimeException("Unable to retrieve sub-hitbox dimension of bone " + bone.getUniqueBoneId());
|
||||
} else {
|
||||
this.hitboxId = ModelEngineAPI.getEntityHandler().getNextEntityId();
|
||||
this.isOBB = data.get("obb", false);
|
||||
Vector3f bonePosition = bone.getBlueprintBone().getGlobalPosition();
|
||||
this.origin.set(data.get("origin", bonePosition)).sub(bonePosition);
|
||||
this.cubeRotation.set(data.get("rotation", this.cubeRotation));
|
||||
this.cubeOrigin.set(data.get("cube_origin", bonePosition)).sub(bonePosition);
|
||||
this.origin.sub(this.cubeOrigin).rotateX(this.cubeRotation.x).rotateY(this.cubeRotation.y).rotateZ(this.cubeRotation.z).add(this.cubeOrigin);
|
||||
if (this.isOBB) {
|
||||
this.fixedDimension.set(hitbox.getWidth(), hitbox.getHeight(), hitbox.getDepth());
|
||||
} else {
|
||||
this.fixedDimension.set(hitbox.getMaxWidth(), hitbox.getHeight(), hitbox.getMaxWidth());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onApply() {
|
||||
Location baseLocation = this.bone.calculatePivotLocation();
|
||||
this.removeOld();
|
||||
this.hitboxEntity = ModelEngineAPI.getEntityHandler().createHitbox(baseLocation, this.bone, this);
|
||||
this.bone
|
||||
.getBlueprintBone()
|
||||
.getLocalPosition()
|
||||
.rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0), this.location)
|
||||
.add((float)baseLocation.getX(), (float)baseLocation.getY(), (float)baseLocation.getZ());
|
||||
ModelEngineAPI.getInteractionTracker().setEntityRelay(this.hitboxId, this.hitboxEntity.getEntityId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onRemove() {
|
||||
ModelEngineAPI.getInteractionTracker().removeEntityRelay(this.hitboxId);
|
||||
this.removeOld();
|
||||
DualTicker.queueSyncTask(() -> this.boundEntities.forEach((uuid, entity) -> entity.remove()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postAnimation() {
|
||||
Vector3f localScale = this.bone.getLocalTransform().getScale();
|
||||
this.scaledOrigin.set(this.origin).mul(localScale);
|
||||
this.bone.getLocalTransform().mutatePosition(vector3f -> vector3f.add(this.scaledOrigin));
|
||||
this.bone.getLocalTransform().mutateLeftQuaternion(quaternionf -> quaternionf.mul(TMath.toQuaternion(this.cubeRotation)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFinalize() {
|
||||
SafeTransform transform = this.bone.getGlobalTransform();
|
||||
this.location.set(transform.getPosition()).rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0));
|
||||
this.rotation.set(transform.getLeftQuaternion()).mul(transform.getRightQuaternion()).rotateLocalY(-this.bone.getYaw() * (float) (Math.PI / 180.0));
|
||||
transform.getScale().mul(this.fixedDimension, this.dimension);
|
||||
this.dimension.mul(this.bone.getBlueprintBone().getScale()).mul(this.bone.getActiveModel().getScale());
|
||||
Location baseLocation = this.bone.calculatePivotLocation();
|
||||
this.location.add((float)baseLocation.getX(), (float)baseLocation.getY(), (float)baseLocation.getZ());
|
||||
if (!this.isOBB) {
|
||||
this.location.sub(0.0F, this.dimension.y * 0.5F, 0.0F);
|
||||
}
|
||||
|
||||
if (this.hitboxEntity != null && !this.hitboxEntity.isValid()) {
|
||||
this.hitboxEntity = null;
|
||||
}
|
||||
|
||||
if (this.hitboxEntity == null) {
|
||||
this.hitboxEntity = ModelEngineAPI.getEntityHandler().createHitbox(baseLocation, this.bone, this);
|
||||
if (this.hitboxEntity == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
ModelEngineAPI.getInteractionTracker().setEntityRelay(this.hitboxId, this.hitboxEntity.getEntityId());
|
||||
}
|
||||
|
||||
this.hitboxEntity.queueLocation(new Vector3f(this.location));
|
||||
if (DebugToggle.isDebugging(DebugToggle.SHOW_OBB) && this.isOBB) {
|
||||
OrientedBoundingBox obb = this.hitboxEntity.getOrientedBoundingBox();
|
||||
if (obb != null) {
|
||||
obb.visualize(baseLocation.getWorld());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addBoundEntity(Entity entity) {
|
||||
this.getBoundEntities().put(entity.getUniqueId(), entity);
|
||||
ModelEngineAPI.getEntityHandler().forceDespawn(entity);
|
||||
ModelEngineAPI.setRenderCanceled(entity.getEntityId(), true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeBoundEntity(Entity entity) {
|
||||
this.getBoundEntities().remove(entity.getUniqueId(), entity);
|
||||
ModelEngineAPI.setRenderCanceled(entity.getEntityId(), false);
|
||||
ModelEngineAPI.getEntityHandler().forceSpawn(entity);
|
||||
}
|
||||
|
||||
private void removeOld() {
|
||||
if (this.hitboxEntity != null) {
|
||||
this.hitboxEntity.markRemoved();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOBB() {
|
||||
return this.isOBB;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3f getFixedDimension() {
|
||||
return this.fixedDimension;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3f getOrigin() {
|
||||
return this.origin;
|
||||
}
|
||||
|
||||
public Vector3f getCubeRotation() {
|
||||
return this.cubeRotation;
|
||||
}
|
||||
|
||||
public Vector3f getCubeOrigin() {
|
||||
return this.cubeOrigin;
|
||||
}
|
||||
|
||||
public Vector3f getScaledOrigin() {
|
||||
return this.scaledOrigin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHitboxId() {
|
||||
return this.hitboxId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3f getDimension() {
|
||||
return this.dimension;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3f getLocation() {
|
||||
return this.location;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Quaternionf getRotation() {
|
||||
return this.rotation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<UUID, Entity> getBoundEntities() {
|
||||
return this.boundEntities;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getYaw() {
|
||||
return this.yaw;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HitboxEntity getHitboxEntity() {
|
||||
return this.hitboxEntity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getDamageMultiplier() {
|
||||
return this.damageMultiplier;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCanBeHitByProjectile() {
|
||||
return this.canBeHitByProjectile;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDamageMultiplier(float damageMultiplier) {
|
||||
this.damageMultiplier = damageMultiplier;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCanBeHitByProjectile(boolean canBeHitByProjectile) {
|
||||
this.canBeHitByProjectile = canBeHitByProjectile;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.ticxo.modelengine.core.model.bone.behavior;
|
||||
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
|
||||
public class TailImpl extends AbstractSegmentImpl<TailImpl> {
|
||||
public TailImpl(ModelBone bone, BoneBehaviorType<TailImpl> type, BoneBehaviorData data) {
|
||||
super(bone, type, data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package com.ticxo.modelengine.core.model.bone.behavior;
|
||||
|
||||
import com.destroystokyo.paper.profile.PlayerProfile;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.generator.skin.LimbData;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.model.bone.type.UserLimb;
|
||||
import com.ticxo.modelengine.api.utils.MojangAPI;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.DataTracker;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.SkullMeta;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Quaternionf;
|
||||
|
||||
public class UserLimbImpl extends AbstractBoneBehavior<UserLimbImpl> implements UserLimb {
|
||||
private final String limbType;
|
||||
private final DataTracker<ItemStack> generatedStack = new DataTracker<>(this.createHead(), ItemStack::isSimilar);
|
||||
private LimbData limbData;
|
||||
private boolean slim;
|
||||
private final Matrix4f originalTransform = new Matrix4f();
|
||||
private boolean generating;
|
||||
private volatile int generation;
|
||||
private String placeholder;
|
||||
|
||||
public UserLimbImpl(ModelBone bone, BoneBehaviorType<UserLimbImpl> type, BoneBehaviorData data) {
|
||||
super(bone, type, data);
|
||||
this.limbType = data.get("type");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onApply() {
|
||||
this.bone.setRenderer(true);
|
||||
this.bone.setModel(this.generatedStack.get());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void preTransformDecompose() {
|
||||
if (this.limbData != null) {
|
||||
this.originalTransform.set(this.bone.getTransformMatrix());
|
||||
this.bone.getTransformMatrix().translate(this.limbData.translation()).rotate(new Quaternionf().rotateY((float) Math.PI)).scale(this.limbData.scale());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postTransformRecompose() {
|
||||
this.bone.getTransformMatrix().set(this.originalTransform);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFinalize() {
|
||||
this.generatedStack.ifDirty(this.bone::setModel);
|
||||
this.generatedStack.clearDirty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTexture(@Nullable Player player) {
|
||||
if (player == null) {
|
||||
this.generatedStack.set(this.createHead());
|
||||
} else {
|
||||
this.setTexture(player.getPlayerProfile());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLimbType() {
|
||||
return this.limbType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setStaticSkin(boolean slim, @Nullable String url) {
|
||||
this.generation++;
|
||||
this.slim = slim;
|
||||
this.limbData = ModelEngineAPI.getAPI().getSkinSplitter().getLimb(this.limbType, slim);
|
||||
if (url != null && this.limbData != null) {
|
||||
this.generatedStack.set(this.limbData.createItem(url));
|
||||
} else {
|
||||
this.generatedStack.set(this.createHead());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTexture(@Nullable PlayerProfile profile) {
|
||||
int gen = ++this.generation;
|
||||
this.generatedStack.set(this.createHead());
|
||||
if (profile != null) {
|
||||
switch (profile.getTextures().getSkinModel()) {
|
||||
case CLASSIC:
|
||||
this.slim = false;
|
||||
break;
|
||||
case SLIM:
|
||||
this.slim = true;
|
||||
}
|
||||
|
||||
this.limbData = ModelEngineAPI.getAPI().getSkinSplitter().getLimb(this.limbType, this.slim);
|
||||
if (this.limbData.isHead()) {
|
||||
ItemStack head = this.createHead();
|
||||
head.editMeta(itemMeta -> ((SkullMeta)itemMeta).setPlayerProfile(profile));
|
||||
this.generatedStack.set(head);
|
||||
} else {
|
||||
this.generating = true;
|
||||
ModelEngineAPI.getUserLimbRegistry()
|
||||
.getSkinUrlFromKey(this.getPlaceholder(), this.limbType, this.slim)
|
||||
.thenApply(url -> this.limbData.createItem(url))
|
||||
.handle((stack, throwable) -> {
|
||||
if (throwable != null) {
|
||||
throwable.printStackTrace();
|
||||
return null;
|
||||
} else {
|
||||
if (this.generating && gen == this.generation) {
|
||||
this.generatedStack.set(stack);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
});
|
||||
MojangAPI.getRawSkinData(profile)
|
||||
.thenCompose(base64 -> ModelEngineAPI.getUserLimbRegistry().getSkinUrlFromSource(base64, this.limbType, this.slim))
|
||||
.thenApply(url -> this.limbData.createItem(url))
|
||||
.handle((stack, throwable) -> {
|
||||
if (throwable != null) {
|
||||
throwable.printStackTrace();
|
||||
return null;
|
||||
} else if (gen != this.generation) {
|
||||
return null;
|
||||
} else {
|
||||
this.generatedStack.set(stack);
|
||||
this.generating = false;
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlaceholder() {
|
||||
return this.placeholder != null
|
||||
? this.placeholder
|
||||
: (this.slim ? ModelEngineAPI.getConfigCache().getSlim() : ModelEngineAPI.getConfigCache().getClassic());
|
||||
}
|
||||
|
||||
private ItemStack createHead() {
|
||||
return new ItemStack(Material.PLAYER_HEAD);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPlaceholder(String placeholder) {
|
||||
this.placeholder = placeholder;
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.ticxo.modelengine.core.model.bone.manager;
|
||||
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.AbstractBehaviorManager;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.LeashManager;
|
||||
import com.ticxo.modelengine.api.model.bone.type.Leash;
|
||||
import com.ticxo.modelengine.core.model.bone.behavior.LeashImpl;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.bukkit.entity.Entity;
|
||||
|
||||
public class LeashManagerImpl extends AbstractBehaviorManager<LeashImpl> implements LeashManager {
|
||||
private final Map<String, ?> main = new LinkedHashMap<>();
|
||||
private final Map<String, ?> leashes = new LinkedHashMap<>();
|
||||
|
||||
public LeashManagerImpl(ActiveModel activeModel, BoneBehaviorType<LeashImpl> type) {
|
||||
super(activeModel, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Leash & BoneBehavior> void registerLeash(T leash) {
|
||||
this.<T>getLeashes().put(leash.getBone().getUniqueBoneId(), leash);
|
||||
if (leash.isMainLeash()) {
|
||||
this.<T>getMainLeashes().put(leash.getBone().getUniqueBoneId(), leash);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Leash & BoneBehavior> Map<String, T> getMainLeashes() {
|
||||
return (Map<String, T>)this.main;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Leash & BoneBehavior> Map<String, T> getLeashes() {
|
||||
return (Map<String, T>)this.leashes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Leash & BoneBehavior> Optional<T> getLeash(String boneId) {
|
||||
return Optional.ofNullable(this.<T>getLeashes().get(boneId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectMainLeashes(Entity leashHolder) {
|
||||
this.getMainLeashes().values().forEach(leash -> ((Leash)leash).connect(leashHolder));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectMainLeashes(String from) {
|
||||
this.getLeash(from).ifPresent(leash -> this.getMainLeashes().values().forEach(mainLeash -> ((Leash)mainLeash).connect(leash)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnectMainLeashes() {
|
||||
this.getMainLeashes().values().forEach(rec$ -> ((Leash)rec$).disconnect());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectLeash(Entity leashHolder, String to) {
|
||||
this.getLeash(to).ifPresent(leash -> ((Leash)leash).connect(leashHolder));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectLeash(String from, String to) {
|
||||
this.getLeash(to).ifPresent(toLeash -> this.getLeash(from).ifPresent(fromLeash -> ((Leash)toLeash).connect(fromLeash)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnect(String bone) {
|
||||
this.getLeash(bone).ifPresent(rec$ -> ((Leash)rec$).disconnect());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Entity getLeashHolder(String bone) {
|
||||
return this.getLeash(bone).map(rec$ -> ((Leash)rec$).getConnectedEntity()).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Leash & BoneBehavior> T getLeashConnection(String bone) {
|
||||
Optional<T> leash = this.getLeash(bone);
|
||||
return leash.isPresent() ? leash.get().getConnectedLeash() : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.ticxo.modelengine.core.model.bone.manager;
|
||||
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.MountData;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.MountManager;
|
||||
import com.ticxo.modelengine.api.model.bone.type.Mount;
|
||||
|
||||
public class MountDataImpl implements GlobalBehaviorData, MountData {
|
||||
private MountManager mainMountManager;
|
||||
|
||||
@Override
|
||||
public <T extends BehaviorManager<? extends Mount> & MountManager> T getMainMountManager() {
|
||||
return (T)this.mainMountManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends BehaviorManager<? extends Mount> & MountManager> void setMainMountManager(T manager) {
|
||||
this.mainMountManager = manager;
|
||||
}
|
||||
}
|
||||
+497
@@ -0,0 +1,497 @@
|
||||
package com.ticxo.modelengine.core.model.bone.manager;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.ServerInfo;
|
||||
import com.ticxo.modelengine.api.events.ModelDismountEvent;
|
||||
import com.ticxo.modelengine.api.events.ModelMountEvent;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.AbstractBehaviorManager;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.MountManager;
|
||||
import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer;
|
||||
import com.ticxo.modelengine.api.model.bone.type.Mount;
|
||||
import com.ticxo.modelengine.api.mount.controller.MountController;
|
||||
import com.ticxo.modelengine.api.mount.controller.MountControllerSupplier;
|
||||
import com.ticxo.modelengine.api.utils.data.io.SavedData;
|
||||
import com.ticxo.modelengine.core.model.bone.behavior.MountImpl;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class MountManagerImpl extends AbstractBehaviorManager<MountImpl> implements MountManager {
|
||||
private final Map<String, ?> seats = new LinkedHashMap<>();
|
||||
private final Map<Entity, Mount> passengerSeatMap = new HashMap<>();
|
||||
boolean canDrive;
|
||||
boolean canRide;
|
||||
private Entity driver;
|
||||
private Mount driverBone;
|
||||
|
||||
public MountManagerImpl(ActiveModel activeModel, BoneBehaviorType<MountImpl> supplier) {
|
||||
super(activeModel, supplier);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
this.dismountDriver();
|
||||
this.dismountAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(SavedData data) {
|
||||
this.canDrive = data.getBoolean("drive");
|
||||
this.canRide = data.getBoolean("ride");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(SavedData data) {
|
||||
data.putBoolean("drive", this.canDrive);
|
||||
data.putBoolean("ride", this.canRide);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canDrive() {
|
||||
return this.canDrive;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canRide() {
|
||||
return this.canRide;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isControlled() {
|
||||
return this.driver != null && this.driverBone != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPassengers() {
|
||||
return !this.passengerSeatMap.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasRiders() {
|
||||
return this.driver != null || !this.passengerSeatMap.isEmpty();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public <T extends Mount & BoneBehavior> T getDriverBone() {
|
||||
return (T)this.driverBone;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Mount & BoneBehavior> void setDriverBone(@Nullable T mount) {
|
||||
this.driverBone = mount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Mount & BoneBehavior> void registerSeat(T mount) {
|
||||
this.<T>getSeats().put(mount.getBone().getUniqueBoneId(), mount);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Mount & BoneBehavior> Map<String, T> getSeats() {
|
||||
return (Map<String, T>)this.seats;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Mount & BoneBehavior> Optional<T> getSeat(String boneId) {
|
||||
if (boneId == null) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
Map seats = this.getSeats();
|
||||
BoneBehavior seat = (BoneBehavior)seats.get(boneId);
|
||||
if (seat == null && boneId.startsWith("p_")) {
|
||||
seat = (BoneBehavior)seats.get(boneId.substring(2));
|
||||
}
|
||||
|
||||
return Optional.ofNullable((T)seat);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Mount & BoneBehavior> Optional<T> getMount(Entity entity) {
|
||||
if (entity == this.driver) {
|
||||
return Optional.ofNullable(this.getDriverBone());
|
||||
} else {
|
||||
Mount mount = this.passengerSeatMap.get(entity);
|
||||
return Optional.ofNullable((T)mount);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Entity, Mount> getPassengerSeatMap() {
|
||||
return ImmutableMap.copyOf(this.passengerSeatMap);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mountDriver(Entity entity, MountControllerSupplier supplier) {
|
||||
return this.mountDriver(entity, supplier, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mountDriver(Entity entity, MountControllerSupplier supplier, @Nullable Consumer<MountController> consumer) {
|
||||
if (this.driverBone != null && this.driverBone.getPassengers().isEmpty() && this.canDrive()) {
|
||||
ModelMountEvent event = new ModelMountEvent(this.activeModel, entity, true, this.driverBone);
|
||||
ModelEngineAPI.callEvent(event);
|
||||
if (event.isCancelled()) {
|
||||
return false;
|
||||
} else {
|
||||
boolean success = this.driverBone.addPassenger(entity);
|
||||
if (success) {
|
||||
this.driver = entity;
|
||||
this.registerMountPair(entity, this.driverBone, supplier, consumer);
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mountPassenger(String boneId, Entity entity, MountControllerSupplier supplier) {
|
||||
return this.mountPassenger(boneId, entity, supplier, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mountPassenger(String boneId, Entity entity, MountControllerSupplier supplier, @Nullable Consumer<MountController> consumer) {
|
||||
return this.canRide() && this.getSeat(boneId).map(mount -> this.mountPassenger((Mount)mount, entity, supplier, consumer)).orElse(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mountPassenger(Mount mount, Entity entity, MountControllerSupplier supplier) {
|
||||
return this.mountPassenger(mount, entity, supplier, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mountPassenger(Mount mount, Entity entity, MountControllerSupplier supplier, @Nullable Consumer<MountController> consumer) {
|
||||
ModelMountEvent event = new ModelMountEvent(this.activeModel, entity, false, mount);
|
||||
ModelEngineAPI.callEvent(event);
|
||||
if (event.isCancelled()) {
|
||||
return false;
|
||||
} else {
|
||||
boolean success = mount.addPassenger(entity);
|
||||
if (success) {
|
||||
this.passengerSeatMap.put(entity, mount);
|
||||
this.registerMountPair(entity, mount, supplier, consumer);
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mountAvailable(Entity entity, MountControllerSupplier supplier) {
|
||||
return this.mountAvailable(entity, supplier, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mountAvailable(Entity entity, MountControllerSupplier supplier, @Nullable Consumer<MountController> consumer) {
|
||||
return this.mountAvailable(entity, this.seats.keySet(), supplier, consumer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Entity> mountAvailable(Collection<Entity> entities, MountControllerSupplier supplier) {
|
||||
return this.mountAvailable(entities, supplier, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Entity> mountAvailable(Collection<Entity> entities, MountControllerSupplier supplier, @Nullable Consumer<MountController> consumer) {
|
||||
return this.mountAvailable(entities, this.seats.keySet(), supplier, consumer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mountAvailable(Entity entity, Collection<String> seats, MountControllerSupplier supplier) {
|
||||
return this.mountAvailable(entity, seats, supplier, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mountAvailable(Entity entity, Collection<String> seats, MountControllerSupplier supplier, @Nullable Consumer<MountController> consumer) {
|
||||
for (String seatId : seats) {
|
||||
Optional maybeSeat = this.getSeat(seatId);
|
||||
if (!maybeSeat.isEmpty()) {
|
||||
BoneBehavior seat = (BoneBehavior)maybeSeat.get();
|
||||
if (((Mount)seat).getPassengers().isEmpty()) {
|
||||
this.mountPassenger((Mount)seat, entity, supplier, consumer);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Entity> mountAvailable(Collection<Entity> entities, Collection<String> seats, MountControllerSupplier supplier) {
|
||||
return this.mountAvailable(entities, seats, supplier, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Entity> mountAvailable(
|
||||
Collection<Entity> entities, Collection<String> seats, MountControllerSupplier supplier, @Nullable Consumer<MountController> consumer
|
||||
) {
|
||||
HashSet<Entity> unseated = new HashSet<>();
|
||||
boolean noSeats = false;
|
||||
|
||||
label30:
|
||||
for (Entity entity : entities) {
|
||||
if (!noSeats) {
|
||||
noSeats = true;
|
||||
|
||||
for (String seatId : seats) {
|
||||
Optional maybeSeat = this.getSeat(seatId);
|
||||
if (!maybeSeat.isEmpty()) {
|
||||
BoneBehavior seat = (BoneBehavior)maybeSeat.get();
|
||||
if (((Mount)seat).getPassengers().isEmpty()) {
|
||||
this.mountPassenger((Mount)seat, entity, supplier, consumer);
|
||||
noSeats = false;
|
||||
continue label30;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unseated.add(entity);
|
||||
}
|
||||
|
||||
return unseated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mountLeastOccupied(Entity entity, MountControllerSupplier supplier) {
|
||||
return this.mountLeastOccupied(entity, supplier, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mountLeastOccupied(Entity entity, MountControllerSupplier supplier, @Nullable Consumer<MountController> consumer) {
|
||||
return this.mountLeastOccupied(entity, this.seats.keySet(), supplier, consumer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Entity> mountLeastOccupied(Collection<Entity> entities, MountControllerSupplier supplier) {
|
||||
return this.mountLeastOccupied(entities, supplier, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Entity> mountLeastOccupied(Collection<Entity> entities, MountControllerSupplier supplier, @Nullable Consumer<MountController> consumer) {
|
||||
return this.mountLeastOccupied(entities, this.seats.keySet(), supplier, consumer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mountLeastOccupied(Entity entity, Collection<String> seats, MountControllerSupplier supplier) {
|
||||
return this.mountLeastOccupied(entity, seats, supplier, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mountLeastOccupied(Entity entity, Collection<String> seats, MountControllerSupplier supplier, @Nullable Consumer<MountController> consumer) {
|
||||
int leastCount = Integer.MAX_VALUE;
|
||||
Mount leastOccupied = null;
|
||||
|
||||
for (String seatId : seats) {
|
||||
Optional maybeSeat = this.getSeat(seatId);
|
||||
if (!maybeSeat.isEmpty()) {
|
||||
BoneBehavior seat = (BoneBehavior)maybeSeat.get();
|
||||
if (((Mount)seat).canMountMore()) {
|
||||
int count = ((Mount)seat).getPassengers().size();
|
||||
if (count == 0) {
|
||||
return this.mountPassenger((Mount)seat, entity, supplier, consumer);
|
||||
}
|
||||
|
||||
if (leastCount > count) {
|
||||
leastCount = count;
|
||||
leastOccupied = (Mount)seat;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return leastOccupied != null ? this.mountPassenger(leastOccupied, entity, supplier, consumer) : false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Entity> mountLeastOccupied(Collection<Entity> entities, Collection<String> seats, MountControllerSupplier supplier) {
|
||||
return this.mountLeastOccupied(entities, seats, supplier, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Entity> mountLeastOccupied(
|
||||
Collection<Entity> entities, Collection<String> seats, MountControllerSupplier supplier, @Nullable Consumer<MountController> consumer
|
||||
) {
|
||||
HashSet<Entity> set = new HashSet<>();
|
||||
|
||||
for (Entity entity : entities) {
|
||||
if (!this.mountLeastOccupied(entity, seats, supplier, consumer)) {
|
||||
set.add(entity);
|
||||
}
|
||||
}
|
||||
|
||||
return set;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Entity dismountDriver() {
|
||||
if (this.driverBone != null && this.driver != null) {
|
||||
ModelDismountEvent event = new ModelDismountEvent(this.activeModel, this.driver, true, this.driverBone);
|
||||
ModelEngineAPI.callEvent(event);
|
||||
if (event.isCancelled()) {
|
||||
return null;
|
||||
} else {
|
||||
this.driverBone.removePassenger(this.driver);
|
||||
this.flushMountPassengerUpdate(this.driverBone);
|
||||
this.removeMountPair(this.driver);
|
||||
Entity t = this.driver;
|
||||
this.driver = null;
|
||||
return t;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dismountPassenger(@NotNull Entity entity) {
|
||||
Mount mount = this.passengerSeatMap.remove(entity);
|
||||
if (mount != null) {
|
||||
ModelDismountEvent event = new ModelDismountEvent(this.activeModel, entity, false, mount);
|
||||
ModelEngineAPI.callEvent(event);
|
||||
if (event.isCancelled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
mount.removePassenger(entity);
|
||||
this.flushMountPassengerUpdate(mount);
|
||||
this.removeMountPair(entity);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dismountRider(@NotNull Entity entity) {
|
||||
if (entity == this.driver) {
|
||||
this.dismountDriver();
|
||||
} else {
|
||||
this.dismountPassenger(entity);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Entity> dismountPassengers(String boneId) {
|
||||
HashSet<Entity> removed = new HashSet<>();
|
||||
this.getSeat(boneId).ifPresent(mount -> {
|
||||
for (Entity entity : ((Mount)mount).getPassengers()) {
|
||||
ModelDismountEvent event = new ModelDismountEvent(this.activeModel, entity, false, (Mount)mount);
|
||||
ModelEngineAPI.callEvent(event);
|
||||
if (!event.isCancelled()) {
|
||||
((Mount)mount).removePassenger(entity);
|
||||
this.removeMountPair(entity);
|
||||
removed.add(entity);
|
||||
}
|
||||
}
|
||||
|
||||
if (!removed.isEmpty()) {
|
||||
this.flushMountPassengerUpdate((Mount)mount);
|
||||
}
|
||||
});
|
||||
return removed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Entity> dismountAll() {
|
||||
HashSet<Entity> set = new HashSet<>();
|
||||
|
||||
for (BoneBehavior val : this.getSeats().values()) {
|
||||
Set<Entity> passengers = ((Mount)val).clearPassengers();
|
||||
boolean anyDismounted = false;
|
||||
|
||||
for (Entity entity : passengers) {
|
||||
ModelDismountEvent event = new ModelDismountEvent(this.activeModel, entity, false, (Mount)val);
|
||||
ModelEngineAPI.callEvent(event);
|
||||
if (!event.isCancelled()) {
|
||||
this.passengerSeatMap.remove(entity);
|
||||
this.removeMountPair(entity);
|
||||
set.add(entity);
|
||||
anyDismounted = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (anyDismounted) {
|
||||
this.flushMountPassengerUpdate((Mount)val);
|
||||
}
|
||||
}
|
||||
|
||||
return set;
|
||||
}
|
||||
|
||||
private void registerMountPair(Entity entity, Mount mount, MountControllerSupplier supplier, @Nullable Consumer<MountController> consumer) {
|
||||
MountController controller = supplier.createController(entity, mount);
|
||||
if (consumer != null) {
|
||||
consumer.accept(controller);
|
||||
}
|
||||
|
||||
ModelEngineAPI.getMountPairManager().registerMountedPair(entity, this.activeModel, controller);
|
||||
this.activeModel.getModeledEntity().getBase().setCollidableWith(entity, false);
|
||||
}
|
||||
|
||||
private void removeMountPair(Entity entity) {
|
||||
ModelEngineAPI.getMountPairManager().unregisterMountedPair(entity.getUniqueId());
|
||||
this.activeModel.getModeledEntity().getBase().setCollidableWith(entity, true);
|
||||
}
|
||||
|
||||
private void flushMountPassengerUpdate(Mount mount) {
|
||||
if (mount instanceof BoneBehavior behavior) {
|
||||
String boneId = behavior.getBone().getUniqueBoneId();
|
||||
this.activeModel.getBehaviorRenderer(BoneBehaviorTypes.MOUNT).ifPresent(renderer -> {
|
||||
if (renderer instanceof MountRenderer mountRenderer) {
|
||||
MountRenderer.Mount renderedMount = mountRenderer.getRendered().get(boneId);
|
||||
if (renderedMount == null) {
|
||||
renderedMount = mountRenderer.getSpawnQueue().get(boneId);
|
||||
}
|
||||
|
||||
if (renderedMount != null) {
|
||||
HashSet<Integer> newIds = new HashSet<>();
|
||||
if (ServerInfo.IS_FOLIA && mount instanceof MountImpl mountImpl) {
|
||||
newIds.addAll(mountImpl.getPassengerEntityIds());
|
||||
} else {
|
||||
for (Entity entity : mount.getPassengers()) {
|
||||
newIds.add(entity.getEntityId());
|
||||
}
|
||||
}
|
||||
|
||||
renderedMount.getPassengers().retainAll(newIds);
|
||||
renderedMount.getPassengers().addAll(newIds);
|
||||
Set<UUID> targets = this.activeModel.getModeledEntity().getBase().getData().getTracking().keySet();
|
||||
ModelEngineAPI.getNMSHandler().sendMountPassengerUpdate(targets, renderedMount.getMountId(), renderedMount.getPassengers().get());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCanDrive(boolean canDrive) {
|
||||
this.canDrive = canDrive;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCanRide(boolean canRide) {
|
||||
this.canRide = canRide;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Entity getDriver() {
|
||||
return this.driver;
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.ticxo.modelengine.core.model.bone.render;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer;
|
||||
import com.ticxo.modelengine.api.model.render.ModelRenderer;
|
||||
import com.ticxo.modelengine.api.nms.NMSHandler;
|
||||
|
||||
public abstract class AbstractBehaviorRenderer implements BehaviorRenderer {
|
||||
protected final ActiveModel activeModel;
|
||||
protected final NMSHandler nmsHandler = ModelEngineAPI.getNMSHandler();
|
||||
protected ModelRenderer modelRenderer;
|
||||
|
||||
public AbstractBehaviorRenderer(ActiveModel activeModel) {
|
||||
this.activeModel = activeModel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActiveModel getActiveModel() {
|
||||
return this.activeModel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModelRenderer getModelRenderer() {
|
||||
return this.modelRenderer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setModelRenderer(ModelRenderer modelRenderer) {
|
||||
this.modelRenderer = modelRenderer;
|
||||
}
|
||||
}
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
package com.ticxo.modelengine.core.model.bone.render;
|
||||
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser;
|
||||
import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer;
|
||||
import com.ticxo.modelengine.api.model.bone.type.HeldItem;
|
||||
import com.ticxo.modelengine.api.nms.RenderParsers;
|
||||
import com.ticxo.modelengine.api.utils.data.PositionCodec;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.DataTracker;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.Map.Entry;
|
||||
import org.bukkit.entity.ItemDisplay.ItemDisplayTransform;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class HeldItemRendererImpl extends AbstractBehaviorRenderer implements HeldItemRenderer {
|
||||
private final int id;
|
||||
private final UUID uuid;
|
||||
private final Map<String, HeldItemRenderer.Item> spawnQueue = new HashMap<>();
|
||||
private final Map<String, HeldItemRenderer.Item> rendered = new HashMap<>();
|
||||
private final Map<String, HeldItemRenderer.Item> destroyQueue = new HashMap<>();
|
||||
private final CollectionDataTracker<Integer> passengers = new CollectionDataTracker<>(new HashSet<>());
|
||||
private final PositionCodec positionCodec = new PositionCodec();
|
||||
private boolean initialized;
|
||||
private BehaviorRendererParser<HeldItemRenderer> cachedParser;
|
||||
private RenderParsers cachedParserOwner;
|
||||
|
||||
public HeldItemRendererImpl(ActiveModel activeModel) {
|
||||
super(activeModel);
|
||||
this.id = this.nmsHandler.getEntityHandler().getNextEntityId();
|
||||
this.uuid = UUID.randomUUID();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize() {
|
||||
for (Entry<String, ModelBone> boneEntry : this.activeModel.getBones().entrySet()) {
|
||||
String boneId = boneEntry.getKey();
|
||||
ModelBone modelBone = boneEntry.getValue();
|
||||
this.create(boneId, modelBone);
|
||||
}
|
||||
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
private void create(String boneId, ModelBone modelBone) {
|
||||
Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.ITEM);
|
||||
if (!maybeData.isEmpty()) {
|
||||
BoneBehavior itemData = (BoneBehavior)maybeData.get();
|
||||
HeldItemRendererImpl.ItemImpl item = new HeldItemRendererImpl.ItemImpl(this.nmsHandler.getEntityHandler().getNextEntityId(), UUID.randomUUID());
|
||||
item.position.set(((HeldItem)itemData).getLocation());
|
||||
item.scale.set(modelBone.getGlobalTransform().getScale());
|
||||
item.rotation.set(((HeldItem)itemData).getRotation());
|
||||
item.model.set(modelBone.isVisible() ? modelBone.getModel() : null);
|
||||
item.display.set(((HeldItem)itemData).getDisplay());
|
||||
item.glowing.set(modelBone.isGlowing());
|
||||
item.glowColor.set(modelBone.getGlowColor());
|
||||
this.spawnQueue.put(boneId, item);
|
||||
this.destroyQueue.remove(boneId);
|
||||
this.passengers.add(item.id);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readBoneData() {
|
||||
if (this.initialized) {
|
||||
this.destroyQueue.putAll(this.rendered);
|
||||
|
||||
for (Entry<String, ModelBone> boneEntry : this.activeModel.getBones().entrySet()) {
|
||||
String boneId = boneEntry.getKey();
|
||||
ModelBone modelBone = boneEntry.getValue();
|
||||
HeldItemRenderer.Item renderer = this.getQueued(boneId);
|
||||
if (renderer != null) {
|
||||
this.read(boneId, renderer, modelBone);
|
||||
} else {
|
||||
this.create(boneId, modelBone);
|
||||
}
|
||||
}
|
||||
|
||||
this.destroyQueue.forEach((s, item) -> this.passengers.remove(item.getId()));
|
||||
}
|
||||
}
|
||||
|
||||
private void read(String boneId, HeldItemRenderer.Item item, ModelBone modelBone) {
|
||||
Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.ITEM);
|
||||
maybeData.ifPresent(heldItem -> {
|
||||
item.getPosition().set(((HeldItem)heldItem).getLocation());
|
||||
item.getScale().set(modelBone.getGlobalTransform().getScale());
|
||||
item.getRotation().set(((HeldItem)heldItem).getRotation());
|
||||
item.getGlowing().set(modelBone.isGlowing());
|
||||
item.getGlowColor().set(modelBone.getGlowColor());
|
||||
if (!modelBone.isVisible()) {
|
||||
item.getModel().set(null);
|
||||
} else {
|
||||
item.getModel().set(modelBone.getModel());
|
||||
if (modelBone.getModelTracker().isDirty()) {
|
||||
modelBone.getModelTracker().clearDirty();
|
||||
item.getModel().markDirty();
|
||||
}
|
||||
}
|
||||
|
||||
item.getDisplay().set(((HeldItem)heldItem).getDisplay());
|
||||
this.destroyQueue.remove(boneId);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendToClient(RenderParsers parsers) {
|
||||
if (this.initialized) {
|
||||
this.destroyQueue.keySet().forEach(this.rendered::remove);
|
||||
this.parser(parsers).sendToClients(this);
|
||||
this.rendered.putAll(this.spawnQueue);
|
||||
this.spawnQueue.clear();
|
||||
this.destroyQueue.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy(RenderParsers parsers) {
|
||||
if (this.initialized) {
|
||||
parsers.getBehaviorParser(this).destroy(this);
|
||||
}
|
||||
}
|
||||
|
||||
private BehaviorRendererParser<HeldItemRenderer> parser(RenderParsers parsers) {
|
||||
if (this.cachedParser == null || this.cachedParserOwner != parsers) {
|
||||
this.cachedParserOwner = parsers;
|
||||
this.cachedParser = parsers.getBehaviorParser(this);
|
||||
}
|
||||
|
||||
return this.cachedParser;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUuid() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, HeldItemRenderer.Item> getSpawnQueue() {
|
||||
return this.spawnQueue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, HeldItemRenderer.Item> getRendered() {
|
||||
return this.rendered;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, HeldItemRenderer.Item> getDestroyQueue() {
|
||||
return this.destroyQueue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CollectionDataTracker<Integer> getPassengers() {
|
||||
return this.passengers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PositionCodec getPositionCodec() {
|
||||
return this.positionCodec;
|
||||
}
|
||||
|
||||
public static class ItemImpl implements HeldItemRenderer.Item {
|
||||
private final int id;
|
||||
private final UUID uuid;
|
||||
private final DataTracker<Vector3f> position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set);
|
||||
private final DataTracker<Vector3f> scale = new UpdateDataTracker<>(new Vector3f(), Vector3f::set);
|
||||
private final DataTracker<Quaternionf> rotation = new UpdateDataTracker<>(new Quaternionf(), Quaternionf::set);
|
||||
private final DataTracker<ItemStack> model = new DataTracker<>();
|
||||
private final DataTracker<ItemDisplayTransform> display = new DataTracker<>(ItemDisplayTransform.NONE);
|
||||
private final DataTracker<Boolean> glowing = new DataTracker<>(false);
|
||||
private final DataTracker<Integer> glowColor = new DataTracker<>(-1);
|
||||
|
||||
@Override
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUuid() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getPosition() {
|
||||
return this.position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getScale() {
|
||||
return this.scale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Quaternionf> getRotation() {
|
||||
return this.rotation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<ItemStack> getModel() {
|
||||
return this.model;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<ItemDisplayTransform> getDisplay() {
|
||||
return this.display;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Boolean> getGlowing() {
|
||||
return this.glowing;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Integer> getGlowColor() {
|
||||
return this.glowColor;
|
||||
}
|
||||
|
||||
public ItemImpl(int id, UUID uuid) {
|
||||
this.id = id;
|
||||
this.uuid = uuid;
|
||||
}
|
||||
}
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
package com.ticxo.modelengine.core.model.bone.render;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.interaction.InteractionTracker;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser;
|
||||
import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer;
|
||||
import com.ticxo.modelengine.api.nms.RenderParsers;
|
||||
import com.ticxo.modelengine.api.utils.data.PositionCodec;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.DataTracker;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.Map.Entry;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class LeashRendererImpl extends AbstractBehaviorRenderer implements LeashRenderer {
|
||||
private final Map<String, LeashRenderer.Leash> spawnQueue = new HashMap<>();
|
||||
private final Map<String, LeashRenderer.Leash> rendered = new HashMap<>();
|
||||
private final Map<String, LeashRenderer.Leash> destroyQueue = new HashMap<>();
|
||||
private boolean initialized;
|
||||
private BehaviorRendererParser<LeashRenderer> cachedParser;
|
||||
private RenderParsers cachedParserOwner;
|
||||
|
||||
public LeashRendererImpl(ActiveModel activeModel) {
|
||||
super(activeModel);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize() {
|
||||
for (Entry<String, ModelBone> boneEntry : this.activeModel.getBones().entrySet()) {
|
||||
String boneId = boneEntry.getKey();
|
||||
ModelBone modelBone = boneEntry.getValue();
|
||||
this.create(boneId, modelBone);
|
||||
}
|
||||
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
private void create(String boneId, ModelBone modelBone) {
|
||||
Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.LEASH);
|
||||
if (!maybeData.isEmpty()) {
|
||||
BoneBehavior leashData = (BoneBehavior)maybeData.get();
|
||||
LeashRendererImpl.LeashImpl leash = new LeashRendererImpl.LeashImpl(
|
||||
this.nmsHandler.getEntityHandler().getNextEntityId(), ((com.ticxo.modelengine.api.model.bone.type.Leash)leashData).getId()
|
||||
);
|
||||
leash.position.set(((com.ticxo.modelengine.api.model.bone.type.Leash)leashData).getLocation());
|
||||
leash.connected.set(this.getConnectedId((com.ticxo.modelengine.api.model.bone.type.Leash)leashData));
|
||||
this.spawnQueue.put(boneId, leash);
|
||||
this.destroyQueue.remove(boneId);
|
||||
ModelEngineAPI.getInteractionTracker().setModelRelay(leash.getLeashId(), this.activeModel);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readBoneData() {
|
||||
if (this.initialized) {
|
||||
this.destroyQueue.putAll(this.rendered);
|
||||
|
||||
for (Entry<String, ModelBone> boneEntry : this.activeModel.getBones().entrySet()) {
|
||||
String boneId = boneEntry.getKey();
|
||||
ModelBone modelBone = boneEntry.getValue();
|
||||
LeashRenderer.Leash renderer = this.getQueued(boneId);
|
||||
if (renderer != null) {
|
||||
this.read(boneId, renderer, modelBone);
|
||||
} else {
|
||||
this.create(boneId, modelBone);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void read(String boneId, LeashRenderer.Leash leash, ModelBone modelBone) {
|
||||
Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.LEASH);
|
||||
maybeData.ifPresent(leashData -> {
|
||||
leash.getPosition().set(((com.ticxo.modelengine.api.model.bone.type.Leash)leashData).getLocation());
|
||||
leash.getConnected().set(this.getConnectedId((com.ticxo.modelengine.api.model.bone.type.Leash)leashData));
|
||||
this.destroyQueue.remove(boneId);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendToClient(RenderParsers parsers) {
|
||||
if (this.initialized) {
|
||||
this.destroyQueue.keySet().forEach(this.rendered::remove);
|
||||
this.parser(parsers).sendToClients(this);
|
||||
this.destroyQueue.values().forEach(leash -> ModelEngineAPI.getInteractionTracker().removeModelRelay(leash.getLeashId()));
|
||||
this.rendered.putAll(this.spawnQueue);
|
||||
this.spawnQueue.clear();
|
||||
this.destroyQueue.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy(RenderParsers parsers) {
|
||||
if (this.initialized) {
|
||||
InteractionTracker tracker = ModelEngineAPI.getInteractionTracker();
|
||||
this.rendered.values().forEach(leash -> tracker.removeModelRelay(leash.getLeashId()));
|
||||
this.spawnQueue.values().forEach(leash -> tracker.removeModelRelay(leash.getLeashId()));
|
||||
parsers.getBehaviorParser(this).destroy(this);
|
||||
}
|
||||
}
|
||||
|
||||
private int getConnectedId(com.ticxo.modelengine.api.model.bone.type.Leash leash) {
|
||||
Entity entity = leash.getConnectedEntity();
|
||||
if (entity != null) {
|
||||
return entity.getEntityId();
|
||||
} else {
|
||||
var other = (BoneBehavior & com.ticxo.modelengine.api.model.bone.type.Leash)leash.getConnectedLeash();
|
||||
return other != null ? ((com.ticxo.modelengine.api.model.bone.type.Leash)other).getId() : -1;
|
||||
}
|
||||
}
|
||||
|
||||
private BehaviorRendererParser<LeashRenderer> parser(RenderParsers parsers) {
|
||||
if (this.cachedParser == null || this.cachedParserOwner != parsers) {
|
||||
this.cachedParserOwner = parsers;
|
||||
this.cachedParser = parsers.getBehaviorParser(this);
|
||||
}
|
||||
|
||||
return this.cachedParser;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, LeashRenderer.Leash> getSpawnQueue() {
|
||||
return this.spawnQueue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, LeashRenderer.Leash> getRendered() {
|
||||
return this.rendered;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, LeashRenderer.Leash> getDestroyQueue() {
|
||||
return this.destroyQueue;
|
||||
}
|
||||
|
||||
public static class LeashImpl implements LeashRenderer.Leash {
|
||||
private final int pivotId;
|
||||
private final UUID pivotUUID = UUID.randomUUID();
|
||||
private final int leashId;
|
||||
private final UUID leastUUID = UUID.randomUUID();
|
||||
private final DataTracker<Vector3f> position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set);
|
||||
private final DataTracker<Integer> connected = new DataTracker<>();
|
||||
private final PositionCodec positionCodec = new PositionCodec();
|
||||
|
||||
public LeashImpl(int pivotId, int leashId) {
|
||||
this.pivotId = pivotId;
|
||||
this.leashId = leashId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPivotId() {
|
||||
return this.pivotId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getPivotUUID() {
|
||||
return this.pivotUUID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getLeashId() {
|
||||
return this.leashId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getLeastUUID() {
|
||||
return this.leastUUID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getPosition() {
|
||||
return this.position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Integer> getConnected() {
|
||||
return this.connected;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PositionCodec getPositionCodec() {
|
||||
return this.positionCodec;
|
||||
}
|
||||
}
|
||||
}
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
package com.ticxo.modelengine.core.model.bone.render;
|
||||
|
||||
import com.ticxo.modelengine.api.ServerInfo;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser;
|
||||
import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer;
|
||||
import com.ticxo.modelengine.api.nms.RenderParsers;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.DataTracker;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker;
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import com.ticxo.modelengine.core.model.bone.behavior.MountImpl;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.Map.Entry;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class MountRendererImpl extends AbstractBehaviorRenderer implements MountRenderer {
|
||||
private final Map<String, MountRenderer.Mount> spawnQueue = new HashMap<>();
|
||||
private final Map<String, MountRenderer.Mount> rendered = new HashMap<>();
|
||||
private final Map<String, MountRenderer.Mount> destroyQueue = new HashMap<>();
|
||||
private boolean initialized;
|
||||
private BehaviorRendererParser<MountRenderer> cachedParser;
|
||||
private RenderParsers cachedParserOwner;
|
||||
|
||||
public MountRendererImpl(ActiveModel activeModel) {
|
||||
super(activeModel);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize() {
|
||||
for (Entry<String, ModelBone> boneEntry : this.activeModel.getBones().entrySet()) {
|
||||
String boneId = boneEntry.getKey();
|
||||
ModelBone modelBone = boneEntry.getValue();
|
||||
this.create(boneId, modelBone);
|
||||
}
|
||||
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
private void create(String boneId, ModelBone modelBone) {
|
||||
Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.MOUNT);
|
||||
if (!maybeData.isEmpty()) {
|
||||
BoneBehavior mountData = (BoneBehavior)maybeData.get();
|
||||
MountRendererImpl.MountRenderData mount = new MountRendererImpl.MountRenderData(
|
||||
this.nmsHandler.getEntityHandler().getNextEntityId(), UUID.randomUUID(), this.nmsHandler.getEntityHandler().getNextEntityId(), UUID.randomUUID()
|
||||
);
|
||||
mount.position.set(((com.ticxo.modelengine.api.model.bone.type.Mount)mountData).getGlobalLocation());
|
||||
mount.yaw.set(TMath.rotToByte(modelBone.getYaw()));
|
||||
mount.health.set(modelBone.getActiveModel().getModeledEntity().getBase().getHealth());
|
||||
mount.maxHealth.set(modelBone.getActiveModel().getModeledEntity().getBase().getMaxHealth());
|
||||
if (ServerInfo.IS_FOLIA && mountData instanceof MountImpl mountImpl) {
|
||||
mount.passengers.get().addAll(mountImpl.getPassengerEntityIds());
|
||||
} else {
|
||||
for (Entity entity : ((com.ticxo.modelengine.api.model.bone.type.Mount)mountData).getPassengers()) {
|
||||
mount.passengers.get().add(entity.getEntityId());
|
||||
}
|
||||
}
|
||||
|
||||
this.spawnQueue.put(boneId, mount);
|
||||
this.destroyQueue.remove(boneId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readBoneData() {
|
||||
if (this.initialized) {
|
||||
this.destroyQueue.putAll(this.rendered);
|
||||
|
||||
for (Entry<String, ModelBone> boneEntry : this.activeModel.getBones().entrySet()) {
|
||||
String boneId = boneEntry.getKey();
|
||||
ModelBone modelBone = boneEntry.getValue();
|
||||
MountRenderer.Mount renderer = this.getQueued(boneId);
|
||||
if (renderer != null) {
|
||||
this.read(boneId, renderer, modelBone);
|
||||
} else {
|
||||
this.create(boneId, modelBone);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void read(String boneId, MountRenderer.Mount mount, ModelBone modelBone) {
|
||||
mount.getYaw().set(TMath.rotToByte(modelBone.getYaw()));
|
||||
mount.getHealth().set(modelBone.getActiveModel().getModeledEntity().getBase().getHealth());
|
||||
mount.getMaxHealth().set(modelBone.getActiveModel().getModeledEntity().getBase().getMaxHealth());
|
||||
Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.MOUNT);
|
||||
maybeData.ifPresent(mountData -> {
|
||||
mount.getPosition().set(((com.ticxo.modelengine.api.model.bone.type.Mount)mountData).getGlobalLocation());
|
||||
HashSet<Integer> newIds = new HashSet<>();
|
||||
if (ServerInfo.IS_FOLIA && mountData instanceof MountImpl mountImpl) {
|
||||
newIds.addAll(mountImpl.getPassengerEntityIds());
|
||||
} else {
|
||||
for (Entity entity : ((com.ticxo.modelengine.api.model.bone.type.Mount)mountData).getPassengers()) {
|
||||
newIds.add(entity.getEntityId());
|
||||
}
|
||||
}
|
||||
|
||||
mount.getPassengers().retainAll(newIds);
|
||||
mount.getPassengers().addAll(newIds);
|
||||
this.destroyQueue.remove(boneId);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendToClient(RenderParsers parsers) {
|
||||
if (this.initialized) {
|
||||
this.destroyQueue.keySet().forEach(this.rendered::remove);
|
||||
this.parser(parsers).sendToClients(this);
|
||||
this.rendered.putAll(this.spawnQueue);
|
||||
this.spawnQueue.clear();
|
||||
this.destroyQueue.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy(RenderParsers parsers) {
|
||||
if (this.initialized) {
|
||||
parsers.getBehaviorParser(this).destroy(this);
|
||||
}
|
||||
}
|
||||
|
||||
private BehaviorRendererParser<MountRenderer> parser(RenderParsers parsers) {
|
||||
if (this.cachedParser == null || this.cachedParserOwner != parsers) {
|
||||
this.cachedParserOwner = parsers;
|
||||
this.cachedParser = parsers.getBehaviorParser(this);
|
||||
}
|
||||
|
||||
return this.cachedParser;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, MountRenderer.Mount> getSpawnQueue() {
|
||||
return this.spawnQueue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, MountRenderer.Mount> getRendered() {
|
||||
return this.rendered;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, MountRenderer.Mount> getDestroyQueue() {
|
||||
return this.destroyQueue;
|
||||
}
|
||||
|
||||
public static class MountRenderData implements MountRenderer.Mount {
|
||||
private final int pivotId;
|
||||
private final UUID pivotUuid;
|
||||
private final int mountId;
|
||||
private final UUID mountUuid;
|
||||
private final DataTracker<Vector3f> position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set);
|
||||
private final DataTracker<Float> health = new DataTracker<>(20.0F);
|
||||
private final DataTracker<Float> maxHealth = new DataTracker<>(20.0F);
|
||||
private final DataTracker<Byte> yaw = new DataTracker<>((byte)0);
|
||||
private final CollectionDataTracker<Integer> passengers = new CollectionDataTracker<>(new HashSet<>());
|
||||
|
||||
public MountRenderData(int pivotId, UUID pivotUuid, int mountId, UUID mountUuid) {
|
||||
this.pivotId = pivotId;
|
||||
this.pivotUuid = pivotUuid;
|
||||
this.mountId = mountId;
|
||||
this.mountUuid = mountUuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPivotId() {
|
||||
return this.pivotId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getPivotUuid() {
|
||||
return this.pivotUuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMountId() {
|
||||
return this.mountId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getMountUuid() {
|
||||
return this.mountUuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getPosition() {
|
||||
return this.position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Float> getHealth() {
|
||||
return this.health;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Float> getMaxHealth() {
|
||||
return this.maxHealth;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Byte> getYaw() {
|
||||
return this.yaw;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CollectionDataTracker<Integer> getPassengers() {
|
||||
return this.passengers;
|
||||
}
|
||||
}
|
||||
}
|
||||
+277
@@ -0,0 +1,277 @@
|
||||
package com.ticxo.modelengine.core.model.bone.render;
|
||||
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser;
|
||||
import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer;
|
||||
import com.ticxo.modelengine.api.nms.RenderParsers;
|
||||
import com.ticxo.modelengine.api.utils.data.PositionCodec;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.DataTracker;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker;
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.Map.Entry;
|
||||
import org.bukkit.entity.Display.Billboard;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class NameTagRendererImpl extends AbstractBehaviorRenderer implements NameTagRenderer {
|
||||
private final Map<String, NameTagRenderer.NameTag> spawnQueue = new HashMap<>();
|
||||
private final Map<String, NameTagRenderer.NameTag> rendered = new HashMap<>();
|
||||
private final Map<String, NameTagRenderer.NameTag> destroyQueue = new HashMap<>();
|
||||
private boolean initialized;
|
||||
private BehaviorRendererParser<NameTagRenderer> cachedParser;
|
||||
private RenderParsers cachedParserOwner;
|
||||
|
||||
public NameTagRendererImpl(ActiveModel activeModel) {
|
||||
super(activeModel);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize() {
|
||||
for (Entry<String, ModelBone> boneEntry : this.activeModel.getBones().entrySet()) {
|
||||
String boneId = boneEntry.getKey();
|
||||
ModelBone modelBone = boneEntry.getValue();
|
||||
this.create(boneId, modelBone);
|
||||
}
|
||||
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
private void create(String boneId, ModelBone modelBone) {
|
||||
Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.NAMETAG);
|
||||
if (!maybeData.isEmpty()) {
|
||||
BoneBehavior nameTagData = (BoneBehavior)maybeData.get();
|
||||
NameTagRendererImpl.NameTagImpl nameTag = new NameTagRendererImpl.NameTagImpl(
|
||||
this.nmsHandler.getEntityHandler().getNextEntityId(), UUID.randomUUID(), this.nmsHandler.getEntityHandler().getNextEntityId(), UUID.randomUUID()
|
||||
);
|
||||
nameTag.position.set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getLocation());
|
||||
nameTag.jsonString.set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getJsonString());
|
||||
nameTag.visibility.set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).isVisible());
|
||||
nameTag.backgroundColor
|
||||
.set(
|
||||
((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).isUseDefaultBackgroundColor()
|
||||
? 1073741824
|
||||
: ((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getBackgroundColor()
|
||||
);
|
||||
nameTag.billboard.set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getBillboard());
|
||||
nameTag.textOpacity.set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getTextOpacity());
|
||||
nameTag.lineWidth.set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getLineWidth());
|
||||
nameTag.translate.set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getPosition());
|
||||
nameTag.scale.set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getScale());
|
||||
nameTag.getStyle().set(this.getStyle((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData));
|
||||
nameTag.getBrightness().set(modelBone.getBrightness());
|
||||
this.spawnQueue.put(boneId, nameTag);
|
||||
this.destroyQueue.remove(boneId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readBoneData() {
|
||||
if (this.initialized) {
|
||||
this.destroyQueue.putAll(this.rendered);
|
||||
|
||||
for (Entry<String, ModelBone> boneEntry : this.activeModel.getBones().entrySet()) {
|
||||
String boneId = boneEntry.getKey();
|
||||
ModelBone modelBone = boneEntry.getValue();
|
||||
NameTagRenderer.NameTag renderer = this.getQueued(boneId);
|
||||
if (renderer != null) {
|
||||
this.read(boneId, renderer, modelBone);
|
||||
} else {
|
||||
this.create(boneId, modelBone);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void read(String boneId, NameTagRenderer.NameTag nameTag, ModelBone modelBone) {
|
||||
Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.NAMETAG);
|
||||
maybeData.ifPresent(
|
||||
nameTagData -> {
|
||||
nameTag.getPosition().set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getLocation());
|
||||
nameTag.getJsonString().set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getJsonString());
|
||||
nameTag.getVisibility().set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).isVisible());
|
||||
nameTag.getBillboard().set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getBillboard());
|
||||
nameTag.getBackgroundColor()
|
||||
.set(
|
||||
((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).isUseDefaultBackgroundColor()
|
||||
? 1073741824
|
||||
: ((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getBackgroundColor()
|
||||
);
|
||||
nameTag.getTextOpacity().set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getTextOpacity());
|
||||
nameTag.getLineWidth().set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getLineWidth());
|
||||
nameTag.getTranslate().set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getPosition());
|
||||
nameTag.getScale().set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getScale());
|
||||
nameTag.getStyle().set(this.getStyle((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData));
|
||||
nameTag.getBrightness().set(modelBone.getBrightness());
|
||||
this.destroyQueue.remove(boneId);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private byte getStyle(com.ticxo.modelengine.api.model.bone.type.NameTag nameTagData) {
|
||||
byte style = 0;
|
||||
style = TMath.setBit(style, 0, nameTagData.isShadow());
|
||||
style = TMath.setBit(style, 1, nameTagData.isSeeThrough());
|
||||
style = TMath.setBit(style, 2, nameTagData.isUseDefaultBackgroundColor());
|
||||
|
||||
return switch (nameTagData.getAlignment()) {
|
||||
case CENTER -> style;
|
||||
case LEFT -> (byte)(style | 8);
|
||||
case RIGHT -> (byte)(style | 16);
|
||||
default -> throw new IncompatibleClassChangeError();
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendToClient(RenderParsers parsers) {
|
||||
if (this.initialized) {
|
||||
this.destroyQueue.keySet().forEach(this.rendered::remove);
|
||||
this.parser(parsers).sendToClients(this);
|
||||
this.rendered.putAll(this.spawnQueue);
|
||||
this.spawnQueue.clear();
|
||||
this.destroyQueue.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy(RenderParsers parsers) {
|
||||
if (this.initialized) {
|
||||
parsers.getBehaviorParser(this).destroy(this);
|
||||
}
|
||||
}
|
||||
|
||||
private BehaviorRendererParser<NameTagRenderer> parser(RenderParsers parsers) {
|
||||
if (this.cachedParser == null || this.cachedParserOwner != parsers) {
|
||||
this.cachedParserOwner = parsers;
|
||||
this.cachedParser = parsers.getBehaviorParser(this);
|
||||
}
|
||||
|
||||
return this.cachedParser;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, NameTagRenderer.NameTag> getSpawnQueue() {
|
||||
return this.spawnQueue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, NameTagRenderer.NameTag> getRendered() {
|
||||
return this.rendered;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, NameTagRenderer.NameTag> getDestroyQueue() {
|
||||
return this.destroyQueue;
|
||||
}
|
||||
|
||||
public static class NameTagImpl implements NameTagRenderer.NameTag {
|
||||
private final int pivotId;
|
||||
private final UUID pivotUuid;
|
||||
private final int tagId;
|
||||
private final UUID tagUuid;
|
||||
private final DataTracker<Vector3f> position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set);
|
||||
private final DataTracker<String> jsonString = new DataTracker<>();
|
||||
private final DataTracker<Boolean> visibility = new DataTracker<>(true);
|
||||
private final DataTracker<Integer> backgroundColor = new DataTracker<>(1073741824);
|
||||
private final DataTracker<Billboard> billboard = new DataTracker<>(Billboard.CENTER);
|
||||
private final DataTracker<Byte> textOpacity = new DataTracker<>((byte)0);
|
||||
private final DataTracker<Integer> lineWidth = new DataTracker<>(0);
|
||||
private final DataTracker<Vector3f> translate = new DataTracker<>(new Vector3f(0.0F));
|
||||
private final DataTracker<Vector3f> scale = new DataTracker<>(new Vector3f(1.0F));
|
||||
private final DataTracker<Byte> style = new DataTracker<>((byte)0);
|
||||
private final DataTracker<Integer> brightness = new DataTracker<>(0);
|
||||
private final PositionCodec positionCodec = new PositionCodec();
|
||||
|
||||
public NameTagImpl(int pivotId, UUID pivotUuid, int tagId, UUID tagUuid) {
|
||||
this.pivotId = pivotId;
|
||||
this.pivotUuid = pivotUuid;
|
||||
this.tagId = tagId;
|
||||
this.tagUuid = tagUuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPivotId() {
|
||||
return this.pivotId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getPivotUuid() {
|
||||
return this.pivotUuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTagId() {
|
||||
return this.tagId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getTagUuid() {
|
||||
return this.tagUuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getPosition() {
|
||||
return this.position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<String> getJsonString() {
|
||||
return this.jsonString;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Boolean> getVisibility() {
|
||||
return this.visibility;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Integer> getBackgroundColor() {
|
||||
return this.backgroundColor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Billboard> getBillboard() {
|
||||
return this.billboard;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Byte> getTextOpacity() {
|
||||
return this.textOpacity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Integer> getLineWidth() {
|
||||
return this.lineWidth;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getTranslate() {
|
||||
return this.translate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getScale() {
|
||||
return this.scale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Byte> getStyle() {
|
||||
return this.style;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Integer> getBrightness() {
|
||||
return this.brightness;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PositionCodec getPositionCodec() {
|
||||
return this.positionCodec;
|
||||
}
|
||||
}
|
||||
}
|
||||
+361
@@ -0,0 +1,361 @@
|
||||
package com.ticxo.modelengine.core.model.bone.render;
|
||||
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneItems;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser;
|
||||
import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer;
|
||||
import com.ticxo.modelengine.api.model.bone.type.HeldItem;
|
||||
import com.ticxo.modelengine.api.model.bone.type.Segment;
|
||||
import com.ticxo.modelengine.api.model.render.DisplayBone;
|
||||
import com.ticxo.modelengine.api.nms.RenderParsers;
|
||||
import com.ticxo.modelengine.api.nms.entity.EntityHandler;
|
||||
import com.ticxo.modelengine.api.utils.data.PositionCodec;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.DataTracker;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker;
|
||||
import com.ticxo.modelengine.api.utils.math.SafeTransform;
|
||||
import com.ticxo.modelengine.core.model.render.DisplayBoneImpl;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.Map.Entry;
|
||||
import org.bukkit.entity.ItemDisplay.ItemDisplayTransform;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class SegmentRendererImpl extends AbstractBehaviorRenderer implements SegmentRenderer {
|
||||
private final EntityHandler entityHandler;
|
||||
private final Map<String, SegmentRenderer.Pivot> spawnQueue = new HashMap<>();
|
||||
private final Map<String, SegmentRenderer.Pivot> rendered = new HashMap<>();
|
||||
private final Map<String, SegmentRenderer.Pivot> destroyQueue = new HashMap<>();
|
||||
private boolean initialized;
|
||||
private final Map<String, ModelBone> unhandled = new HashMap<>();
|
||||
private final Map<String, SegmentRenderer.SegmentDisplayBone> bones = new HashMap<>();
|
||||
private BehaviorRendererParser<SegmentRenderer> cachedParser;
|
||||
private RenderParsers cachedParserOwner;
|
||||
|
||||
public SegmentRendererImpl(ActiveModel activeModel) {
|
||||
super(activeModel);
|
||||
this.entityHandler = this.nmsHandler.getEntityHandler();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize() {
|
||||
for (Entry<String, ModelBone> entry : this.activeModel.getBones().entrySet()) {
|
||||
this.createPivotOrBone(entry.getKey(), entry.getValue(), this.unhandled);
|
||||
}
|
||||
|
||||
for (Entry<String, ModelBone> entry : this.unhandled.entrySet()) {
|
||||
this.createBone(entry.getKey(), entry.getValue(), null);
|
||||
}
|
||||
|
||||
this.unhandled.clear();
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
private void createPivotOrBone(String boneId, ModelBone modelBone, Map<String, ModelBone> unhandled) {
|
||||
if (!this.createPivot(boneId, modelBone)) {
|
||||
this.createBone(boneId, modelBone, unhandled);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean createPivot(String boneId, ModelBone modelBone) {
|
||||
Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.SEGMENT);
|
||||
if (maybeData.isEmpty()) {
|
||||
return false;
|
||||
} else {
|
||||
BoneBehavior segmentData = (BoneBehavior)maybeData.get();
|
||||
SegmentRendererImpl.PivotImpl pivot = new SegmentRendererImpl.PivotImpl(this.entityHandler.getNextEntityId());
|
||||
pivot.getPosition().set(((Segment)segmentData).getWorldLocation());
|
||||
pivot.getYaw().set(-modelBone.getYaw() * (float) (Math.PI / 180.0));
|
||||
this.spawnQueue.put(boneId, pivot);
|
||||
this.destroyQueue.remove(boneId);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private void createBone(String boneId, ModelBone modelBone, @Nullable Map<String, ModelBone> unhandled) {
|
||||
if (modelBone.isRenderer() && modelBone.getPivot() != null) {
|
||||
SegmentRendererImpl.PivotImpl pivot = this.getPivot(modelBone.getPivot().getUniqueBoneId());
|
||||
if (pivot == null) {
|
||||
if (unhandled != null) {
|
||||
unhandled.put(boneId, modelBone);
|
||||
}
|
||||
} else {
|
||||
SafeTransform transform = modelBone.getGlobalTransform();
|
||||
BoneItems models = modelBone.getModels();
|
||||
SegmentRendererImpl.SegmentDisplayBoneImpl bone = new SegmentRendererImpl.SegmentDisplayBoneImpl(boneId, pivot);
|
||||
bone.getGlowing().set(modelBone.isGlowing());
|
||||
bone.getGlowColor().set(modelBone.getGlowColor());
|
||||
bone.getBrightness().set(modelBone.getBrightness());
|
||||
bone.getBillboard().set(modelBone.getBillboard());
|
||||
bone.getVisibility().set(modelBone.isVisible());
|
||||
bone.getPosition().set(transform.getPosition().rotateY(pivot.yaw.get()));
|
||||
bone.getLeftRotation().set(transform.getLeftQuaternion().rotateLocalY(pivot.yaw.get()));
|
||||
bone.getScale().set(modelBone.isScaleHidden() ? new Vector3f() : transform.getScale());
|
||||
bone.getRightRotation().set(transform.getRightQuaternion());
|
||||
bone.getDisplay().set(ItemDisplayTransform.HEAD);
|
||||
bone.getSnapshotHandler().recordSnapshot();
|
||||
models.forEach((uuid, stack) -> {
|
||||
DisplayBoneImpl.BoneDataImpl data = new DisplayBoneImpl.BoneDataImpl(this.entityHandler.getNextEntityId(), bone);
|
||||
data.getModel().set(stack.clone());
|
||||
bone.getModel().put(uuid, data);
|
||||
pivot.passengers.add(data.getId());
|
||||
});
|
||||
this.initializeSpecialBehaviorRender(modelBone, bone);
|
||||
this.bones.put(boneId, bone);
|
||||
pivot.spawnQueue.put(boneId, bone);
|
||||
pivot.destroyQueue.remove(boneId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void initializeSpecialBehaviorRender(ModelBone modelBone, DisplayBone bone) {
|
||||
modelBone.getBoneBehavior(BoneBehaviorTypes.ITEM).ifPresent(item -> bone.getDisplay().set(((HeldItem)item).getDisplay()));
|
||||
modelBone.getBoneBehavior(BoneBehaviorTypes.PLAYER_LIMB).ifPresent(limb -> bone.getDisplay().set(ItemDisplayTransform.THIRDPERSON_RIGHTHAND));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private SegmentRendererImpl.PivotImpl getPivot(String boneId) {
|
||||
SegmentRenderer.Pivot pivot = this.getQueued(boneId);
|
||||
return pivot instanceof SegmentRendererImpl.PivotImpl impl ? impl : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readBoneData() {
|
||||
if (this.initialized) {
|
||||
this.destroyQueue.putAll(this.rendered);
|
||||
ArrayList<Runnable> boneReadQueue = new ArrayList<>();
|
||||
ArrayList<Runnable> createQueue = new ArrayList<>();
|
||||
|
||||
for (Entry<String, ModelBone> entry : this.activeModel.getBones().entrySet()) {
|
||||
String boneId = entry.getKey();
|
||||
ModelBone modelBone = entry.getValue();
|
||||
SegmentRenderer.Pivot pivot = this.getQueued(boneId);
|
||||
if (pivot != null) {
|
||||
this.readPivotBone(boneId, pivot, modelBone);
|
||||
} else {
|
||||
SegmentRenderer.SegmentDisplayBone displayBone = this.bones.get(boneId);
|
||||
if (displayBone != null) {
|
||||
boneReadQueue.add(() -> this.readDisplayBone(boneId, displayBone, modelBone));
|
||||
} else {
|
||||
createQueue.add(() -> this.createPivotOrBone(boneId, modelBone, this.unhandled));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
boneReadQueue.forEach(Runnable::run);
|
||||
createQueue.forEach(Runnable::run);
|
||||
|
||||
for (Entry<String, ModelBone> entryx : this.unhandled.entrySet()) {
|
||||
this.createBone(entryx.getKey(), entryx.getValue(), null);
|
||||
}
|
||||
|
||||
this.unhandled.clear();
|
||||
this.spawnQueue
|
||||
.forEach(
|
||||
(pivotName, pivotx) -> pivotx.getDestroyQueue().forEach((s, bone) -> bone.getModel().keySet().forEach(id -> pivotx.getPassengers().remove(id)))
|
||||
);
|
||||
this.rendered
|
||||
.forEach(
|
||||
(pivotName, pivotx) -> pivotx.getDestroyQueue().forEach((s, bone) -> bone.getModel().keySet().forEach(id -> pivotx.getPassengers().remove(id)))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private void readPivotBone(String boneId, SegmentRenderer.Pivot pivot, ModelBone modelBone) {
|
||||
Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.SEGMENT);
|
||||
maybeData.ifPresent(segmentData -> {
|
||||
pivot.getPosition().set(((Segment)segmentData).getWorldLocation());
|
||||
pivot.getYaw().set(-modelBone.getYaw() * (float) (Math.PI / 180.0));
|
||||
this.destroyQueue.remove(boneId);
|
||||
});
|
||||
}
|
||||
|
||||
private void readDisplayBone(String boneId, SegmentRenderer.SegmentDisplayBone bone, ModelBone modelBone) {
|
||||
DataTracker<Boolean> shouldRender = bone.getRender();
|
||||
shouldRender.set(!modelBone.isEffectivelyInvisible());
|
||||
SegmentRenderer.Pivot pivot = bone.getPivot();
|
||||
if (shouldRender.get() || shouldRender.isDirty()) {
|
||||
SafeTransform transform = modelBone.getGlobalTransform();
|
||||
bone.getStep().set(modelBone.pollModelScaleChanged() || modelBone.shouldStep() || shouldRender.isDirty());
|
||||
bone.getPosition().set(transform.getPosition().rotateY(pivot.getYaw().get()));
|
||||
bone.getLeftRotation().set(transform.getLeftQuaternion().rotateLocalY(pivot.getYaw().get(), new Quaternionf()));
|
||||
bone.getScale().set(modelBone.isScaleHidden() ? new Vector3f() : transform.getScale());
|
||||
bone.getRightRotation().set(transform.getRightQuaternion());
|
||||
bone.getBillboard().set(modelBone.getBillboard());
|
||||
if (!modelBone.isScaleHidden()) {
|
||||
bone.getVisibility().set(modelBone.isVisible());
|
||||
}
|
||||
|
||||
bone.getGlowing().set(modelBone.isGlowing());
|
||||
bone.getGlowColor().set(modelBone.getGlowColor());
|
||||
bone.getBrightness().set(modelBone.getBrightness());
|
||||
bone.getSnapshotHandler().recordSnapshot();
|
||||
BoneItems models = modelBone.getModels();
|
||||
if (models.isDirty()) {
|
||||
models.clearDirty();
|
||||
((SegmentRendererImpl.SegmentDisplayBoneImpl)bone).updateBoneData(this.entityHandler, pivot.getPassengers(), models);
|
||||
}
|
||||
|
||||
this.updateSpecialBehaviorRender(modelBone, bone);
|
||||
}
|
||||
|
||||
shouldRender.clearDirty();
|
||||
pivot.getDestroyQueue().remove(boneId);
|
||||
}
|
||||
|
||||
private void updateSpecialBehaviorRender(ModelBone modelBone, DisplayBone bone) {
|
||||
modelBone.getBoneBehavior(BoneBehaviorTypes.ITEM).ifPresent(item -> bone.getDisplay().set(((HeldItem)item).getDisplay()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendToClient(RenderParsers parsers) {
|
||||
if (this.initialized) {
|
||||
this.destroyQueue.keySet().forEach(s -> {
|
||||
SegmentRenderer.Pivot pivot = this.rendered.remove(s);
|
||||
if (pivot != null) {
|
||||
pivot.getSpawnQueue().forEach((s1, bone) -> this.bones.remove(s1));
|
||||
pivot.getRendered().forEach((s1, bone) -> this.bones.remove(s1));
|
||||
pivot.getDestroyQueue().forEach((s1, bone) -> this.bones.remove(s1));
|
||||
}
|
||||
});
|
||||
this.parser(parsers).sendToClients(this);
|
||||
this.rendered.putAll(this.spawnQueue);
|
||||
this.spawnQueue.clear();
|
||||
this.destroyQueue.clear();
|
||||
this.rendered.forEach((s, pivot) -> {
|
||||
pivot.getDestroyQueue().forEach((s1, bone) -> {
|
||||
pivot.getRendered().remove(s1);
|
||||
this.bones.remove(s1);
|
||||
});
|
||||
pivot.getRendered().putAll(pivot.getSpawnQueue());
|
||||
pivot.getSpawnQueue().clear();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy(RenderParsers parsers) {
|
||||
if (this.initialized) {
|
||||
parsers.getBehaviorParser(this).destroy(this);
|
||||
}
|
||||
}
|
||||
|
||||
private BehaviorRendererParser<SegmentRenderer> parser(RenderParsers parsers) {
|
||||
if (this.cachedParser == null || this.cachedParserOwner != parsers) {
|
||||
this.cachedParserOwner = parsers;
|
||||
this.cachedParser = parsers.getBehaviorParser(this);
|
||||
}
|
||||
|
||||
return this.cachedParser;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, SegmentRenderer.Pivot> getSpawnQueue() {
|
||||
return this.spawnQueue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, SegmentRenderer.Pivot> getRendered() {
|
||||
return this.rendered;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, SegmentRenderer.Pivot> getDestroyQueue() {
|
||||
return this.destroyQueue;
|
||||
}
|
||||
|
||||
public static class PivotImpl implements SegmentRenderer.Pivot {
|
||||
private final Map<String, SegmentRenderer.SegmentDisplayBone> spawnQueue = new HashMap<>();
|
||||
private final Map<String, SegmentRenderer.SegmentDisplayBone> rendered = new HashMap<>();
|
||||
private final Map<String, SegmentRenderer.SegmentDisplayBone> destroyQueue = new HashMap<>();
|
||||
private final int id;
|
||||
private final UUID uuid = UUID.randomUUID();
|
||||
private final DataTracker<Vector3f> position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set);
|
||||
private final PositionCodec positionCodec = new PositionCodec();
|
||||
private final DataTracker<Float> yaw = new DataTracker<>();
|
||||
private final CollectionDataTracker<Integer> passengers = new CollectionDataTracker<>(new HashSet<>());
|
||||
|
||||
@Override
|
||||
public void clearDirty() {
|
||||
this.yaw.clearDirty();
|
||||
this.passengers.clearDirty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUuid() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getPosition() {
|
||||
return this.position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PositionCodec getPositionCodec() {
|
||||
return this.positionCodec;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Float> getYaw() {
|
||||
return this.yaw;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CollectionDataTracker<Integer> getPassengers() {
|
||||
return this.passengers;
|
||||
}
|
||||
|
||||
public PivotImpl(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, SegmentRenderer.SegmentDisplayBone> getSpawnQueue() {
|
||||
return this.spawnQueue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, SegmentRenderer.SegmentDisplayBone> getRendered() {
|
||||
return this.rendered;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, SegmentRenderer.SegmentDisplayBone> getDestroyQueue() {
|
||||
return this.destroyQueue;
|
||||
}
|
||||
}
|
||||
|
||||
public static class SegmentDisplayBoneImpl extends DisplayBoneImpl implements SegmentRenderer.SegmentDisplayBone {
|
||||
private final SegmentRenderer.Pivot pivot;
|
||||
|
||||
public SegmentDisplayBoneImpl(String boneId, SegmentRenderer.Pivot pivot) {
|
||||
super(boneId);
|
||||
this.pivot = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void updateBoneData(EntityHandler entityHandler, CollectionDataTracker<Integer> passengerCollector, BoneItems boneItems) {
|
||||
super.updateBoneData(entityHandler, passengerCollector, boneItems);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SegmentRenderer.Pivot getPivot() {
|
||||
return this.pivot;
|
||||
}
|
||||
}
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
package com.ticxo.modelengine.core.model.bone.render;
|
||||
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser;
|
||||
import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer;
|
||||
import com.ticxo.modelengine.api.nms.RenderParsers;
|
||||
import com.ticxo.modelengine.api.utils.data.PositionCodec;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.DataTracker;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.Map.Entry;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class SubHitboxRendererImpl extends AbstractBehaviorRenderer implements SubHitboxRenderer {
|
||||
private final Map<String, SubHitboxRenderer.SubHitbox> spawnQueue = new HashMap<>();
|
||||
private final Map<String, SubHitboxRenderer.SubHitbox> rendered = new HashMap<>();
|
||||
private final Map<String, SubHitboxRenderer.SubHitbox> destroyQueue = new HashMap<>();
|
||||
private boolean initialized;
|
||||
private BehaviorRendererParser<SubHitboxRenderer> cachedParser;
|
||||
private RenderParsers cachedParserOwner;
|
||||
|
||||
public SubHitboxRendererImpl(ActiveModel activeModel) {
|
||||
super(activeModel);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize() {
|
||||
for (Entry<String, ModelBone> boneEntry : this.activeModel.getBones().entrySet()) {
|
||||
String boneId = boneEntry.getKey();
|
||||
ModelBone modelBone = boneEntry.getValue();
|
||||
this.create(boneId, modelBone);
|
||||
}
|
||||
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
private void create(String boneId, ModelBone modelBone) {
|
||||
Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.SUB_HITBOX);
|
||||
if (!maybeData.isEmpty()) {
|
||||
BoneBehavior subHitboxData = (BoneBehavior)maybeData.get();
|
||||
if (!((com.ticxo.modelengine.api.model.bone.type.SubHitbox)subHitboxData).isOBB()) {
|
||||
SubHitboxRendererImpl.SubHitboxImpl subHitbox = new SubHitboxRendererImpl.SubHitboxImpl(
|
||||
this.nmsHandler.getEntityHandler().getNextEntityId(),
|
||||
((com.ticxo.modelengine.api.model.bone.type.SubHitbox)subHitboxData).getHitboxId(),
|
||||
UUID.randomUUID(),
|
||||
UUID.randomUUID()
|
||||
);
|
||||
subHitbox.position.set(((com.ticxo.modelengine.api.model.bone.type.SubHitbox)subHitboxData).getLocation());
|
||||
subHitbox.width.set(((com.ticxo.modelengine.api.model.bone.type.SubHitbox)subHitboxData).getDimension().x);
|
||||
subHitbox.height.set(((com.ticxo.modelengine.api.model.bone.type.SubHitbox)subHitboxData).getDimension().y);
|
||||
this.spawnQueue.put(boneId, subHitbox);
|
||||
this.destroyQueue.remove(boneId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readBoneData() {
|
||||
if (this.initialized) {
|
||||
this.destroyQueue.putAll(this.rendered);
|
||||
|
||||
for (Entry<String, ModelBone> boneEntry : this.activeModel.getBones().entrySet()) {
|
||||
String boneId = boneEntry.getKey();
|
||||
ModelBone modelBone = boneEntry.getValue();
|
||||
SubHitboxRenderer.SubHitbox renderer = this.getQueued(boneId);
|
||||
if (renderer != null) {
|
||||
this.read(boneId, renderer, modelBone);
|
||||
} else {
|
||||
this.create(boneId, modelBone);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void read(String boneId, SubHitboxRenderer.SubHitbox subHitbox, ModelBone modelBone) {
|
||||
Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.SUB_HITBOX);
|
||||
maybeData.ifPresent(subHitboxData -> {
|
||||
subHitbox.getPosition().set(((com.ticxo.modelengine.api.model.bone.type.SubHitbox)subHitboxData).getLocation());
|
||||
subHitbox.getWidth().set(((com.ticxo.modelengine.api.model.bone.type.SubHitbox)subHitboxData).getDimension().x);
|
||||
subHitbox.getHeight().set(((com.ticxo.modelengine.api.model.bone.type.SubHitbox)subHitboxData).getDimension().y);
|
||||
this.destroyQueue.remove(boneId);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendToClient(RenderParsers parsers) {
|
||||
if (this.initialized) {
|
||||
this.destroyQueue.keySet().forEach(this.rendered::remove);
|
||||
this.parser(parsers).sendToClients(this);
|
||||
this.rendered.putAll(this.spawnQueue);
|
||||
this.spawnQueue.clear();
|
||||
this.destroyQueue.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy(RenderParsers parsers) {
|
||||
if (this.initialized) {
|
||||
parsers.getBehaviorParser(this).destroy(this);
|
||||
}
|
||||
}
|
||||
|
||||
private BehaviorRendererParser<SubHitboxRenderer> parser(RenderParsers parsers) {
|
||||
if (this.cachedParser == null || this.cachedParserOwner != parsers) {
|
||||
this.cachedParserOwner = parsers;
|
||||
this.cachedParser = parsers.getBehaviorParser(this);
|
||||
}
|
||||
|
||||
return this.cachedParser;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, SubHitboxRenderer.SubHitbox> getSpawnQueue() {
|
||||
return this.spawnQueue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, SubHitboxRenderer.SubHitbox> getRendered() {
|
||||
return this.rendered;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, SubHitboxRenderer.SubHitbox> getDestroyQueue() {
|
||||
return this.destroyQueue;
|
||||
}
|
||||
|
||||
public static class SubHitboxImpl implements SubHitboxRenderer.SubHitbox {
|
||||
private final int pivotId;
|
||||
private final int hitboxId;
|
||||
private final UUID pivotUuid;
|
||||
private final UUID hitboxUuid;
|
||||
private final DataTracker<Vector3f> position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set);
|
||||
private final DataTracker<Float> width = new DataTracker<>();
|
||||
private final DataTracker<Float> height = new DataTracker<>();
|
||||
private final PositionCodec positionCodec = new PositionCodec();
|
||||
|
||||
public SubHitboxImpl(int pivotId, int hitboxId, UUID pivotUuid, UUID hitboxUuid) {
|
||||
this.pivotId = pivotId;
|
||||
this.hitboxId = hitboxId;
|
||||
this.pivotUuid = pivotUuid;
|
||||
this.hitboxUuid = hitboxUuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPivotId() {
|
||||
return this.pivotId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHitboxId() {
|
||||
return this.hitboxId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getPivotUuid() {
|
||||
return this.pivotUuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getHitboxUuid() {
|
||||
return this.hitboxUuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getPosition() {
|
||||
return this.position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Float> getWidth() {
|
||||
return this.width;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Float> getHeight() {
|
||||
return this.height;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PositionCodec getPositionCodec() {
|
||||
return this.positionCodec;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package com.ticxo.modelengine.core.model.render;
|
||||
|
||||
import com.ticxo.modelengine.api.lod.BoneSnapshotHandler;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneItems;
|
||||
import com.ticxo.modelengine.api.model.render.DisplayBone;
|
||||
import com.ticxo.modelengine.api.nms.entity.EntityHandler;
|
||||
import com.ticxo.modelengine.api.utils.data.UpdateScheme;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.DataTracker;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.QuaternionfDataTracker;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.Vector3fDataTracker;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.ints.IntIterator;
|
||||
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
|
||||
import it.unimi.dsi.fastutil.ints.IntSet;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.entity.Display.Billboard;
|
||||
import org.bukkit.entity.ItemDisplay.ItemDisplayTransform;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class DisplayBoneImpl implements DisplayBone {
|
||||
private final String boneId;
|
||||
private final BoneSnapshotHandler snapshotHandler = new BoneSnapshotHandler(this);
|
||||
private final DataTracker<Boolean> render = new DataTracker<>(true);
|
||||
private final DataTracker<Boolean> step = new DataTracker<>(false);
|
||||
private final DataTracker<Vector3f> position = new Vector3fDataTracker();
|
||||
private final DataTracker<Quaternionf> leftRotation = new QuaternionfDataTracker();
|
||||
private final DataTracker<Vector3f> scale = new Vector3fDataTracker();
|
||||
private final DataTracker<Quaternionf> rightRotation = new QuaternionfDataTracker();
|
||||
private final DataTracker<Billboard> billboard = new DataTracker<>(Billboard.FIXED);
|
||||
private final DataTracker<ItemDisplayTransform> display = new DataTracker<>(ItemDisplayTransform.NONE);
|
||||
private final DataTracker<Boolean> visibility = new DataTracker<>(true);
|
||||
private final DataTracker<Boolean> glowing = new DataTracker<>(false);
|
||||
private final DataTracker<Integer> glowColor = new DataTracker<>(-1);
|
||||
private final DataTracker<Integer> brightness = new DataTracker<>(-1);
|
||||
private final DataTracker<Set<UUID>> glowAudience = new DataTracker<>();
|
||||
private final DataTracker<Boolean> audienceGlowing = new DataTracker<>(false);
|
||||
private final DataTracker<Integer> audienceGlowColor = new DataTracker<>(-1);
|
||||
private final Int2ObjectMap<DisplayBone.BoneData> model = new Int2ObjectOpenHashMap();
|
||||
private final UpdateScheme<DisplayBone.BoneData> modelUpdateScheme = new UpdateScheme<>();
|
||||
|
||||
protected void updateBoneData(EntityHandler entityHandler, CollectionDataTracker<Integer> passengerCollector, BoneItems boneItems) {
|
||||
Map<Integer, ItemStack> newItems = boneItems.getItems();
|
||||
IntSet oldKeys = this.model.keySet();
|
||||
IntOpenHashSet added = new IntOpenHashSet(newItems.keySet());
|
||||
IntOpenHashSet removed = new IntOpenHashSet(oldKeys);
|
||||
removed.removeAll(added);
|
||||
added.removeAll(oldKeys);
|
||||
HashSet<DisplayBone.BoneData> reusableData = new HashSet<>();
|
||||
IntIterator it = removed.iterator();
|
||||
|
||||
while (it.hasNext()) {
|
||||
reusableData.add((DisplayBone.BoneData)this.model.remove(it.nextInt()));
|
||||
}
|
||||
|
||||
Iterator<DisplayBone.BoneData> iterator = reusableData.iterator();
|
||||
IntIterator itx = added.iterator();
|
||||
|
||||
while (itx.hasNext()) {
|
||||
int hash = itx.nextInt();
|
||||
ItemStack stack = newItems.get(hash).clone();
|
||||
if (iterator.hasNext()) {
|
||||
DisplayBone.BoneData data = iterator.next();
|
||||
int oldHash = data.getModelHash();
|
||||
data.getModel().set(stack);
|
||||
this.modelUpdateScheme.addUpdated(data);
|
||||
this.model.remove(oldHash);
|
||||
this.model.put(hash, data);
|
||||
} else {
|
||||
DisplayBoneImpl.BoneDataImpl data = new DisplayBoneImpl.BoneDataImpl(entityHandler.getNextEntityId(), this);
|
||||
data.getModel().set(stack);
|
||||
this.model.put(hash, data);
|
||||
this.modelUpdateScheme.addAdded(data);
|
||||
passengerCollector.add(data.getId());
|
||||
}
|
||||
}
|
||||
|
||||
while (iterator.hasNext()) {
|
||||
DisplayBone.BoneData data = iterator.next();
|
||||
this.modelUpdateScheme.addRemove(data);
|
||||
passengerCollector.remove(data.getId());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBoneId() {
|
||||
return this.boneId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BoneSnapshotHandler getSnapshotHandler() {
|
||||
return this.snapshotHandler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Boolean> getRender() {
|
||||
return this.render;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Boolean> getStep() {
|
||||
return this.step;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getPosition() {
|
||||
return this.position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Quaternionf> getLeftRotation() {
|
||||
return this.leftRotation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getScale() {
|
||||
return this.scale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Quaternionf> getRightRotation() {
|
||||
return this.rightRotation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Billboard> getBillboard() {
|
||||
return this.billboard;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<ItemDisplayTransform> getDisplay() {
|
||||
return this.display;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Boolean> getVisibility() {
|
||||
return this.visibility;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Boolean> getGlowing() {
|
||||
return this.glowing;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Integer> getGlowColor() {
|
||||
return this.glowColor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Integer> getBrightness() {
|
||||
return this.brightness;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Set<UUID>> getGlowAudience() {
|
||||
return this.glowAudience;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Boolean> getAudienceGlowing() {
|
||||
return this.audienceGlowing;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Integer> getAudienceGlowColor() {
|
||||
return this.audienceGlowColor;
|
||||
}
|
||||
|
||||
public Int2ObjectMap<DisplayBone.BoneData> getModel() {
|
||||
return this.model;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateScheme<DisplayBone.BoneData> getModelUpdateScheme() {
|
||||
return this.modelUpdateScheme;
|
||||
}
|
||||
|
||||
public DisplayBoneImpl(String boneId) {
|
||||
this.boneId = boneId;
|
||||
}
|
||||
|
||||
public static class BoneDataImpl implements DisplayBone.BoneData {
|
||||
private final int id;
|
||||
private final UUID uuid = UUID.randomUUID();
|
||||
private final DisplayBone bone;
|
||||
private final DataTracker<ItemStack> model = new DataTracker<>();
|
||||
|
||||
@Override
|
||||
public boolean equals(Object object) {
|
||||
if (object != null && this.getClass() == object.getClass()) {
|
||||
DisplayBoneImpl.BoneDataImpl boneData = (DisplayBoneImpl.BoneDataImpl)object;
|
||||
return Objects.equals(this.model, boneData.model);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(this.model);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getModelHash() {
|
||||
return this.model.get().hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUuid() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DisplayBone getBone() {
|
||||
return this.bone;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<ItemStack> getModel() {
|
||||
return this.model;
|
||||
}
|
||||
|
||||
public BoneDataImpl(int id, DisplayBone bone) {
|
||||
this.id = id;
|
||||
this.bone = bone;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.ticxo.modelengine.core.model.render;
|
||||
|
||||
import com.ticxo.modelengine.api.model.render.DisplayFire;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.DataTracker;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class DisplayFireImpl implements DisplayFire {
|
||||
private final int id;
|
||||
private final UUID uuid = UUID.randomUUID();
|
||||
private final DataTracker<Vector3f> position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set, Vector3f::new);
|
||||
private final DataTracker<Vector3f> scale = new UpdateDataTracker<>(new Vector3f(), Vector3f::set, Vector3f::new);
|
||||
private final DataTracker<ItemStack> fireModel = new DataTracker<>(new ItemStack(Material.AIR), ItemStack::isSimilar);
|
||||
private final DataTracker<Boolean> visible = new DataTracker<>(false);
|
||||
|
||||
@Override
|
||||
public void clearDirty() {
|
||||
this.position.clearDirty();
|
||||
this.scale.clearDirty();
|
||||
this.fireModel.clearDirty();
|
||||
this.visible.clearDirty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUuid() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getPosition() {
|
||||
return this.position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getScale() {
|
||||
return this.scale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<ItemStack> getFireModel() {
|
||||
return this.fireModel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Boolean> getVisible() {
|
||||
return this.visible;
|
||||
}
|
||||
|
||||
public DisplayFireImpl(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,796 @@
|
||||
package com.ticxo.modelengine.core.model.render;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.ServerInfo;
|
||||
import com.ticxo.modelengine.api.entity.BaseEntity;
|
||||
import com.ticxo.modelengine.api.events.BoneTransformReadEvent;
|
||||
import com.ticxo.modelengine.api.generator.assets.ItemModelData;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone;
|
||||
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
|
||||
import com.ticxo.modelengine.api.model.ActiveModel;
|
||||
import com.ticxo.modelengine.api.model.ModeledEntity;
|
||||
import com.ticxo.modelengine.api.model.PivotOverride;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes;
|
||||
import com.ticxo.modelengine.api.model.bone.BoneItems;
|
||||
import com.ticxo.modelengine.api.model.bone.ModelBone;
|
||||
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior;
|
||||
import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager;
|
||||
import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer;
|
||||
import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer;
|
||||
import com.ticxo.modelengine.api.model.bone.type.HeldItem;
|
||||
import com.ticxo.modelengine.api.model.render.DisplayBone;
|
||||
import com.ticxo.modelengine.api.model.render.DisplayFire;
|
||||
import com.ticxo.modelengine.api.model.render.DisplayRenderer;
|
||||
import com.ticxo.modelengine.api.model.render.ModelRendererParser;
|
||||
import com.ticxo.modelengine.api.nms.RenderParsers;
|
||||
import com.ticxo.modelengine.api.nms.entity.EntityHandler;
|
||||
import com.ticxo.modelengine.api.utils.data.PooledCollection;
|
||||
import com.ticxo.modelengine.api.utils.data.PositionCodec;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.DataTracker;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker;
|
||||
import com.ticxo.modelengine.api.utils.math.SafeTransform;
|
||||
import com.ticxo.modelengine.api.utils.math.TMath;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Queue;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Consumer;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.ItemDisplay;
|
||||
import org.bukkit.entity.ItemDisplay.ItemDisplayTransform;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.util.Transformation;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
import org.joml.Vector3fc;
|
||||
|
||||
public class DisplayRendererImpl implements DisplayRenderer {
|
||||
private final ActiveModel activeModel;
|
||||
private final EntityHandler entityHandler;
|
||||
private final Map<String, DisplayBone> spawnQueue = new HashMap<>();
|
||||
private final Map<String, DisplayBone> rendered = new HashMap<>();
|
||||
private final Map<String, DisplayBone> destroyQueue = new HashMap<>();
|
||||
private final Set<UUID> fullUpdate = new HashSet<>();
|
||||
private final AtomicInteger glowAudienceBones = new AtomicInteger();
|
||||
private final Vector3f scratchPosition = new Vector3f();
|
||||
private final Vector3f scratchScale = new Vector3f();
|
||||
private final Quaternionf scratchLeft = new Quaternionf();
|
||||
private final Quaternionf scratchRight = new Quaternionf();
|
||||
private final Quaternionf scratchRotated = new Quaternionf();
|
||||
private boolean trigValid;
|
||||
private int trigYawBits;
|
||||
private float yawSin;
|
||||
private float yawCos;
|
||||
private float halfYawSin;
|
||||
private float halfYawCos;
|
||||
private DisplayRendererImpl.PivotImpl pivot;
|
||||
private DisplayRendererImpl.HitboxImpl hitbox;
|
||||
private boolean initialized;
|
||||
private boolean firstSpawned;
|
||||
private final Queue<Runnable> queuedTasks = new ConcurrentLinkedQueue<>();
|
||||
private ModelRendererParser<DisplayRenderer> cachedParser;
|
||||
private RenderParsers cachedParserOwner;
|
||||
|
||||
public DisplayRendererImpl(ActiveModel activeModel) {
|
||||
this.activeModel = activeModel;
|
||||
this.entityHandler = ModelEngineAPI.getEntityHandler();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updatePivotOverride(PivotOverride override) {
|
||||
if (this.initialized) {
|
||||
this.updatePivotOverride0(override);
|
||||
} else {
|
||||
this.queuedTasks.add(() -> this.updatePivotOverride0(override));
|
||||
}
|
||||
}
|
||||
|
||||
private void updatePivotOverride0(PivotOverride override) {
|
||||
this.activeModel.getPivotOverride().ifPresent(old -> old.removePassenger(this.pivot.id));
|
||||
if (override != null) {
|
||||
override.addPassenger(this.pivot.id);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize() {
|
||||
ModeledEntity model = this.activeModel.getModeledEntity();
|
||||
BaseEntity<?> base = model.getBase();
|
||||
Location location = base.getLocation();
|
||||
ModelBlueprint blueprint = this.activeModel.getBlueprint();
|
||||
Vector3fc scale = this.activeModel.getScale();
|
||||
Vector3fc hitboxScale = this.activeModel.getHitboxScale();
|
||||
com.ticxo.modelengine.api.entity.Hitbox mainHitbox = blueprint.getMainHitbox();
|
||||
float scaledEyeHeight = (float)mainHitbox.getEyeHeight() * scale.y();
|
||||
float scaledHeight = (float)mainHitbox.getHeight() * hitboxScale.y();
|
||||
float scaledWidth = (float)mainHitbox.getMaxWidth() * hitboxScale.x();
|
||||
this.pivot = new DisplayRendererImpl.PivotImpl(this.entityHandler.getNextEntityId());
|
||||
this.pivot.pivotOverride = this.activeModel.getPivotOverride().orElse(null);
|
||||
this.updateCameraPivot();
|
||||
this.pivot.updatePosition(location, scaledEyeHeight);
|
||||
this.pivot.getYaw().set(this.pivot.cameraEye != null ? 0.0F : -this.activeModel.getYBodyRot() * (float) (Math.PI / 180.0));
|
||||
Vector3f initialOffset = this.pivot.getMountOffset(scaledEyeHeight);
|
||||
|
||||
for (Entry<String, ModelBone> entry : this.activeModel.getBones().entrySet()) {
|
||||
this.create(entry.getKey(), entry.getValue(), initialOffset);
|
||||
}
|
||||
|
||||
this.forBehaviorRenderer(behaviorRenderer -> {
|
||||
behaviorRenderer.setModelRenderer(this);
|
||||
behaviorRenderer.initialize();
|
||||
});
|
||||
this.hitbox = new DisplayRendererImpl.HitboxImpl(
|
||||
this.entityHandler.getNextEntityId(), this.entityHandler.getNextEntityId(), this.entityHandler.getNextEntityId()
|
||||
);
|
||||
this.hitbox.updatePosition(location);
|
||||
this.hitbox.getHeight().set(scaledHeight);
|
||||
this.hitbox.getWidth().set(scaledWidth);
|
||||
this.hitbox.getShadowRadius().set(blueprint.getShadowRadius() * scale.x());
|
||||
this.hitbox.getHitboxVisible().set(this.activeModel.isHitboxVisible());
|
||||
this.hitbox.getShadowVisible().set(this.activeModel.isShadowVisible());
|
||||
this.hitbox.getFireVisible().set(this.activeModel.canRenderFire());
|
||||
if (this.hitbox.isHitboxDirty() || this.hitbox.getFireVisible().isDirty()) {
|
||||
this.hitbox.updateFireDisplay();
|
||||
}
|
||||
|
||||
this.hitbox.setOnFire(this.activeModel.isOnFire());
|
||||
ModelEngineAPI.getInteractionTracker().setModelRelay(this.hitbox.hitboxId, this.activeModel);
|
||||
this.initialized = true;
|
||||
this.firstSpawned = true;
|
||||
|
||||
while (!this.queuedTasks.isEmpty()) {
|
||||
this.queuedTasks.poll().run();
|
||||
}
|
||||
}
|
||||
|
||||
private void updateCameraPivot() {
|
||||
Float eye = null;
|
||||
Float height = null;
|
||||
if (this.activeModel.isCameraPivot()
|
||||
&& this.pivot.pivotOverride != null
|
||||
&& this.activeModel.getModeledEntity().getBase().getOriginal() instanceof Entity entity) {
|
||||
eye = this.entityHandler.getCameraEyeHeight(entity);
|
||||
height = this.entityHandler.getCameraPivotHeight(entity);
|
||||
if (eye == null || height == null) {
|
||||
eye = null;
|
||||
height = null;
|
||||
}
|
||||
}
|
||||
|
||||
this.pivot.cameraEye = eye;
|
||||
if (height != null || this.pivot.cameraHeight.get() != null) {
|
||||
this.pivot.cameraHeight.set(height);
|
||||
}
|
||||
}
|
||||
|
||||
private void create(String boneId, ModelBone modelBone, Vector3f offset) {
|
||||
if (modelBone.isRenderer() && modelBone.getPivot() == null) {
|
||||
BoneItems models = modelBone.getModels();
|
||||
DisplayBoneImpl bone = new DisplayBoneImpl(boneId);
|
||||
this.applyGlow(bone, modelBone);
|
||||
bone.getBrightness().set(modelBone.getBrightness());
|
||||
bone.getBillboard().set(modelBone.getBillboard());
|
||||
bone.getVisibility().set(modelBone.isVisible());
|
||||
SafeTransform transform = modelBone.getGlobalTransform();
|
||||
BoneTransformReadEvent event = new BoneTransformReadEvent(
|
||||
modelBone, transform.getPosition(), transform.getLeftQuaternion(), transform.getScale(), transform.getRightQuaternion()
|
||||
);
|
||||
Bukkit.getPluginManager().callEvent(event);
|
||||
modelBone.forBehaviors(boneBehavior -> boneBehavior.modifyTransform(event));
|
||||
bone.getPosition().set(event.getPosition().rotateY(this.pivot.yaw.get()).sub(offset));
|
||||
bone.getLeftRotation().set(event.getLeftRotation().rotateLocalY(this.pivot.yaw.get()));
|
||||
bone.getScale().set(modelBone.isScaleHidden() ? new Vector3f() : TMath.zerofyScale(event.getScale()));
|
||||
bone.getRightRotation().set(event.getRightRotation());
|
||||
bone.getDisplay().set(ItemDisplayTransform.HEAD);
|
||||
bone.getSnapshotHandler().recordSnapshot();
|
||||
models.forEach((uuid, stack) -> {
|
||||
DisplayBoneImpl.BoneDataImpl data = new DisplayBoneImpl.BoneDataImpl(this.entityHandler.getNextEntityId(), bone);
|
||||
data.getModel().set(stack.clone());
|
||||
bone.getModel().put(uuid, data);
|
||||
this.pivot.passengers.add(data.getId());
|
||||
});
|
||||
this.initializeSpecialBehaviorRender(modelBone, bone);
|
||||
this.spawnQueue.put(boneId, bone);
|
||||
this.destroyQueue.remove(boneId);
|
||||
}
|
||||
}
|
||||
|
||||
private void initializeSpecialBehaviorRender(ModelBone modelBone, DisplayBone bone) {
|
||||
modelBone.getBoneBehavior(BoneBehaviorTypes.ITEM).ifPresent(item -> bone.getDisplay().set(((HeldItem)item).getDisplay()));
|
||||
modelBone.getBoneBehavior(BoneBehaviorTypes.PLAYER_LIMB).ifPresent(limb -> bone.getDisplay().set(ItemDisplayTransform.THIRDPERSON_RIGHTHAND));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readModelData() {
|
||||
if (this.initialized) {
|
||||
ModeledEntity model = this.activeModel.getModeledEntity();
|
||||
BaseEntity<?> base = model.getBase();
|
||||
Location location = base.getLocation();
|
||||
ModelBlueprint blueprint = this.activeModel.getBlueprint();
|
||||
Vector3fc scale = this.activeModel.getScale();
|
||||
Vector3fc hitboxScale = this.activeModel.getHitboxScale();
|
||||
com.ticxo.modelengine.api.entity.Hitbox mainHitbox = blueprint.getMainHitbox();
|
||||
float scaledEyeHeight = (float)mainHitbox.getEyeHeight() * scale.y();
|
||||
float scaledHeight = (float)mainHitbox.getHeight() * hitboxScale.y();
|
||||
float scaledWidth = (float)mainHitbox.getMaxWidth() * hitboxScale.x();
|
||||
this.pivot.pivotOverride = this.activeModel.getPivotOverride().orElse(null);
|
||||
this.updateCameraPivot();
|
||||
this.pivot.updatePosition(location, scaledEyeHeight);
|
||||
this.pivot.getYaw().set(this.pivot.cameraEye != null ? 0.0F : -this.activeModel.getYBodyRot() * (float) (Math.PI / 180.0));
|
||||
Vector3f offset = this.pivot.getMountOffset(scaledEyeHeight);
|
||||
boolean hasTransformListeners = BoneTransformReadEvent.getHandlerList().getRegisteredListeners().length > 0;
|
||||
Map<String, ModelBone> bones = this.activeModel.getBones();
|
||||
|
||||
for (Entry<String, ModelBone> entry : bones.entrySet()) {
|
||||
DisplayBone bone = this.getQueued(entry.getKey());
|
||||
if (bone == null) {
|
||||
this.create(entry.getKey(), entry.getValue(), offset);
|
||||
} else {
|
||||
this.read(entry.getKey(), bone, entry.getValue(), offset, hasTransformListeners);
|
||||
}
|
||||
}
|
||||
|
||||
for (Entry<String, DisplayBone> entryx : this.rendered.entrySet()) {
|
||||
if (!bones.containsKey(entryx.getKey()) && !this.spawnQueue.containsKey(entryx.getKey())) {
|
||||
this.destroyQueue.put(entryx.getKey(), entryx.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
for (DisplayBone bone : this.destroyQueue.values()) {
|
||||
for (DisplayBone.BoneData boneData : bone.getModel().values()) {
|
||||
this.pivot.passengers.remove(boneData.getId());
|
||||
}
|
||||
}
|
||||
|
||||
this.forBehaviorRenderer(BehaviorRenderer::readBoneData);
|
||||
this.hitbox.updatePosition(location);
|
||||
this.hitbox.getHeight().set(scaledHeight);
|
||||
this.hitbox.getWidth().set(scaledWidth);
|
||||
this.hitbox.getShadowRadius().set(blueprint.getShadowRadius() * scale.x());
|
||||
this.hitbox.getHitboxVisible().set(this.activeModel.isHitboxVisible());
|
||||
this.hitbox.getShadowVisible().set(this.activeModel.isShadowVisible());
|
||||
this.hitbox.getFireVisible().set(this.activeModel.canRenderFire());
|
||||
if (this.hitbox.isHitboxDirty() || this.hitbox.getFireVisible().isDirty()) {
|
||||
this.hitbox.updateFireDisplay();
|
||||
}
|
||||
|
||||
this.hitbox.setOnFire(this.activeModel.isOnFire());
|
||||
}
|
||||
}
|
||||
|
||||
private void read(String boneId, DisplayBone bone, ModelBone modelBone, Vector3f offset, boolean hasTransformListeners) {
|
||||
DataTracker<Boolean> shouldRender = bone.getRender();
|
||||
shouldRender.set(!modelBone.isEffectivelyInvisible());
|
||||
if (shouldRender.get() || shouldRender.isDirty()) {
|
||||
bone.getStep().set(modelBone.pollModelScaleChanged() || modelBone.shouldStep() || shouldRender.isDirty());
|
||||
SafeTransform transform = modelBone.getGlobalTransform();
|
||||
float yaw = this.pivot.yaw.get();
|
||||
int yawBits = Float.floatToRawIntBits(yaw);
|
||||
if (!this.trigValid || yawBits != this.trigYawBits) {
|
||||
this.trigYawBits = yawBits;
|
||||
this.trigValid = true;
|
||||
this.yawSin = org.joml.Math.sin(yaw);
|
||||
this.yawCos = org.joml.Math.cosFromSin(this.yawSin, yaw);
|
||||
float halfYaw = yaw * 0.5F;
|
||||
this.halfYawSin = org.joml.Math.sin(halfYaw);
|
||||
this.halfYawCos = org.joml.Math.cosFromSin(this.halfYawSin, halfYaw);
|
||||
}
|
||||
|
||||
if (!hasTransformListeners && !modelBone.hasBoneBehaviors()) {
|
||||
bone.getPosition().set(rotateY(transform.getPosition(this.scratchPosition), this.yawSin, this.yawCos).sub(offset));
|
||||
bone.getLeftRotation().set(rotateLocalY(transform.getLeftQuaternion(this.scratchLeft), this.halfYawSin, this.halfYawCos, this.scratchRotated));
|
||||
bone.getScale().set(TMath.zerofyScale(transform.getScale(this.scratchScale), this.scratchScale));
|
||||
bone.getRightRotation().set(transform.getRightQuaternion(this.scratchRight));
|
||||
} else {
|
||||
BoneTransformReadEvent event = new BoneTransformReadEvent(
|
||||
modelBone, transform.getPosition(), transform.getLeftQuaternion(), transform.getScale(), transform.getRightQuaternion()
|
||||
);
|
||||
if (hasTransformListeners) {
|
||||
Bukkit.getPluginManager().callEvent(event);
|
||||
}
|
||||
|
||||
modelBone.forBehaviors(boneBehavior -> boneBehavior.modifyTransform(event));
|
||||
bone.getPosition().set(rotateY(event.getPosition(), this.yawSin, this.yawCos).sub(offset));
|
||||
bone.getLeftRotation().set(rotateLocalY(event.getLeftRotation(), this.halfYawSin, this.halfYawCos, this.scratchRotated));
|
||||
bone.getScale().set(TMath.zerofyScale(event.getScale()));
|
||||
bone.getRightRotation().set(event.getRightRotation());
|
||||
}
|
||||
|
||||
if (modelBone.isScaleHidden()) {
|
||||
bone.getScale().set(this.scratchScale.zero());
|
||||
}
|
||||
|
||||
bone.getBillboard().set(modelBone.getBillboard());
|
||||
if (!modelBone.isScaleHidden()) {
|
||||
bone.getVisibility().set(modelBone.isVisible());
|
||||
}
|
||||
|
||||
this.applyGlow(bone, modelBone);
|
||||
bone.getBrightness().set(modelBone.getBrightness());
|
||||
bone.getSnapshotHandler().recordSnapshot();
|
||||
BoneItems models = modelBone.getModels();
|
||||
if (models.isDirty()) {
|
||||
models.clearDirty();
|
||||
((DisplayBoneImpl)bone).updateBoneData(this.entityHandler, this.pivot.getPassengers(), models);
|
||||
}
|
||||
|
||||
this.updateSpecialBehaviorRender(modelBone, bone);
|
||||
}
|
||||
|
||||
shouldRender.clearDirty();
|
||||
}
|
||||
|
||||
private static Vector3f rotateY(Vector3f vector, float sin, float cos) {
|
||||
float x = vector.x * cos + vector.z * sin;
|
||||
float z = -vector.x * sin + vector.z * cos;
|
||||
vector.x = x;
|
||||
vector.z = z;
|
||||
return vector;
|
||||
}
|
||||
|
||||
private static Quaternionf rotateLocalY(Quaternionf quaternion, float sin, float cos, Quaternionf dest) {
|
||||
return dest.set(
|
||||
cos * quaternion.x + sin * quaternion.z,
|
||||
cos * quaternion.y + sin * quaternion.w,
|
||||
cos * quaternion.z - sin * quaternion.x,
|
||||
cos * quaternion.w - sin * quaternion.y
|
||||
);
|
||||
}
|
||||
|
||||
private void updateSpecialBehaviorRender(ModelBone modelBone, DisplayBone bone) {
|
||||
modelBone.getBoneBehavior(BoneBehaviorTypes.ITEM).ifPresent(item -> bone.getDisplay().set(((HeldItem)item).getDisplay()));
|
||||
}
|
||||
|
||||
private void applyGlow(DisplayBone bone, ModelBone modelBone) {
|
||||
Set<UUID> audience = modelBone.getGlowAudience();
|
||||
DataTracker<Set<UUID>> audienceTracker = bone.getGlowAudience();
|
||||
Set<UUID> previousAudience = audienceTracker.get();
|
||||
if (!Objects.equals(previousAudience, audience)) {
|
||||
if (previousAudience == null) {
|
||||
this.glowAudienceBones.incrementAndGet();
|
||||
} else if (audience == null) {
|
||||
this.glowAudienceBones.decrementAndGet();
|
||||
}
|
||||
|
||||
audienceTracker.set(audience);
|
||||
}
|
||||
|
||||
if (audience == null) {
|
||||
bone.getGlowing().set(modelBone.isGlowing());
|
||||
bone.getGlowColor().set(modelBone.getGlowColor());
|
||||
bone.getAudienceGlowing().set(false);
|
||||
} else {
|
||||
bone.getGlowing().set(false);
|
||||
bone.getAudienceGlowing().set(modelBone.isGlowing());
|
||||
bone.getAudienceGlowColor().set(modelBone.getGlowColor());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendToClient(RenderParsers parsers) {
|
||||
if (this.initialized) {
|
||||
this.forManagers(BehaviorManager::preBoneRender);
|
||||
this.forBehavior(BoneBehavior::preRender);
|
||||
|
||||
for (String boneId : this.destroyQueue.keySet()) {
|
||||
DisplayBone removed = this.rendered.remove(boneId);
|
||||
if (removed != null && removed.getGlowAudience().get() != null) {
|
||||
this.glowAudienceBones.decrementAndGet();
|
||||
}
|
||||
}
|
||||
|
||||
this.activeModel.getPreSendCallback().invoker().run();
|
||||
this.parser(parsers).sendToClients(this);
|
||||
this.activeModel.getPostSendCallback().invoker().run();
|
||||
this.rendered.putAll(this.spawnQueue);
|
||||
this.spawnQueue.clear();
|
||||
this.destroyQueue.clear();
|
||||
this.forBehaviorRenderer(behaviorRenderer -> behaviorRenderer.sendToClient(parsers));
|
||||
this.forBehavior(BoneBehavior::onRender);
|
||||
this.forBehavior(BoneBehavior::postRender);
|
||||
this.forManagers(BehaviorManager::postBoneRender);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy(RenderParsers parsers) {
|
||||
if (this.initialized) {
|
||||
this.forBehaviorRenderer(behaviorRenderer -> behaviorRenderer.destroy(parsers));
|
||||
parsers.getModelParser(this).destroy(this);
|
||||
ModelEngineAPI.getInteractionTracker().removeModelRelay(this.hitbox.hitboxId);
|
||||
this.activeModel.getPivotOverride().ifPresent(override -> {
|
||||
ModeledEntity model = this.activeModel.getModeledEntity();
|
||||
if (model != null) {
|
||||
List<Entity> basePassengers = model.getBase().getPassengers();
|
||||
int[] snapshot = new int[basePassengers.size()];
|
||||
int i = 0;
|
||||
|
||||
for (Entity passenger : basePassengers) {
|
||||
snapshot[i++] = passenger.getEntityId();
|
||||
}
|
||||
|
||||
override.setBasePassengerSnapshot(snapshot);
|
||||
}
|
||||
|
||||
override.removePassenger(this.pivot.id);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void createRealEntities() {
|
||||
World world = this.activeModel.getModeledEntity().getBase().getLocation().getWorld();
|
||||
if (world != null) {
|
||||
Vector3f pos = this.pivot.getPosition().get();
|
||||
Location location = new Location(world, pos.x, pos.y, pos.z);
|
||||
|
||||
for (DisplayBone bone : this.rendered.values()) {
|
||||
for (DisplayBone.BoneData boneData : bone.getModel().values()) {
|
||||
world.spawn(location, ItemDisplay.class, itemDisplay -> {
|
||||
Quaternionf rotation = bone.getLeftRotation().get();
|
||||
if (ServerInfo.VERSION_NUMBER <= 19) {
|
||||
rotation = rotation.rotateY((float) Math.PI, new Quaternionf());
|
||||
}
|
||||
|
||||
itemDisplay.setTransformation(new Transformation(bone.getPosition().get(), rotation, bone.getScale().get(), new Quaternionf()));
|
||||
itemDisplay.setItemStack(boneData.getModel().get().clone());
|
||||
itemDisplay.setItemDisplayTransform(bone.getDisplay().get());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean pollFirstSpawn() {
|
||||
if (!this.firstSpawned) {
|
||||
return false;
|
||||
} else {
|
||||
this.firstSpawned = false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasGlowAudience() {
|
||||
return this.glowAudienceBones.get() > 0;
|
||||
}
|
||||
|
||||
private void forManagers(Consumer<BehaviorManager<?>> consumer) {
|
||||
for (BehaviorManager<?> manager : this.activeModel.getBehaviorManagers().values()) {
|
||||
consumer.accept(manager);
|
||||
}
|
||||
}
|
||||
|
||||
private void forBehavior(Consumer<BoneBehavior> consumer) {
|
||||
Map<String, ModelBone> bones = this.activeModel.getBones();
|
||||
|
||||
for (String boneId : this.activeModel.getBlueprint().getBones().keySet()) {
|
||||
ModelBone bone = bones.get(boneId);
|
||||
if (bone != null) {
|
||||
bone.forBehaviors(consumer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void forBehaviorRenderer(Consumer<BehaviorRenderer> consumer) {
|
||||
for (BehaviorRenderer renderer : this.activeModel.getBehaviorRenderers().values()) {
|
||||
if (!(renderer instanceof HeldItemRenderer)) {
|
||||
consumer.accept(renderer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTick() {
|
||||
return this.activeModel.getModeledEntity().getTick();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pushFullUpdate(UUID uuid) {
|
||||
this.fullUpdate.add(uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean pollFullUpdate(UUID uuid) {
|
||||
return this.fullUpdate.remove(uuid);
|
||||
}
|
||||
|
||||
private ModelRendererParser<DisplayRenderer> parser(RenderParsers parsers) {
|
||||
if (this.cachedParser == null || this.cachedParserOwner != parsers) {
|
||||
this.cachedParserOwner = parsers;
|
||||
this.cachedParser = parsers.getModelParser(this);
|
||||
}
|
||||
|
||||
return this.cachedParser;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActiveModel getActiveModel() {
|
||||
return this.activeModel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, DisplayBone> getSpawnQueue() {
|
||||
return this.spawnQueue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, DisplayBone> getRendered() {
|
||||
return this.rendered;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, DisplayBone> getDestroyQueue() {
|
||||
return this.destroyQueue;
|
||||
}
|
||||
|
||||
public DisplayRendererImpl.PivotImpl getPivot() {
|
||||
return this.pivot;
|
||||
}
|
||||
|
||||
public DisplayRendererImpl.HitboxImpl getHitbox() {
|
||||
return this.hitbox;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInitialized() {
|
||||
return this.initialized;
|
||||
}
|
||||
|
||||
public class HitboxImpl implements DisplayRenderer.Hitbox {
|
||||
private final int pivotId;
|
||||
private final UUID pivotUuid = UUID.randomUUID();
|
||||
private final int hitboxId;
|
||||
private final UUID hitboxUuid = UUID.randomUUID();
|
||||
private final int shadowId;
|
||||
private final UUID shadowUuid = UUID.randomUUID();
|
||||
private final DataTracker<Vector3f> position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set);
|
||||
private final PositionCodec positionCodec = new PositionCodec();
|
||||
private final DataTracker<Float> width = new DataTracker<>();
|
||||
private final DataTracker<Float> height = new DataTracker<>();
|
||||
private final DataTracker<Float> shadowRadius = new DataTracker<>();
|
||||
private final DataTracker<Boolean> hitboxVisible = new DataTracker<>();
|
||||
private final DataTracker<Boolean> shadowVisible = new DataTracker<>();
|
||||
private final DataTracker<Boolean> fireVisible = new DataTracker<>();
|
||||
private final DataTracker<Boolean> onFire = new DataTracker<>();
|
||||
private final PooledCollection<DisplayFire> fireDisplay = new PooledCollection<>(
|
||||
() -> new DisplayFireImpl(DisplayRendererImpl.this.entityHandler.getNextEntityId())
|
||||
);
|
||||
|
||||
public void updatePosition(Location location) {
|
||||
this.position.set(new Vector3f().set(location.getX(), location.getY(), location.getZ()));
|
||||
}
|
||||
|
||||
public void updateFireDisplay() {
|
||||
this.fireDisplay.releaseAll();
|
||||
if (this.isFireVisible()) {
|
||||
Map<String, BlueprintBone> fireBones = ModelEngineAPI.getBlueprint("internal_fire").getBones();
|
||||
float fireScale = this.width.get() * 1.4F;
|
||||
if (!TMath.isSimilar(fireScale, 0.0F)) {
|
||||
float fireWidth = 1.0F;
|
||||
float fireHeight = this.height.get() / fireScale;
|
||||
float fireYOffset = 0.0F;
|
||||
float fireZOffset = 0.3F - (int)fireHeight * 0.02F;
|
||||
|
||||
for (int modelType = 0; fireHeight > 0.0F; modelType++) {
|
||||
ItemModelData modelData = fireBones.get("fire_" + modelType % 2).getModelData();
|
||||
float flip = fireHeight / 2.0F % 2.0F == 0.0F ? -1.0F : 1.0F;
|
||||
Optional<ItemStack> maybeStack = modelData.createItemStack().stream().findFirst();
|
||||
if (maybeStack.isPresent()) {
|
||||
DisplayFire fire = this.fireDisplay.getOrCreate();
|
||||
fire.getFireModel().set(maybeStack.get());
|
||||
fire.getPosition().set(new Vector3f(0.0F, fireYOffset, fireZOffset).mul(fireScale));
|
||||
fire.getScale().set(new Vector3f(flip * fireWidth, 1.4F, 1.0F).mul(fireScale));
|
||||
}
|
||||
|
||||
fireHeight -= 0.45F;
|
||||
fireYOffset += 0.45F;
|
||||
fireWidth *= 0.9F;
|
||||
fireZOffset -= 0.03F;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void setOnFire(boolean flag) {
|
||||
this.onFire.set(flag, () -> this.fireDisplay.getInUse().forEach(displayFire -> displayFire.getVisible().set(flag)));
|
||||
this.onFire.clearDirty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearDirty() {
|
||||
this.width.clearDirty();
|
||||
this.height.clearDirty();
|
||||
this.shadowRadius.clearDirty();
|
||||
this.hitboxVisible.clearDirty();
|
||||
this.shadowVisible.clearDirty();
|
||||
this.fireVisible.clearDirty();
|
||||
this.fireDisplay.getInUse().forEach(DisplayFire::clearDirty);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPivotId() {
|
||||
return this.pivotId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getPivotUuid() {
|
||||
return this.pivotUuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHitboxId() {
|
||||
return this.hitboxId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getHitboxUuid() {
|
||||
return this.hitboxUuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getShadowId() {
|
||||
return this.shadowId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getShadowUuid() {
|
||||
return this.shadowUuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getPosition() {
|
||||
return this.position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PositionCodec getPositionCodec() {
|
||||
return this.positionCodec;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Float> getWidth() {
|
||||
return this.width;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Float> getHeight() {
|
||||
return this.height;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Float> getShadowRadius() {
|
||||
return this.shadowRadius;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Boolean> getHitboxVisible() {
|
||||
return this.hitboxVisible;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Boolean> getShadowVisible() {
|
||||
return this.shadowVisible;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Boolean> getFireVisible() {
|
||||
return this.fireVisible;
|
||||
}
|
||||
|
||||
public DataTracker<Boolean> getOnFire() {
|
||||
return this.onFire;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PooledCollection<DisplayFire> getFireDisplay() {
|
||||
return this.fireDisplay;
|
||||
}
|
||||
|
||||
public HitboxImpl(int pivotId, int hitboxId, int shadowId) {
|
||||
this.pivotId = pivotId;
|
||||
this.hitboxId = hitboxId;
|
||||
this.shadowId = shadowId;
|
||||
}
|
||||
}
|
||||
|
||||
public static class PivotImpl implements DisplayRenderer.Pivot {
|
||||
private PivotOverride pivotOverride;
|
||||
private Float cameraEye;
|
||||
private final int id;
|
||||
private final UUID uuid = UUID.randomUUID();
|
||||
private final DataTracker<Vector3f> position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set);
|
||||
private final PositionCodec positionCodec = new PositionCodec();
|
||||
private final DataTracker<Float> yaw = new DataTracker<>();
|
||||
private final DataTracker<Float> cameraHeight = new DataTracker<>();
|
||||
private final CollectionDataTracker<Integer> passengers = new CollectionDataTracker<>(new HashSet<>());
|
||||
|
||||
public Vector3f getMountOffset(float eyeHeight) {
|
||||
if (this.pivotOverride == null) {
|
||||
return new Vector3f(0.0F, eyeHeight, 0.0F);
|
||||
} else if (this.cameraEye != null) {
|
||||
return new Vector3f(0.0F, this.cameraEye, 0.0F);
|
||||
} else {
|
||||
Vector3f offset = this.pivotOverride.getMountOffset();
|
||||
return offset == null ? new Vector3f(0.0F, eyeHeight, 0.0F) : offset;
|
||||
}
|
||||
}
|
||||
|
||||
public void updatePosition(Location location, float eyeHeight) {
|
||||
Vector3f offset = this.getMountOffset(eyeHeight);
|
||||
this.position.set(new Vector3f().set(location.getX(), location.getY(), location.getZ()).add(offset));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearDirty() {
|
||||
this.yaw.clearDirty();
|
||||
this.position.clearDirty();
|
||||
this.passengers.clearDirty();
|
||||
this.cameraHeight.clearDirty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOverridden() {
|
||||
return this.pivotOverride != null;
|
||||
}
|
||||
|
||||
public PivotOverride getPivotOverride() {
|
||||
return this.pivotOverride;
|
||||
}
|
||||
|
||||
public Float getCameraEye() {
|
||||
return this.cameraEye;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUuid() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getPosition() {
|
||||
return this.position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PositionCodec getPositionCodec() {
|
||||
return this.positionCodec;
|
||||
}
|
||||
|
||||
public DataTracker<Float> getYaw() {
|
||||
return this.yaw;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Float> getCameraHeight() {
|
||||
return this.cameraHeight;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CollectionDataTracker<Integer> getPassengers() {
|
||||
return this.passengers;
|
||||
}
|
||||
|
||||
public PivotImpl(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
package com.ticxo.modelengine.core.vfx;
|
||||
|
||||
import com.ticxo.modelengine.api.entity.BaseEntity;
|
||||
import com.ticxo.modelengine.api.generator.BaseItemEnum;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.DataTracker;
|
||||
import com.ticxo.modelengine.api.vfx.VFX;
|
||||
import com.ticxo.modelengine.api.vfx.render.VFXRenderer;
|
||||
import com.ticxo.modelengine.core.vfx.render.VFXDisplayRendererImpl;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.util.Vector;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class VFXImpl implements VFX {
|
||||
private final BaseEntity<?> base;
|
||||
private final VFXRenderer renderer;
|
||||
private final Vector3f modelScale = new Vector3f();
|
||||
private final boolean initialized;
|
||||
private final List<Runnable> queuedTask = new ArrayList<>();
|
||||
private final DataTracker<ItemStack> modelTracker = new DataTracker<>(new ItemStack(Material.AIR));
|
||||
private boolean isBaseEntityVisible = true;
|
||||
private boolean destroyed;
|
||||
private boolean removed;
|
||||
private float yaw;
|
||||
private float pitch;
|
||||
private Vector origin = new Vector();
|
||||
private Vector3f position = new Vector3f();
|
||||
private Vector3f rotation = new Vector3f();
|
||||
private Vector3f scale = new Vector3f(1.0F);
|
||||
private Color color;
|
||||
private boolean enchanted;
|
||||
private int blockLight = -1;
|
||||
private int skyLight = -1;
|
||||
private boolean visible = true;
|
||||
|
||||
public VFXImpl(@NotNull BaseEntity<?> base, @Nullable Function<VFX, VFXRenderer> rendererSupplier, @Nullable Consumer<VFX> consumer) {
|
||||
this.base = base;
|
||||
this.setOrigin(base.getLocation().toVector());
|
||||
VFXRenderer renderer = (VFXRenderer)(rendererSupplier == null ? new VFXDisplayRendererImpl(this) : rendererSupplier.apply(this));
|
||||
this.renderer = (VFXRenderer)(renderer == null ? new VFXDisplayRendererImpl(this) : renderer);
|
||||
if (consumer != null) {
|
||||
consumer.accept(this);
|
||||
}
|
||||
|
||||
this.renderer.initialize();
|
||||
synchronized (this.queuedTask) {
|
||||
this.queuedTask.forEach(Runnable::run);
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
this.registerSelf();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean tick() {
|
||||
if (!this.initialized) {
|
||||
return true;
|
||||
} else {
|
||||
this.setOrigin(this.base.getLocation().toVector());
|
||||
this.setYaw(this.base.getYHeadRot());
|
||||
this.setPitch(this.base.getXHeadRot());
|
||||
this.renderer.readVFXData();
|
||||
return !this.removed && !this.base.isRemoved();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
this.destroyed = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markRemoved() {
|
||||
this.removed = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void queuePostInitTask(Runnable runnable) {
|
||||
synchronized (this.queuedTask) {
|
||||
if (this.initialized) {
|
||||
runnable.run();
|
||||
} else {
|
||||
this.queuedTask.add(runnable);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBaseEntityVisible(boolean flag) {
|
||||
if (this.isBaseEntityVisible() != flag) {
|
||||
this.isBaseEntityVisible = flag;
|
||||
this.base.setVisible(flag);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setModelScale(int scale) {
|
||||
this.modelScale.set(scale);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getModel() {
|
||||
return this.modelTracker.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setModel(ItemStack stack) {
|
||||
this.modelTracker.set(stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setColor(Color color) {
|
||||
this.color = color;
|
||||
ItemStack model = this.modelTracker.get();
|
||||
BaseItemEnum base = BaseItemEnum.fromMaterial(model.getType());
|
||||
if (base != null) {
|
||||
ItemMeta meta = model.getItemMeta();
|
||||
base.color(meta, color);
|
||||
model.setItemMeta(meta);
|
||||
this.modelTracker.markDirty();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setEnchanted(boolean flag) {
|
||||
if (this.isEnchanted() != flag) {
|
||||
this.enchanted = flag;
|
||||
ItemStack model = this.modelTracker.get();
|
||||
if (flag) {
|
||||
model.addUnsafeEnchantment(Enchantment.VANISHING_CURSE, 1);
|
||||
} else {
|
||||
model.removeEnchantment(Enchantment.VANISHING_CURSE);
|
||||
}
|
||||
|
||||
this.modelTracker.markDirty();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public BaseEntity<?> getBase() {
|
||||
return this.base;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VFXRenderer getRenderer() {
|
||||
return this.renderer;
|
||||
}
|
||||
|
||||
public Vector3f getModelScale() {
|
||||
return this.modelScale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInitialized() {
|
||||
return this.initialized;
|
||||
}
|
||||
|
||||
public List<Runnable> getQueuedTask() {
|
||||
return this.queuedTask;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<ItemStack> getModelTracker() {
|
||||
return this.modelTracker;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isBaseEntityVisible() {
|
||||
return this.isBaseEntityVisible;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDestroyed() {
|
||||
return this.destroyed;
|
||||
}
|
||||
|
||||
public boolean isRemoved() {
|
||||
return this.removed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getYaw() {
|
||||
return this.yaw;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getPitch() {
|
||||
return this.pitch;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector getOrigin() {
|
||||
return this.origin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3f getPosition() {
|
||||
return this.position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3f getRotation() {
|
||||
return this.rotation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3f getScale() {
|
||||
return this.scale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Color getColor() {
|
||||
return this.color;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnchanted() {
|
||||
return this.enchanted;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getBlockLight() {
|
||||
return this.blockLight;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getSkyLight() {
|
||||
return this.skyLight;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVisible() {
|
||||
return this.visible;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setYaw(float yaw) {
|
||||
this.yaw = yaw;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPitch(float pitch) {
|
||||
this.pitch = pitch;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setOrigin(Vector origin) {
|
||||
this.origin = origin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPosition(Vector3f position) {
|
||||
this.position = position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRotation(Vector3f rotation) {
|
||||
this.rotation = rotation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setScale(Vector3f scale) {
|
||||
this.scale = scale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBlockLight(int blockLight) {
|
||||
this.blockLight = blockLight;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSkyLight(int skyLight) {
|
||||
this.skyLight = skyLight;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVisible(boolean visible) {
|
||||
this.visible = visible;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package com.ticxo.modelengine.core.vfx.render;
|
||||
|
||||
import com.ticxo.modelengine.api.ModelEngineAPI;
|
||||
import com.ticxo.modelengine.api.nms.entity.EntityHandler;
|
||||
import com.ticxo.modelengine.api.utils.data.PositionCodec;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.DataTracker;
|
||||
import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker;
|
||||
import com.ticxo.modelengine.api.vfx.VFX;
|
||||
import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer;
|
||||
import com.ticxo.modelengine.api.vfx.render.VFXRendererParser;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
public class VFXDisplayRendererImpl implements VFXDisplayRenderer {
|
||||
private final VFX vfx;
|
||||
private final EntityHandler entityHandler;
|
||||
private final VFXRendererParser<VFXDisplayRenderer> parser;
|
||||
private VFXDisplayRendererImpl.VFXModelImpl vfxModel;
|
||||
private boolean respawnRequired;
|
||||
private boolean initialized;
|
||||
|
||||
public VFXDisplayRendererImpl(VFX vfx) {
|
||||
this.vfx = vfx;
|
||||
this.entityHandler = ModelEngineAPI.getEntityHandler();
|
||||
this.parser = ModelEngineAPI.getNMSHandler().getVFXRendererParser(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public VFX getVFX() {
|
||||
return this.vfx;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize() {
|
||||
this.vfxModel = new VFXDisplayRendererImpl.VFXModelImpl(
|
||||
this.entityHandler.getNextEntityId(), UUID.randomUUID(), this.entityHandler.getNextEntityId(), UUID.randomUUID()
|
||||
);
|
||||
this.vfxModel.getOrigin().set(this.vfx.getOrigin().toVector3f());
|
||||
this.vfxModel.getPosition().set(this.calculatePosition());
|
||||
this.vfxModel.getLeftRotation().set(this.calculateRotation());
|
||||
this.vfxModel.getScale().set(this.vfx.getScale());
|
||||
this.vfxModel.getModel().set(this.vfx.isVisible() ? this.vfx.getModel() : null);
|
||||
this.vfxModel.getBrightness().set(this.vfx.getBrightness());
|
||||
this.initialized = true;
|
||||
this.respawnRequired = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readVFXData() {
|
||||
if (this.initialized) {
|
||||
this.vfxModel.getOrigin().set(this.vfx.getOrigin().toVector3f());
|
||||
this.vfxModel.getPosition().set(this.calculatePosition());
|
||||
this.vfxModel.getLeftRotation().set(this.calculateRotation());
|
||||
this.vfxModel.getScale().set(this.vfx.getScale());
|
||||
this.vfxModel.getBrightness().set(this.vfx.getBrightness());
|
||||
if (!this.vfx.isVisible()) {
|
||||
this.vfxModel.getModel().set(null);
|
||||
} else {
|
||||
this.vfxModel.getModel().set(this.vfx.getModel());
|
||||
if (this.vfx.getModelTracker().isDirty()) {
|
||||
this.vfx.getModelTracker().clearDirty();
|
||||
this.vfxModel.getModel().markDirty();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendToClient() {
|
||||
if (this.initialized) {
|
||||
this.parser.sendToClients(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
if (this.initialized) {
|
||||
this.parser.destroy(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public VFXDisplayRenderer.VFXModel getVFXModel() {
|
||||
return this.vfxModel;
|
||||
}
|
||||
|
||||
private Vector3f calculatePosition() {
|
||||
float yaw = this.vfx.getYaw();
|
||||
float pitch = this.vfx.getPitch();
|
||||
Vector3f pos = this.vfx.getPosition();
|
||||
return new Vector3f(pos).rotateX(pitch * (float) (Math.PI / 180.0)).rotateY(-yaw * (float) (Math.PI / 180.0));
|
||||
}
|
||||
|
||||
private Quaternionf calculateRotation() {
|
||||
float yaw = this.vfx.getYaw();
|
||||
float pitch = this.vfx.getPitch();
|
||||
Vector3f rot = this.vfx.getRotation();
|
||||
return new Quaternionf().rotateY((180.0F - yaw) * (float) (Math.PI / 180.0)).rotateX(-pitch * (float) (Math.PI / 180.0)).rotateZYX(rot.z, rot.y, rot.x);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRespawnRequired() {
|
||||
return this.respawnRequired;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRespawnRequired(boolean respawnRequired) {
|
||||
this.respawnRequired = respawnRequired;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInitialized() {
|
||||
return this.initialized;
|
||||
}
|
||||
|
||||
public static class VFXModelImpl implements VFXDisplayRenderer.VFXModel {
|
||||
private final int pivotId;
|
||||
private final UUID pivotUuid;
|
||||
private final int modelId;
|
||||
private final UUID modelUuid;
|
||||
private final DataTracker<Vector3f> origin = new UpdateDataTracker<>(new Vector3f(), Vector3f::set);
|
||||
private final PositionCodec positionCodec = new PositionCodec();
|
||||
private final DataTracker<Vector3f> position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set);
|
||||
private final DataTracker<Quaternionf> leftRotation = new UpdateDataTracker<>(new Quaternionf(), Quaternionf::set);
|
||||
private final DataTracker<Vector3f> scale = new UpdateDataTracker<>(new Vector3f(), Vector3f::set);
|
||||
private final DataTracker<ItemStack> model = new DataTracker<>();
|
||||
private final DataTracker<Integer> brightness = new DataTracker<>(-1);
|
||||
|
||||
@Override
|
||||
public int getPivotId() {
|
||||
return this.pivotId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getPivotUuid() {
|
||||
return this.pivotUuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getModelId() {
|
||||
return this.modelId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getModelUuid() {
|
||||
return this.modelUuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getOrigin() {
|
||||
return this.origin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PositionCodec getPositionCodec() {
|
||||
return this.positionCodec;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getPosition() {
|
||||
return this.position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Quaternionf> getLeftRotation() {
|
||||
return this.leftRotation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Vector3f> getScale() {
|
||||
return this.scale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<ItemStack> getModel() {
|
||||
return this.model;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTracker<Integer> getBrightness() {
|
||||
return this.brightness;
|
||||
}
|
||||
|
||||
public VFXModelImpl(int pivotId, UUID pivotUuid, int modelId, UUID modelUuid) {
|
||||
this.pivotId = pivotId;
|
||||
this.pivotUuid = pivotUuid;
|
||||
this.modelId = modelId;
|
||||
this.modelUuid = modelUuid;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1072 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user