This commit is contained in:
bloodyfox committed 2026-11-22 20:16:53 +01:00
commit a517969a28
1072 files changed
+160209

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
.gradle/
build/
*/build/
nms/*/build/
.idea/
*.iml
+58
View File
@@ -0,0 +1,58 @@
<p align="center">
<img src="https://img.shields.io/badge/Version-R4.2.0-27272a?style=for-the-badge&labelColor=09090b" alt="Version R4.2.0" />
<img src="https://img.shields.io/badge/Java-17%20%7C%2021%20%7C%2025-3f3f46?style=for-the-badge&logo=openjdk&logoColor=ffffff&labelColor=09090b" alt="Java 17 | 21 | 25" />
<img src="https://img.shields.io/badge/Gradle-9.9.1-52525b?style=for-the-badge&logo=gradle&logoColor=ffffff&labelColor=09090b" alt="Gradle 9.9.1" />
<img src="https://img.shields.io/badge/Paper-1.19.4%20--%2026.3-71717a?style=for-the-badge&labelColor=09090b" alt="Paper 1.19.4 - 26.3" />
</p>
## How to build
### Prerequisites
- **Java Development Kit**: JDK 21 or newer to run Gradle (paperweight 2.x needs at least Java 21).
- **Toolchains**: Gradle downloads JDK 17, 21 and 25 for the modules automatically through the foojay resolver if you don't have them.
- **Network access**: the first build downloads and sets up a Paper dev bundle for each of the 15 supported Minecraft versions. Expect about 15 minutes and a few GB in `~/.gradle`.
### Building ModelEngine
Run from this folder.
macOS / Linux:
```bash
./gradlew clean build
```
Windows:
```powershell
$env:JAVA_HOME = "C:\Program Files\Java\jdk-21"
.\gradlew.bat clean build
```
Generated in `build/libs/`:
- `ModelEngine-R4.2.0.jar`
### Running
1. Copy `build/libs/ModelEngine-R4.2.0.jar` into your server's `plugins/` folder.
2. Start a Paper or Folia server running 1.19.4 – 26.3.
3. Optional integrations: MythicMobs, Citizens, LibsDisguises, ViaVersion.
## Project layout
| Module | Java | Purpose |
| --- | --- | --- |
| `api` | 17 | Public API |
| `core` | 17 | Plugin core, commands, generator, resources |
| `core21` | 21 | MythicMobs integration, 1.20.5+ adapter loader |
| `core25` | 25 | 26.x adapter loader |
| `nms/v1_19_R3` – `nms/v1_20_R3` | 17 | Adapters for 1.19.4 – 1.20.4 (ship Spigot-mapped) |
| `nms/v1_20_R4` – `nms/v1_21_R7` | 21 | Adapters for 1.20.6 – 1.21.11 |
| `nms/v26_1` – `nms/v26_3` | 25 | Adapters for 26.1 – 26.3 |
## Notes
- **Spigot-mapped adapters:** Paper ran Spigot-mapped before 1.20.5, so the `v1_19_R3` – `v1_20_R3` adapters are reobfuscated to Spigot names at build time. The newer adapters ship Mojang-mapped.
- **IDE sources:** `paperweight.experimental.genSources=false` in `gradle.properties` turns off patched Minecraft sources for IDE browsing. The 1.19.4 – 1.20.2 dev bundles fail to generate them under paperweight 2.x, and compiling doesn't need them.
- **Bundled libraries:** `libs/mineskin-java-client-3.2.1-SNAPSHOT.jar` holds the MineSkin client, since that snapshot isn't published anywhere. jsoup 1.17.2 comes from Maven Central. Both are bundled into the plugin jar without relocation.
+5
View File
@@ -0,0 +1,5 @@
dependencies {
compileOnly("io.papermc.paper:paper-api:1.20.4-R0.1-SNAPSHOT")
compileOnly("io.netty:netty-all:4.1.97.Final")
compileOnly("net.kyori:adventure-text-serializer-bungeecord:4.3.0") { isTransitive = false }
}
@@ -0,0 +1,404 @@
package com.ticxo.modelengine.api;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import com.ticxo.modelengine.api.animation.AnimationHandlerRegistry;
import com.ticxo.modelengine.api.animation.AnimationPropertyRegistry;
import com.ticxo.modelengine.api.animation.handler.AnimationHandler;
import com.ticxo.modelengine.api.animation.keyframe.KeyframeTypeRegistry;
import com.ticxo.modelengine.api.animation.keyframe.data.KeyframeReaderRegistry;
import com.ticxo.modelengine.api.animation.script.ScriptReaderRegistry;
import com.ticxo.modelengine.api.entity.BaseEntity;
import com.ticxo.modelengine.api.entity.BukkitEntity;
import com.ticxo.modelengine.api.entity.BukkitPlayer;
import com.ticxo.modelengine.api.entity.EntityDataTrackers;
import com.ticxo.modelengine.api.generator.ModelGenerator;
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
import com.ticxo.modelengine.api.generator.skin.SkinGeneratorService;
import com.ticxo.modelengine.api.generator.skin.SkinSplitter;
import com.ticxo.modelengine.api.interaction.InteractionTracker;
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.behavior.BoneBehaviorRegistry;
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.nms.NMSHandler;
import com.ticxo.modelengine.api.nms.entity.EntityHandler;
import com.ticxo.modelengine.api.nms.network.CancelType;
import com.ticxo.modelengine.api.nms.network.NetworkHandler;
import com.ticxo.modelengine.api.nms.ui.AnvilHandler;
import com.ticxo.modelengine.api.utils.CompatibilityManager;
import com.ticxo.modelengine.api.utils.config.ConfigCache;
import com.ticxo.modelengine.api.utils.config.ConfigManager;
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 java.util.Set;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.plugin.java.JavaPlugin;
public abstract class ModelEngineAPI extends JavaPlugin {
protected static ModelEngineAPI API;
protected final Set<Integer> renderCanceled = Sets.newConcurrentHashSet();
protected ConfigManager configManager;
protected ConfigCache configCache;
protected Gson gson;
protected PlatformScheduler scheduler;
protected ModelRegistry modelRegistry;
protected ModelGenerator modelGenerator;
protected KeyframeTypeRegistry keyframeTypeRegistry;
protected KeyframeReaderRegistry keyframeReaderRegistry;
protected ScriptReaderRegistry scriptReaderRegistry;
protected BoneBehaviorRegistry boneBehaviorRegistry;
protected AnimationHandlerRegistry animationHandlerRegistry;
protected AnimationPropertyRegistry animationPropertyRegistry;
protected DualTicker ticker;
protected ModelUpdaters modelUpdaters;
protected VFXUpdater vfxUpdater;
protected EntityDataTrackers dataTrackers;
protected InteractionTracker interactionTracker;
protected MountPairManager mountPairManager;
protected MountControllerTypeRegistry mountControllerTypeRegistry;
protected NMSHandler nmsHandler;
protected CompatibilityManager compatibilityManager;
protected ScreenManager screenManager;
protected SkinSplitter skinSplitter;
protected SkinGeneratorService skinGenerator;
protected UserLimbRegistry userLimbRegistry;
protected PivotOverrideRegistry pivotOverrideRegistry;
public static ConfigCache getConfigCache() {
return getAPI().configCache;
}
public static NMSHandler getNMSHandler() {
return getAPI().nmsHandler;
}
public static EntityHandler getEntityHandler() {
return getNMSHandler().getEntityHandler();
}
public static AnvilHandler getAnvilHandler() {
return getNMSHandler().getAnvilHandler();
}
public static NetworkHandler getNetworkHandler() {
return getNMSHandler().getNetworkHandler();
}
public static InteractionTracker getInteractionTracker() {
return getAPI().interactionTracker;
}
public static MountPairManager getMountPairManager() {
return getAPI().mountPairManager;
}
public static MountControllerTypeRegistry getMountControllerTypeRegistry() {
return getAPI().mountControllerTypeRegistry;
}
public static AnimationHandlerRegistry getAnimationHandlerRegistry() {
return getAPI().animationHandlerRegistry;
}
public static AnimationPropertyRegistry getAnimationPropertyRegistry() {
return getAPI().animationPropertyRegistry;
}
public static UserLimbRegistry getUserLimbRegistry() {
return getAPI().userLimbRegistry;
}
public static SkinGeneratorService getSkinGeneratorService() {
return getAPI().skinGenerator;
}
public static PivotOverrideRegistry getPivotOverrideRegistry() {
return getAPI().pivotOverrideRegistry;
}
public VFXUpdater getVFXUpdater() {
return this.vfxUpdater;
}
public static ModeledEntity createModeledEntity(Entity base) {
return createModeledEntity(base, null);
}
public static ModeledEntity createModeledEntity(Entity base, Consumer<ModeledEntity> consumer) {
return createModeledEntity((BaseEntity<?>)(base instanceof Player player ? new BukkitPlayer(player) : new BukkitEntity(base)), consumer);
}
public static ModeledEntity createModeledEntity(BaseEntity<?> base) {
return createModeledEntity(base, null);
}
public static ModeledEntity createModeledEntity(BaseEntity<?> base, Consumer<ModeledEntity> consumer) {
return getAPI().createModeledEntityImpl(base, consumer);
}
public static ModeledEntity getModeledEntity(Entity entity) {
return getModeledEntity(entity.getUniqueId());
}
public static ModeledEntity getModeledEntity(int id) {
return getAPI().getModelUpdaters().getModeledEntity(id);
}
public static ModeledEntity getModeledEntity(UUID uuid) {
return getAPI().getModelUpdaters().getModeledEntity(uuid);
}
public static ModeledEntity getOrCreateModeledEntity(Entity base) {
ModeledEntity model = getModeledEntity(base);
return model != null ? model : createModeledEntity(base, null);
}
public static ModeledEntity getOrCreateModeledEntity(Entity base, Consumer<ModeledEntity> consumer) {
ModeledEntity model = getModeledEntity(base);
return model != null
? model
: createModeledEntity((BaseEntity<?>)(base instanceof Player player ? new BukkitPlayer(player) : new BukkitEntity(base)), consumer);
}
public static ModeledEntity getOrCreateModeledEntity(UUID uuid, Supplier<BaseEntity<?>> baseEntitySupplier) {
ModeledEntity model = getModeledEntity(uuid);
return model != null ? model : createModeledEntity(baseEntitySupplier.get(), null);
}
public static ModeledEntity getOrCreateModeledEntity(UUID uuid, Supplier<BaseEntity<?>> baseEntitySupplier, Consumer<ModeledEntity> consumer) {
ModeledEntity model = getModeledEntity(uuid);
return model != null ? model : getAPI().createModeledEntityImpl(baseEntitySupplier.get(), consumer);
}
public static ModeledEntity removeModeledEntity(Entity entity) {
return removeModeledEntity(entity.getUniqueId());
}
public static ModeledEntity removeModeledEntity(int id) {
return getAPI().getModelUpdaters().removeModeledEntity(id);
}
public static ModeledEntity removeModeledEntity(UUID uuid) {
return getAPI().getModelUpdaters().removeModeledEntity(uuid);
}
public static boolean isModeledEntity(UUID uuid) {
return getModeledEntity(uuid) != null;
}
public static ActiveModel createActiveModel(String modelId) {
return createActiveModel(modelId, null, null);
}
public static ActiveModel createActiveModel(
String modelId, Function<ActiveModel, ModelRenderer> rendererSupplier, Function<ActiveModel, AnimationHandler> handlerSupplier
) {
ModelBlueprint blueprint = getAPI().getModelRegistry().get(modelId);
if (blueprint == null) {
throw new RuntimeException("Error while creating ActiveModel. Unknown model: " + modelId);
} else {
return createActiveModel(blueprint, rendererSupplier, handlerSupplier);
}
}
public static ActiveModel createActiveModel(ModelBlueprint blueprint) {
return createActiveModel(blueprint, null, null);
}
public static ActiveModel createActiveModel(
ModelBlueprint blueprint, Function<ActiveModel, ModelRenderer> rendererSupplier, Function<ActiveModel, AnimationHandler> handlerSupplier
) {
return getAPI().createActiveModelImpl(blueprint, rendererSupplier, handlerSupplier);
}
public static AnimationHandler createPriorityHandler(ActiveModel activeModel) {
return getAPI().getPriorityHandler(activeModel);
}
public static AnimationHandler createStateMachineHandler(ActiveModel activeModel) {
return getAPI().getStateMachineHandler(activeModel);
}
public static VFX createVFX(Entity base) {
return createVFX(base, null, null);
}
public static VFX createVFX(Entity base, Consumer<VFX> consumer) {
return createVFX(base, consumer, null);
}
public static VFX createVFX(Entity base, Consumer<VFX> consumer, Function<VFX, VFXRenderer> rendererSupplier) {
return createVFX((BaseEntity<?>)(base instanceof Player player ? new BukkitPlayer(player) : new BukkitEntity(base)), consumer, rendererSupplier);
}
public static VFX createVFX(BaseEntity<?> base) {
return createVFX(base, null, null);
}
public static VFX createVFX(BaseEntity<?> base, Consumer<VFX> consumer) {
return createVFX(base, consumer, null);
}
public static VFX createVFX(BaseEntity<?> base, Consumer<VFX> consumer, Function<VFX, VFXRenderer> rendererSupplier) {
return getAPI().createVFXImpl(base, rendererSupplier, consumer);
}
public static VFX getVFX(Entity entity) {
return getVFX(entity.getUniqueId());
}
public static VFX getVFX(int id) {
return getAPI().getVFXUpdater().getVFX(id);
}
public static VFX getVFX(UUID uuid) {
return getAPI().getVFXUpdater().getVFX(uuid);
}
public static boolean isVFX(UUID uuid) {
return getVFX(uuid) != null;
}
public static ModelBlueprint getBlueprint(String id) {
return getAPI().getModelRegistry().get(id);
}
public static void setRenderCanceled(int id, boolean flag) {
if (flag) {
getAPI().renderCanceled.add(id);
} else {
getAPI().renderCanceled.remove(id);
}
}
public static boolean isRenderCanceled(int id) {
return getAPI().renderCanceled.contains(id);
}
public static CancelType shouldShow(Player player, int id) {
if (player.getEntityId() == id) {
return CancelType.SHOW;
} else {
ModeledEntity entity = getAPI().modelUpdaters.getModeledEntity(id);
if (entity != null && !entity.isBaseEntityVisible()) {
return entity.isPivotOverride(id) ? CancelType.INVIS : CancelType.HIDE;
} else {
return isRenderCanceled(id) ? CancelType.HIDE : CancelType.SHOW;
}
}
}
public static void callEvent(Event event) {
Bukkit.getPluginManager().callEvent(event);
}
public static int getPlayerProtocolVersion(UUID uuid) {
return getAPI().playerProtocolVersion(uuid);
}
public abstract ModeledEntity createModeledEntityImpl(BaseEntity<?> var1, Consumer<ModeledEntity> var2);
public abstract ActiveModel createActiveModelImpl(
ModelBlueprint var1, Function<ActiveModel, ModelRenderer> var2, Function<ActiveModel, AnimationHandler> var3
);
public abstract VFX createVFXImpl(BaseEntity<?> var1, Function<VFX, VFXRenderer> var2, Consumer<VFX> var3);
public abstract UUID getDisguiseRelayOrDefault(UUID var1);
public abstract AnimationHandler getPriorityHandler(ActiveModel var1);
public abstract AnimationHandler getStateMachineHandler(ActiveModel var1);
public abstract int playerProtocolVersion(UUID var1);
public Set<Integer> getRenderCanceled() {
return this.renderCanceled;
}
public ConfigManager getConfigManager() {
return this.configManager;
}
public Gson getGson() {
return this.gson;
}
public PlatformScheduler getScheduler() {
return this.scheduler;
}
public ModelRegistry getModelRegistry() {
return this.modelRegistry;
}
public ModelGenerator getModelGenerator() {
return this.modelGenerator;
}
public KeyframeTypeRegistry getKeyframeTypeRegistry() {
return this.keyframeTypeRegistry;
}
public KeyframeReaderRegistry getKeyframeReaderRegistry() {
return this.keyframeReaderRegistry;
}
public ScriptReaderRegistry getScriptReaderRegistry() {
return this.scriptReaderRegistry;
}
public BoneBehaviorRegistry getBoneBehaviorRegistry() {
return this.boneBehaviorRegistry;
}
public DualTicker getTicker() {
return this.ticker;
}
public ModelUpdaters getModelUpdaters() {
return this.modelUpdaters;
}
public EntityDataTrackers getDataTrackers() {
return this.dataTrackers;
}
public CompatibilityManager getCompatibilityManager() {
return this.compatibilityManager;
}
public ScreenManager getScreenManager() {
return this.screenManager;
}
public SkinSplitter getSkinSplitter() {
return this.skinSplitter;
}
public SkinGeneratorService getSkinGenerator() {
return this.skinGenerator;
}
public static ModelEngineAPI getAPI() {
return API;
}
}
@@ -0,0 +1,78 @@
package com.ticxo.modelengine.api;
import com.google.common.collect.ImmutableSet;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
public class ServerInfo {
public static final boolean IS_PAPER = classExists("com.destroystokyo.paper.VersionHistoryManager$VersionData");
public static final boolean IS_FOLIA = classExists("io.papermc.paper.threadedregions.RegionizedServer");
public static final String NMS_VERSION = Bukkit.getServer().getMinecraftVersion();
public static final int VERSION_NUMBER = Integer.parseInt(NMS_VERSION.split("\\.")[1]);
public static boolean HAS_VIAVERSION;
public static boolean HAS_CITIZENS;
public static volatile int CURRENT_TICK;
private static final Set<UUID> ONLINE_PLAYERS = new HashSet<>();
private static volatile ImmutableSet<UUID> ONLINE_PLAYERS_VIEW = ImmutableSet.of();
public static void setOnline(UUID uuid, boolean flag) {
if (flag) {
ONLINE_PLAYERS.add(uuid);
} else {
ONLINE_PLAYERS.remove(uuid);
}
ONLINE_PLAYERS_VIEW = ImmutableSet.copyOf(ONLINE_PLAYERS);
}
public static ImmutableSet<UUID> getOnlinePlayers() {
return ONLINE_PLAYERS_VIEW;
}
public static boolean scheduleOnRegion(Entity entity, Runnable task) {
if (!IS_FOLIA) {
if (Bukkit.isPrimaryThread()) {
return false;
} else {
Bukkit.getScheduler().runTask(ModelEngineAPI.getAPI(), task);
return true;
}
} else {
boolean onRegionThread;
try {
onRegionThread = Bukkit.isOwnedByCurrentRegion(entity);
} catch (Exception var4) {
onRegionThread = false;
}
if (onRegionThread) {
return false;
} else {
Location loc = new Location(null, 0.0, 0.0, 0.0);
ModelEngineAPI.getEntityHandler().getLocation(entity, loc);
if (loc.getWorld() != null) {
Bukkit.getRegionScheduler().execute(ModelEngineAPI.getAPI(), loc, task);
}
return true;
}
}
}
public static void scheduleOnRegionDelayed(Entity entity, Runnable task, long delayTicks) {
entity.getScheduler().execute(ModelEngineAPI.getAPI(), task, null, delayTicks);
}
private static boolean classExists(String path) {
try {
Class.forName(path);
return true;
} catch (ClassNotFoundException var2) {
return false;
}
}
}
@@ -0,0 +1,14 @@
package com.ticxo.modelengine.api.animation;
import com.ticxo.modelengine.api.animation.handler.AnimationHandler;
import com.ticxo.modelengine.api.model.ActiveModel;
import com.ticxo.modelengine.api.utils.data.io.SavedData;
import com.ticxo.modelengine.api.utils.registry.TUnaryRegistry;
import java.util.function.BiFunction;
public class AnimationHandlerRegistry extends TUnaryRegistry<BiFunction<ActiveModel, SavedData, AnimationHandler>> {
public AnimationHandler createHandler(ActiveModel model, SavedData data) {
String id = data.getString("id");
return id != null ? this.get(id).apply(model, data) : null;
}
}
@@ -0,0 +1,14 @@
package com.ticxo.modelengine.api.animation;
import com.ticxo.modelengine.api.animation.handler.AnimationHandler;
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
import com.ticxo.modelengine.api.utils.data.io.SavedData;
import com.ticxo.modelengine.api.utils.registry.TUnaryRegistry;
import java.util.function.BiFunction;
public class AnimationPropertyRegistry extends TUnaryRegistry<BiFunction<AnimationHandler, SavedData, IAnimationProperty>> {
public IAnimationProperty createAnimationProperty(AnimationHandler handler, SavedData data) {
String id = data.getString("id");
return id != null ? this.get(id).apply(handler, data) : null;
}
}
@@ -0,0 +1,186 @@
package com.ticxo.modelengine.api.animation;
import com.ticxo.modelengine.api.animation.interpolator.KeyframeInterpolator;
import com.ticxo.modelengine.api.animation.keyframe.KeyframeType;
import com.ticxo.modelengine.api.animation.keyframe.KeyframeTypes;
import com.ticxo.modelengine.api.animation.keyframe.type.AbstractKeyframe;
import com.ticxo.modelengine.api.animation.keyframe.type.ScriptKeyframe;
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone;
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
import com.ticxo.modelengine.api.model.bone.ModelBone;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import org.jetbrains.annotations.Nullable;
import org.joml.Vector3f;
public class BlueprintAnimation {
private final ModelBlueprint modelBlueprint;
private final Map<UUID, Timeline> timelines = new HashMap<>();
private final String name;
private final Timeline globalTimeline = new Timeline(this, false);
private double length;
private BlueprintAnimation.LoopMode loopMode;
private boolean override;
public Vector3f getPosition(ModelBone bone, IAnimationProperty property) {
return this.getPosition(bone, bone.getBlueprintBone(), property);
}
public Vector3f getPosition(ModelBone bone, BlueprintBone blueprintBone, IAnimationProperty property) {
Timeline timeline = this.timelines.get(blueprintBone.getUuid());
return timeline == null ? null : timeline.getInterpolator(KeyframeTypes.POSITION).interpolate(bone, property);
}
public Vector3f getVelocity(ModelBone bone, IAnimationProperty property) {
return this.getVelocity(bone, bone.getBlueprintBone(), property);
}
public Vector3f getVelocity(ModelBone bone, BlueprintBone blueprintBone, IAnimationProperty property) {
Timeline timeline = this.timelines.get(blueprintBone.getUuid());
return timeline == null ? null : timeline.getInterpolator(KeyframeTypes.POSITION).interpolateAndDerive(bone, property);
}
public Vector3f getRotation(ModelBone bone, IAnimationProperty property) {
return this.getRotation(bone, bone.getBlueprintBone(), property);
}
public Vector3f getRotation(ModelBone bone, BlueprintBone blueprintBone, IAnimationProperty property) {
Timeline timeline = this.timelines.get(blueprintBone.getUuid());
return timeline == null ? null : timeline.getInterpolator(KeyframeTypes.ROTATION).interpolate(bone, property);
}
public Vector3f getScale(ModelBone bone, IAnimationProperty property) {
return this.getScale(bone, bone.getBlueprintBone(), property);
}
public Vector3f getScale(ModelBone bone, BlueprintBone blueprintBone, IAnimationProperty property) {
Timeline timeline = this.timelines.get(blueprintBone.getUuid());
return timeline == null ? null : timeline.getInterpolator(KeyframeTypes.SCALE).interpolate(bone, property);
}
public List<ScriptKeyframe.Script> getScript(IAnimationProperty property) {
return this.globalTimeline.getInterpolator(KeyframeTypes.SCRIPT).interpolate(null, property);
}
public String getInterpolation(KeyframeType<?, ?> type, UUID uuid, float time) {
Timeline timeline = this.timelines.get(uuid);
if (timeline == null) {
return null;
} else {
KeyframeInterpolator<? extends AbstractKeyframe<?>, ?> interpolator = timeline.getInterpolator((KeyframeType<? extends AbstractKeyframe<?>, ?>)type);
AbstractKeyframe<?> frame = (AbstractKeyframe<?>)interpolator.get(time);
if (frame != null) {
return frame.getInterpolation();
} else {
frame = (AbstractKeyframe<?>)interpolator.get(interpolator.getLowerKey(time));
return frame == null ? null : frame.getInterpolation();
}
}
}
public ModelBlueprint getModelBlueprint() {
return this.modelBlueprint;
}
public Map<UUID, Timeline> getTimelines() {
return this.timelines;
}
public String getName() {
return this.name;
}
public Timeline getGlobalTimeline() {
return this.globalTimeline;
}
public double getLength() {
return this.length;
}
public BlueprintAnimation.LoopMode getLoopMode() {
return this.loopMode;
}
public boolean isOverride() {
return this.override;
}
public BlueprintAnimation(ModelBlueprint modelBlueprint, String name) {
this.modelBlueprint = modelBlueprint;
this.name = name;
}
public void setLength(double length) {
this.length = length;
}
public void setLoopMode(BlueprintAnimation.LoopMode loopMode) {
this.loopMode = loopMode;
}
public void setOverride(boolean override) {
this.override = override;
}
public static enum LoopMode {
ONCE,
HOLD,
LOOP;
public static BlueprintAnimation.LoopMode get(String mode) {
try {
return valueOf(mode.toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException var2) {
return ONCE;
}
}
@Nullable
public static BlueprintAnimation.LoopMode getOrNull(String mode) {
if (mode == null) {
return null;
} else {
try {
return valueOf(mode.toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException var2) {
return null;
}
}
}
}
public static enum OverrideMode {
NONE,
OVERRIDE;
public static BlueprintAnimation.OverrideMode get(String mode) {
try {
return valueOf(mode.toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException var2) {
return NONE;
}
}
@Nullable
public static BlueprintAnimation.OverrideMode getOrNull(String mode) {
if (mode == null) {
return null;
} else {
try {
return valueOf(mode.toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException var2) {
if ("true".equalsIgnoreCase(mode)) {
return OVERRIDE;
} else {
return "false".equalsIgnoreCase(mode) ? NONE : null;
}
}
}
}
}
}
@@ -0,0 +1,56 @@
package com.ticxo.modelengine.api.animation;
import com.ticxo.modelengine.api.utils.config.ConfigProperty;
import com.ticxo.modelengine.api.utils.config.Property;
import java.util.Locale;
import org.jetbrains.annotations.Nullable;
public enum ModelState implements Property {
IDLE(BlueprintAnimation.LoopMode.LOOP, null),
WALK(BlueprintAnimation.LoopMode.LOOP, null),
STRAFE(BlueprintAnimation.LoopMode.LOOP, null),
JUMP_START(BlueprintAnimation.LoopMode.ONCE, BlueprintAnimation.OverrideMode.OVERRIDE),
JUMP(BlueprintAnimation.LoopMode.LOOP, BlueprintAnimation.OverrideMode.OVERRIDE),
JUMP_END(BlueprintAnimation.LoopMode.ONCE, BlueprintAnimation.OverrideMode.OVERRIDE),
HOVER(BlueprintAnimation.LoopMode.LOOP, BlueprintAnimation.OverrideMode.OVERRIDE),
FLY(BlueprintAnimation.LoopMode.LOOP, BlueprintAnimation.OverrideMode.OVERRIDE),
SPAWN(BlueprintAnimation.LoopMode.ONCE, BlueprintAnimation.OverrideMode.OVERRIDE),
DEATH(BlueprintAnimation.LoopMode.HOLD, BlueprintAnimation.OverrideMode.OVERRIDE);
private final String path = ConfigProperty.DEFAULT_NAMES.getPath() + "." + this.name();
private final Object def = this.name().toLowerCase(Locale.ENGLISH);
private final BlueprintAnimation.LoopMode loopMode;
private final BlueprintAnimation.OverrideMode override;
private ModelState(BlueprintAnimation.LoopMode loopMode, BlueprintAnimation.OverrideMode override) {
this.loopMode = loopMode;
this.override = override;
}
@Nullable
public static ModelState get(String value) {
try {
return valueOf(value.toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException var2) {
return null;
}
}
@Override
public String getPath() {
return this.path;
}
@Override
public Object getDef() {
return this.def;
}
public BlueprintAnimation.LoopMode getLoopMode() {
return this.loopMode;
}
public BlueprintAnimation.OverrideMode getOverride() {
return this.override;
}
}
@@ -0,0 +1,76 @@
package com.ticxo.modelengine.api.animation;
import com.google.common.collect.Maps;
import com.ticxo.modelengine.api.animation.interpolator.KeyframeInterpolator;
import com.ticxo.modelengine.api.animation.keyframe.KeyframeType;
import com.ticxo.modelengine.api.animation.keyframe.KeyframeTypes;
import com.ticxo.modelengine.api.animation.keyframe.type.AbstractKeyframe;
import java.util.Map;
public class Timeline {
private final BlueprintAnimation animation;
private final boolean globalRotation;
private final Map<KeyframeType<?, ?>, KeyframeInterpolator<?, ?>> interpolators = Maps.newConcurrentMap();
private volatile KeyframeInterpolator<?, ?> position;
private volatile KeyframeInterpolator<?, ?> rotation;
private volatile KeyframeInterpolator<?, ?> scale;
public boolean hasInterpolator(KeyframeType<?, ?> type) {
return this.getCached(type) != null ? true : this.interpolators.containsKey(type);
}
public <KEY extends AbstractKeyframe<DATA>, DATA> KeyframeInterpolator<KEY, DATA> getInterpolator(KeyframeType<KEY, DATA> type) {
KeyframeInterpolator<? extends AbstractKeyframe<?>, ?> cached = (KeyframeInterpolator<? extends AbstractKeyframe<?>, ?>)this.getCached(type);
if (cached != null) {
return (KeyframeInterpolator<KEY, DATA>)cached;
} else {
KeyframeInterpolator<? extends AbstractKeyframe<?>, ?> interpolator = (KeyframeInterpolator<? extends AbstractKeyframe<?>, ?>)this.interpolators
.get(type);
if (interpolator == null) {
interpolator = (KeyframeInterpolator<? extends AbstractKeyframe<?>, ?>)this.interpolators
.computeIfAbsent(type, keyframeType -> keyframeType.createInterpolator(this));
}
this.setCached(type, interpolator);
return (KeyframeInterpolator<KEY, DATA>)interpolator;
}
}
public <KEY extends AbstractKeyframe<DATA>, DATA> KEY getKeyframe(float time, KeyframeType<KEY, DATA> type) {
KeyframeInterpolator<KEY, DATA> interpolator = this.getInterpolator(type);
return interpolator.computeIfAbsent(time, t -> type.createKeyframe());
}
private KeyframeInterpolator<?, ?> getCached(KeyframeType<?, ?> type) {
if (type == KeyframeTypes.POSITION) {
return this.position;
} else if (type == KeyframeTypes.ROTATION) {
return this.rotation;
} else {
return type == KeyframeTypes.SCALE ? this.scale : null;
}
}
private void setCached(KeyframeType<?, ?> type, KeyframeInterpolator<?, ?> interpolator) {
if (type == KeyframeTypes.POSITION) {
this.position = interpolator;
} else if (type == KeyframeTypes.ROTATION) {
this.rotation = interpolator;
} else if (type == KeyframeTypes.SCALE) {
this.scale = interpolator;
}
}
public Timeline(BlueprintAnimation animation, boolean globalRotation) {
this.animation = animation;
this.globalRotation = globalRotation;
}
public BlueprintAnimation getAnimation() {
return this.animation;
}
public boolean isGlobalRotation() {
return this.globalRotation;
}
}
@@ -0,0 +1,249 @@
package com.ticxo.modelengine.api.animation.handler;
import com.ticxo.modelengine.api.animation.BlueprintAnimation;
import com.ticxo.modelengine.api.animation.ModelState;
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.model.ActiveModel;
import com.ticxo.modelengine.api.model.ModeledEntity;
import com.ticxo.modelengine.api.model.bone.ModelBone;
import com.ticxo.modelengine.api.utils.data.io.DataIO;
import com.ticxo.modelengine.api.utils.data.io.SavedData;
import java.util.Map;
import java.util.function.UnaryOperator;
import org.jetbrains.annotations.Nullable;
public interface AnimationHandler extends DataIO {
ActiveModel getActiveModel();
void prepare();
void updateBone(ModelBone var1);
default void updateBone(ModelBone bone, @Nullable UnaryOperator<IAnimationProperty> propertyMapper) {
this.updateBone(bone);
}
boolean hasFinishedAllAnimations();
void setDefaultProperty(AnimationHandler.DefaultProperty var1);
AnimationHandler.DefaultProperty getDefaultProperty(ModelState var1);
void tickGlobal();
@Nullable
IAnimationProperty playAnimation(String var1, double var2, double var4, double var6, boolean var8);
boolean playAnimation(IAnimationProperty var1, boolean var2);
boolean isPlayingAnimation(String var1);
void stopAnimation(String var1);
void forceStopAnimation(String var1);
void forceStopAllAnimations();
@Nullable
IAnimationProperty getAnimation(String var1);
Map<String, IAnimationProperty> getAnimations();
String getId();
default boolean isWalking(ActiveModel activeModel) {
ModeledEntity modeledEntity = activeModel.getModeledEntity();
BaseEntity<?> baseEntity = modeledEntity.getBase();
return !modeledEntity.getRootMotionHandler().isQueued() && baseEntity.isWalking();
}
@Override
default void save(SavedData data) {
SavedData defaultData = new SavedData();
for (ModelState state : ModelState.values()) {
AnimationHandler.DefaultProperty property = this.getDefaultProperty(state);
SavedData propertyData = new SavedData();
propertyData.putDouble("lerp_in", property.lerpIn);
propertyData.putDouble("lerp_out", property.lerpOut);
propertyData.putDouble("speed", property.speed);
defaultData.putData(state.name(), propertyData);
}
data.putData("defaults", defaultData);
data.putString("id", this.getId());
}
@Override
default void load(SavedData data) {
data.getData("defaults")
.ifPresent(
defaultData -> {
for (String key : defaultData.keySet()) {
ModelState state = ModelState.get(key);
defaultData.getData(key)
.ifPresent(
propertyData -> this.setDefaultProperty(
new AnimationHandler.DefaultProperty(
state, propertyData.getDouble("lerp_in"), propertyData.getDouble("lerp_out"), propertyData.getDouble("speed")
)
)
);
}
}
);
}
public static class DefaultProperty {
private final ModelState state;
private final String animation;
private final double lerpIn;
private final double lerpOut;
private final double speed;
private final boolean merge;
public DefaultProperty(ModelState state, double lerpIn, double lerpOut, double speed) {
this(state, state.getString(), lerpIn, lerpOut, speed, false);
}
public DefaultProperty(ModelState state, double lerpIn, double lerpOut, double speed, boolean merge) {
this(state, state.getString(), lerpIn, lerpOut, speed, merge);
}
public DefaultProperty(ModelState state, String animation, double lerpIn, double lerpOut, double speed) {
this(state, animation, lerpIn, lerpOut, speed, false);
}
public DefaultProperty(ModelState state, String animation, double lerpIn, double lerpOut, double speed, boolean merge) {
this.state = state;
this.animation = animation;
this.lerpIn = lerpIn;
this.lerpOut = lerpOut;
this.speed = speed;
this.merge = merge;
}
public IAnimationProperty build(ActiveModel model) {
return this.build(model, this.lerpIn, this.lerpOut, this.speed);
}
public IAnimationProperty build(ActiveModel model, double lerpIn, double lerpOut, double speed) {
BlueprintAnimation blueprintAnimation = model.getBlueprint().getAnimations().get(this.animation);
if (blueprintAnimation == null) {
return null;
} else {
SimpleProperty property = new SimpleProperty(model, blueprintAnimation, lerpIn, lerpOut, speed);
property.setSkipLastFrame(true);
return property;
}
}
public IAnimationProperty buildRef(ActiveModel model) {
return this.buildRef(model, this.lerpIn, this.lerpOut, this.speed);
}
public IAnimationProperty buildRef(ActiveModel model, double lerpIn, double lerpOut, double speed) {
BlueprintAnimation blueprintAnimation = model.getBlueprint().getAnimationOrRef(this.animation);
if (blueprintAnimation == null) {
return null;
} else {
SimpleProperty property = new SimpleProperty(model, blueprintAnimation, lerpIn, lerpOut, speed);
property.setSkipLastFrame(true);
return property;
}
}
public ModelState getState() {
return this.state;
}
public String getAnimation() {
return this.animation;
}
public double getLerpIn() {
return this.lerpIn;
}
public double getLerpOut() {
return this.lerpOut;
}
public double getSpeed() {
return this.speed;
}
public boolean isMerge() {
return this.merge;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof AnimationHandler.DefaultProperty 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 if (this.isMerge() != other.isMerge()) {
return false;
} else {
Object this$state = this.getState();
Object other$state = other.getState();
if (this$state == null ? other$state == null : this$state.equals(other$state)) {
Object this$animation = this.getAnimation();
Object other$animation = other.getAnimation();
return this$animation == null ? other$animation == null : this$animation.equals(other$animation);
} else {
return false;
}
}
}
protected boolean canEqual(Object other) {
return other instanceof AnimationHandler.DefaultProperty;
}
@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);
result = result * 59 + (this.isMerge() ? 79 : 97);
Object $state = this.getState();
result = result * 59 + ($state == null ? 43 : $state.hashCode());
Object $animation = this.getAnimation();
return result * 59 + ($animation == null ? 43 : $animation.hashCode());
}
@Override
public String toString() {
return "AnimationHandler.DefaultProperty(state="
+ this.getState()
+ ", animation="
+ this.getAnimation()
+ ", lerpIn="
+ this.getLerpIn()
+ ", lerpOut="
+ this.getLerpOut()
+ ", speed="
+ this.getSpeed()
+ ", merge="
+ this.isMerge()
+ ")";
}
}
}
@@ -0,0 +1,44 @@
package com.ticxo.modelengine.api.animation.handler;
import com.ticxo.modelengine.api.animation.BlueprintAnimation;
import com.ticxo.modelengine.api.animation.ModelState;
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
import com.ticxo.modelengine.api.animation.property.SimpleProperty;
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
import com.ticxo.modelengine.api.utils.MiscUtils;
import java.util.function.BiConsumer;
import org.jetbrains.annotations.Nullable;
public interface IPriorityHandler extends AnimationHandler {
void forEachProperty(BiConsumer<String, IAnimationProperty> var1);
void playState(ModelState var1);
@Nullable
default IAnimationProperty playAnimation(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.getActiveModel(), blueprintAnimation, lerpIn, lerpOut, speed);
return this.playAnimation(property, force) ? property : null;
}
}
default void stopAnimation(ModelBlueprint source, String animation) {
this.stopAnimation(this.resolveAnimationName(source, animation));
}
default void forceStopAnimation(ModelBlueprint source, String animation) {
this.forceStopAnimation(this.resolveAnimationName(source, animation));
}
private String resolveAnimationName(ModelBlueprint source, String animation) {
return source == this.getActiveModel().getBlueprint() ? animation : MiscUtils.createAnimationRef(source.getName(), animation);
}
@Override
default String getId() {
return "priority";
}
}
@@ -0,0 +1,52 @@
package com.ticxo.modelengine.api.animation.handler;
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
import org.jetbrains.annotations.Nullable;
public interface IStateMachineHandler extends AnimationHandler {
ModelBlueprint getBlueprint();
@Nullable
default IAnimationProperty getAnimation(int priority, String animation) {
return this.getAnimation(priority, this.getBlueprint(), animation);
}
@Nullable
IAnimationProperty getAnimation(int var1, ModelBlueprint var2, String var3);
@Nullable
default IAnimationProperty playAnimation(int priority, String animation, double lerpIn, double lerpOut, double speed, boolean force) {
return this.playAnimation(priority, this.getBlueprint(), animation, lerpIn, lerpOut, speed, force);
}
@Nullable
IAnimationProperty playAnimation(int var1, ModelBlueprint var2, String var3, double var4, double var6, double var8, boolean var10);
boolean playAnimation(int var1, IAnimationProperty var2, boolean var3);
void refreshState(AnimationHandler.DefaultProperty var1);
default boolean isPlayingAnimation(int priority, String animation) {
return this.isPlayingAnimation(priority, this.getBlueprint(), animation);
}
boolean isPlayingAnimation(int var1, ModelBlueprint var2, String var3);
default void stopAnimation(int priority, String animation) {
this.stopAnimation(priority, this.getBlueprint(), animation);
}
void stopAnimation(int var1, ModelBlueprint var2, String var3);
default void forceStopAnimation(int priority, String animation) {
this.forceStopAnimation(priority, this.getBlueprint(), animation);
}
void forceStopAnimation(int var1, ModelBlueprint var2, String var3);
@Override
default String getId() {
return "state_machine";
}
}
@@ -0,0 +1,101 @@
package com.ticxo.modelengine.api.animation.interpolator;
import com.ticxo.modelengine.api.animation.keyframe.type.AbstractKeyframe;
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
import com.ticxo.modelengine.api.model.bone.ModelBone;
import java.util.TreeMap;
import java.util.Map.Entry;
import java.util.function.Supplier;
import org.jetbrains.annotations.Nullable;
public class KeyframeInterpolator<IN extends AbstractKeyframe<OUT>, OUT> extends TreeMap<Float, IN> {
protected KeyframeInterpolator.Interpolation<IN, OUT> interpolateFunc;
protected Supplier<OUT> defaultValue = null;
public KeyframeInterpolator<IN, OUT> setInterpolateFunc(KeyframeInterpolator.Interpolation<IN, OUT> interpolateFunc) {
this.interpolateFunc = interpolateFunc;
return this;
}
public KeyframeInterpolator<IN, OUT> setDefaultValue(Supplier<OUT> value) {
this.defaultValue = value;
return this;
}
@Nullable
public OUT interpolate(ModelBone bone, IAnimationProperty property) {
if (this.isEmpty()) {
return this.defaultValue.get();
} else {
float time = (float)property.getTime();
Entry<Float, IN> lastEntry = this.floorEntry(time);
if (lastEntry != null && Float.compare(lastEntry.getKey(), time) == 0) {
return lastEntry.getValue().getValue(0, property);
} else {
Entry<Float, IN> nextEntry = this.higherEntry(time);
if (nextEntry == null) {
nextEntry = this.lastEntry();
}
if (lastEntry == null) {
lastEntry = this.firstEntry();
}
float nextKey = nextEntry.getKey();
float lastKey = lastEntry.getKey();
if (nextKey == lastKey) {
return lastEntry.getValue().getValue(0, property);
} else {
float t = (time - lastKey) / (nextKey - lastKey);
IN nextFrame = nextEntry.getValue();
IN prevFrame = lastEntry.getValue();
OUT next = nextFrame.getValue(0, property);
OUT prev = prevFrame.getValue(0, property);
return this.interpolateFunc
.interpolate(new KeyframeInterpolator.Context<>(lastKey, nextKey, prevFrame, nextFrame, property, bone, this), prev, next, t);
}
}
}
}
public OUT interpolateAndDerive(ModelBone bone, IAnimationProperty property) {
throw new UnsupportedOperationException();
}
public float getHigherKey(float time) {
Float high = this.higherKey(time);
return high == null ? this.lastKey() : high;
}
public float getLowerKey(float time) {
Float low = this.lowerKey(time);
return low == null ? this.firstKey() : low;
}
public static class Context<IN extends AbstractKeyframe<OUT>, OUT> {
public final float prevKey;
public final float nextKey;
public final IN prevFrame;
public final IN nextFrame;
public final IAnimationProperty property;
public final ModelBone bone;
public final KeyframeInterpolator<IN, OUT> interpolator;
public Context(
float prevKey, float nextKey, IN prevFrame, IN nextFrame, IAnimationProperty property, ModelBone bone, KeyframeInterpolator<IN, OUT> interpolator
) {
this.prevKey = prevKey;
this.nextKey = nextKey;
this.prevFrame = prevFrame;
this.nextFrame = nextFrame;
this.property = property;
this.bone = bone;
this.interpolator = interpolator;
}
}
@FunctionalInterface
public interface Interpolation<IN extends AbstractKeyframe<OUT>, OUT> {
OUT interpolate(KeyframeInterpolator.Context<IN, OUT> var1, OUT var2, OUT var3, float var4);
}
}
@@ -0,0 +1,93 @@
package com.ticxo.modelengine.api.animation.interpolator;
import com.ticxo.modelengine.api.animation.keyframe.type.AbstractKeyframe;
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
import com.ticxo.modelengine.api.model.bone.ModelBone;
import com.ticxo.modelengine.api.utils.math.TMath;
import java.util.Map.Entry;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import org.jetbrains.annotations.Nullable;
public class PrePostInterpolator<IN extends AbstractKeyframe<OUT>, OUT> extends KeyframeInterpolator<IN, OUT> {
private final BiFunction<OUT, OUT, OUT> derivativeFunc;
private final BiConsumer<KeyframeInterpolator.Context<IN, OUT>, IN> finalizerFunc;
public PrePostInterpolator(
KeyframeInterpolator.Interpolation<IN, OUT> interpolateFunc,
BiConsumer<KeyframeInterpolator.Context<IN, OUT>, IN> finalizerFunc,
BiFunction<OUT, OUT, OUT> derivativeFunc
) {
this(interpolateFunc, finalizerFunc, derivativeFunc, () -> null);
}
public PrePostInterpolator(
KeyframeInterpolator.Interpolation<IN, OUT> interpolateFunc,
BiConsumer<KeyframeInterpolator.Context<IN, OUT>, IN> finalizerFunc,
BiFunction<OUT, OUT, OUT> derivativeFunc,
Supplier<OUT> def
) {
this.setInterpolateFunc(interpolateFunc);
this.derivativeFunc = derivativeFunc;
this.finalizerFunc = finalizerFunc;
this.setDefaultValue(def);
}
@Nullable
@Override
public OUT interpolate(ModelBone bone, IAnimationProperty property) {
return this.interpolate(bone, property, (float)property.getTime());
}
@Override
public OUT interpolateAndDerive(ModelBone bone, IAnimationProperty property) {
float time = (float)property.getTime();
float lastTime = (float)TMath.clamp(property.getLastTime(), 0.0, property.getTime());
OUT curr = this.interpolate(bone, property, time);
if (TMath.isSimilar(time, lastTime)) {
return this.derivativeFunc.apply(curr, curr);
} else {
OUT prev = this.interpolate(bone, property, lastTime);
return this.derivativeFunc.apply(prev, curr);
}
}
@Nullable
private OUT interpolate(ModelBone bone, IAnimationProperty property, float time) {
if (this.isEmpty()) {
return this.defaultValue.get();
} else {
Entry<Float, IN> lastEntry = this.floorEntry(time);
if (lastEntry != null && Float.compare(lastEntry.getKey(), time) == 0) {
IN exact = lastEntry.getValue();
this.finalizerFunc.accept(new KeyframeInterpolator.Context<>(time, time, exact, exact, property, bone, this), exact);
return exact.getValue(0, property);
} else {
Entry<Float, IN> nextEntry = this.higherEntry(time);
if (nextEntry == null) {
nextEntry = this.lastEntry();
}
if (lastEntry == null) {
lastEntry = this.firstEntry();
}
float nextKey = nextEntry.getKey();
float lastKey = lastEntry.getKey();
IN nextFrame = nextEntry.getValue();
IN prevFrame = lastEntry.getValue();
if (nextKey == lastKey) {
this.finalizerFunc.accept(new KeyframeInterpolator.Context<>(lastKey, nextKey, prevFrame, nextFrame, property, bone, this), prevFrame);
return prevFrame.getValue(0, property);
} else {
float t = (time - lastKey) / (nextKey - lastKey);
OUT next = nextFrame.getValue(0, property);
OUT prev = prevFrame.getValue(1, property);
return this.interpolateFunc
.interpolate(new KeyframeInterpolator.Context<>(lastKey, nextKey, prevFrame, nextFrame, property, bone, this), prev, next, t);
}
}
}
}
}
@@ -0,0 +1,47 @@
package com.ticxo.modelengine.api.animation.interpolator;
import com.ticxo.modelengine.api.animation.keyframe.type.AbstractKeyframe;
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
import com.ticxo.modelengine.api.model.bone.ModelBone;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import org.jetbrains.annotations.Nullable;
public class ScriptInterpolator<IN extends AbstractKeyframe<OUT>, OUT> extends KeyframeInterpolator<IN, OUT> {
private final Supplier<OUT> supplier;
private final BiConsumer<OUT, OUT> combiner;
@Nullable
@Override
public OUT interpolate(ModelBone bone, IAnimationProperty property) {
if (this.isEmpty()) {
return null;
} else {
OUT combined = this.supplier.get();
float lastTime = (float)property.getLastTime();
float currTime = (float)property.getTime();
float frame = lastTime;
float lastFrame = this.lastKey();
if (lastTime > currTime) {
while (frame < lastFrame && (frame = this.getHigherKey(frame)) <= lastFrame) {
OUT data = this.get(frame).getValue(0, property);
this.combiner.accept(combined, data);
}
frame = -1.0F;
}
while (frame < lastFrame && (frame = this.getHigherKey(frame)) <= currTime) {
OUT data = this.get(frame).getValue(0, property);
this.combiner.accept(combined, data);
}
return combined;
}
}
public ScriptInterpolator(Supplier<OUT> supplier, BiConsumer<OUT, OUT> combiner) {
this.supplier = supplier;
this.combiner = combiner;
}
}
@@ -0,0 +1,177 @@
package com.ticxo.modelengine.api.animation.keyframe;
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.handler.IStateMachineHandler;
import com.ticxo.modelengine.api.animation.interpolator.KeyframeInterpolator;
import com.ticxo.modelengine.api.animation.keyframe.type.AbstractKeyframe;
import com.ticxo.modelengine.api.model.ActiveModel;
import com.ticxo.modelengine.api.model.bone.ModelBone;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
public class KeyframeType<KEY extends AbstractKeyframe<DATA>, DATA> {
private final String id;
private final Supplier<KEY> keyframeSupplier;
private final Function<Timeline, KeyframeInterpolator<KEY, DATA>> interpolatorSupplier;
private final Map<Class<?>, KeyframeType.ModelUpdater> modelUpdaters;
private final Map<Class<?>, KeyframeType.BoneUpdater> boneUpdaters;
private final boolean global;
private final KeyframeType.ModelUpdater priorityModelUpdater;
private final KeyframeType.ModelUpdater stateMachineModelUpdater;
private final KeyframeType.BoneUpdater priorityBoneUpdater;
private final KeyframeType.BoneUpdater stateMachineBoneUpdater;
protected KeyframeType(
String id,
Supplier<KEY> keyframeSupplier,
Function<Timeline, KeyframeInterpolator<KEY, DATA>> interpolatorSupplier,
Map<Class<?>, KeyframeType.ModelUpdater> modelUpdaters,
Map<Class<?>, KeyframeType.BoneUpdater> boneUpdaters,
boolean global
) {
this.id = id;
this.keyframeSupplier = keyframeSupplier;
this.interpolatorSupplier = interpolatorSupplier;
this.modelUpdaters = modelUpdaters;
this.boneUpdaters = boneUpdaters;
this.global = global;
this.priorityModelUpdater = modelUpdaters.get(IPriorityHandler.class);
this.stateMachineModelUpdater = modelUpdaters.get(IStateMachineHandler.class);
this.priorityBoneUpdater = boneUpdaters.get(IPriorityHandler.class);
this.stateMachineBoneUpdater = boneUpdaters.get(IStateMachineHandler.class);
}
public KeyframeInterpolator<KEY, DATA> createInterpolator(Timeline animation) {
return this.interpolatorSupplier.apply(animation);
}
public KEY createKeyframe() {
return this.keyframeSupplier.get();
}
public void updateModel(Class<?> handlerClass, AnimationHandler handler, Object... data) {
KeyframeType.ModelUpdater updater;
if (handlerClass == IPriorityHandler.class) {
updater = this.priorityModelUpdater;
} else if (handlerClass == IStateMachineHandler.class) {
updater = this.stateMachineModelUpdater;
} else {
updater = this.modelUpdaters.get(handlerClass);
}
if (updater != null) {
updater.update(handler, handler.getActiveModel(), data);
}
}
public void updateBone(Class<?> handlerClass, AnimationHandler handler, ModelBone bone, Object... data) {
KeyframeType.BoneUpdater updater;
if (handlerClass == IPriorityHandler.class) {
updater = this.priorityBoneUpdater;
} else if (handlerClass == IStateMachineHandler.class) {
updater = this.stateMachineBoneUpdater;
} else {
updater = this.boneUpdaters.get(handlerClass);
}
if (updater != null) {
updater.update(handler, bone, data);
}
}
public String getId() {
return this.id;
}
public Supplier<KEY> getKeyframeSupplier() {
return this.keyframeSupplier;
}
public Function<Timeline, KeyframeInterpolator<KEY, DATA>> getInterpolatorSupplier() {
return this.interpolatorSupplier;
}
public Map<Class<?>, KeyframeType.ModelUpdater> getModelUpdaters() {
return this.modelUpdaters;
}
public Map<Class<?>, KeyframeType.BoneUpdater> getBoneUpdaters() {
return this.boneUpdaters;
}
public boolean isGlobal() {
return this.global;
}
public KeyframeType.ModelUpdater getPriorityModelUpdater() {
return this.priorityModelUpdater;
}
public KeyframeType.ModelUpdater getStateMachineModelUpdater() {
return this.stateMachineModelUpdater;
}
public KeyframeType.BoneUpdater getPriorityBoneUpdater() {
return this.priorityBoneUpdater;
}
public KeyframeType.BoneUpdater getStateMachineBoneUpdater() {
return this.stateMachineBoneUpdater;
}
@FunctionalInterface
public interface BoneUpdater {
void update(AnimationHandler var1, ModelBone var2, Object... var3);
}
public static class Builder<KEY extends AbstractKeyframe<DATA>, DATA> {
private final String id;
private final Supplier<KEY> keyframeSupplier;
private final Map<Class<?>, KeyframeType.ModelUpdater> modelUpdaters = new HashMap<>();
private final Map<Class<?>, KeyframeType.BoneUpdater> boneUpdaters = new HashMap<>();
private Function<Timeline, KeyframeInterpolator<KEY, DATA>> interpolatorSupplier = blueprintAnimation -> new KeyframeInterpolator<>();
private boolean global;
public static <KEY extends AbstractKeyframe<DATA>, DATA> KeyframeType.Builder<KEY, DATA> of(String id, Supplier<KEY> keyframeSupplier) {
return new KeyframeType.Builder<>(id, keyframeSupplier);
}
public KeyframeType.Builder<KEY, DATA> interpolator(Function<Timeline, KeyframeInterpolator<KEY, DATA>> interpolatorSupplier) {
this.interpolatorSupplier = interpolatorSupplier;
return this;
}
public KeyframeType.Builder<KEY, DATA> registerModelUpdater(Class<?> handlerClass, KeyframeType.ModelUpdater updater) {
this.modelUpdaters.put(handlerClass, updater);
return this;
}
public KeyframeType.Builder<KEY, DATA> registerBoneUpdater(Class<?> handlerClass, KeyframeType.BoneUpdater updater) {
this.boneUpdaters.put(handlerClass, updater);
return this;
}
public KeyframeType.Builder<KEY, DATA> global() {
this.global = true;
return this;
}
public KeyframeType<KEY, DATA> build() {
return new KeyframeType<>(this.id, this.keyframeSupplier, this.interpolatorSupplier, this.modelUpdaters, this.boneUpdaters, this.global);
}
protected Builder(String id, Supplier<KEY> keyframeSupplier) {
this.id = id;
this.keyframeSupplier = keyframeSupplier;
}
}
@FunctionalInterface
public interface ModelUpdater {
void update(AnimationHandler var1, ActiveModel var2, Object... var3);
}
}
@@ -0,0 +1,19 @@
package com.ticxo.modelengine.api.animation.keyframe;
import com.ticxo.modelengine.api.utils.registry.TUnaryRegistry;
import java.util.LinkedHashSet;
import java.util.Set;
public class KeyframeTypeRegistry extends TUnaryRegistry<KeyframeType<?, ?>> {
private final Set<String> keys = new LinkedHashSet<>();
public void registerKeyframeType(KeyframeType<?, ?> type) {
this.keys.add(type.getId());
this.register(type.getId(), type);
}
@Override
public Set<String> getKeys() {
return this.keys;
}
}
@@ -0,0 +1,464 @@
package com.ticxo.modelengine.api.animation.keyframe;
import com.ticxo.modelengine.api.ModelEngineAPI;
import com.ticxo.modelengine.api.animation.handler.AnimationHandler;
import com.ticxo.modelengine.api.animation.handler.IPriorityHandler;
import com.ticxo.modelengine.api.animation.handler.IStateMachineHandler;
import com.ticxo.modelengine.api.animation.interpolator.KeyframeInterpolator;
import com.ticxo.modelengine.api.animation.interpolator.PrePostInterpolator;
import com.ticxo.modelengine.api.animation.interpolator.ScriptInterpolator;
import com.ticxo.modelengine.api.animation.keyframe.type.ScriptKeyframe;
import com.ticxo.modelengine.api.animation.keyframe.type.VectorKeyframe;
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
import com.ticxo.modelengine.api.animation.script.ScriptReader;
import com.ticxo.modelengine.api.model.ActiveModel;
import com.ticxo.modelengine.api.utils.StepFlag;
import com.ticxo.modelengine.api.utils.math.SafeTransform;
import com.ticxo.modelengine.api.utils.math.TMath;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import org.jetbrains.annotations.Nullable;
import org.joml.Vector3f;
public final class KeyframeTypes {
public static final KeyframeType<VectorKeyframe, Vector3f> POSITION = KeyframeType.Builder.<VectorKeyframe, Vector3f>of("position", VectorKeyframe::new)
.interpolator(
timeline -> new PrePostInterpolator<>(
(ctx, prev, next, ratio) -> standard(ctx, prev, next, ratio, StepFlag.POSITION),
(ctx, vectorKeyframe) -> markStep(ctx, vectorKeyframe, StepFlag.POSITION),
KeyframeTypes::derive
)
)
.registerBoneUpdater(IPriorityHandler.class, (handler, bone, data) -> {
IAnimationProperty property = (IAnimationProperty)data[0];
SafeTransform transform = bone.getLocalTransform();
Vector3f output = transform.getPosition();
if (bone.isRootBone()) {
if (property.getPhase() == IAnimationProperty.Phase.PLAY) {
Vector3f vel = property.getVelocityFrame(bone);
if (vel == null && property.isEmptyZero()) {
vel = new Vector3f();
}
if (vel != null) {
if (property.isOverride()) {
output.set(bone.getBlueprintBone().getLocalPosition());
}
output.add(vel);
}
transform.setPosition(output);
Vector3f val = property.getPositionFrame(bone);
bone.setBoneOnGround(val == null || TMath.isSimilar(val.y, 0.0F));
}
} else {
Vector3f val = property.getPositionFrame(bone);
if (!property.isOverride()) {
if (val == null) {
val = new Vector3f();
}
switch (property.getPhase()) {
case LERPOUT:
val = TMath.lerp(val, new Vector3f(), property.getLerpOutRatio());
break;
case LERPIN:
val = TMath.lerp(new Vector3f(), val, property.getLerpInRatio());
}
output.add(val);
} else {
if (val == null && property.isEmptyZero()) {
val = new Vector3f();
}
if (val != null) {
Vector3f local = bone.getBlueprintBone().getLocalPosition();
switch (property.getPhase()) {
case PLAY:
output.set(local).add(val);
break;
case LERPOUT:
output.set(TMath.lerp(val.add(local), output, property.getLerpOutRatio()));
break;
case LERPIN:
output.set(TMath.lerp(output, val.add(local), property.getLerpInRatio()));
}
}
}
transform.setPosition(output);
}
})
.registerBoneUpdater(IStateMachineHandler.class, (handler, bone, data) -> {
IAnimationProperty currProperty = (IAnimationProperty)data[0];
if (currProperty != null) {
SafeTransform transform = bone.getLocalTransform();
if (bone.isRootBone()) {
Vector3f output = transform.getPosition();
if (currProperty.getPhase() == IAnimationProperty.Phase.PLAY) {
Vector3f vel = currProperty.getVelocityFrame(bone);
if (vel == null && currProperty.isEmptyZero()) {
vel = new Vector3f();
}
if (vel != null) {
if (currProperty.isOverride()) {
output.set(bone.getBlueprintBone().getLocalPosition());
}
output.add(vel);
}
transform.setPosition(output);
Vector3f val = currProperty.getPositionFrame(bone);
bone.setBoneOnGround(val == null || TMath.isSimilar(val.y, 0.0F));
}
} else {
Vector3f currVal = new Vector3f(transform.getPosition());
Vector3f val = currProperty.getPositionFrame(bone);
if (val == null && currProperty.isEmptyZero()) {
val = new Vector3f();
}
if (val != null) {
if (currProperty.isOverride()) {
currVal.set(bone.getBlueprintBone().getLocalPosition());
}
currVal.add(val);
}
switch (currProperty.getPhase()) {
case PLAY:
transform.setPosition(currVal);
return;
case LERPOUT:
transform.setPosition(TMath.lerp(currVal, transform.getPosition(), currProperty.getLerpOutRatio()));
return;
default:
IAnimationProperty lastProperty = (IAnimationProperty)data[1];
if (lastProperty == null) {
transform.setPosition(TMath.lerp(transform.getPosition(), currVal, currProperty.getLerpInRatio()));
return;
}
Vector3f lastVal = new Vector3f(transform.getPosition());
Vector3f valx = lastProperty.getPositionFrame(bone);
if (valx == null && lastProperty.isEmptyZero()) {
valx = new Vector3f();
}
if (valx != null) {
if (lastProperty.isOverride()) {
lastVal.set(bone.getBlueprintBone().getLocalPosition());
}
lastVal.add(valx);
}
transform.setPosition(TMath.lerp(lastVal, currVal, currProperty.getLerpInRatio()));
}
}
}
})
.build();
public static final KeyframeType<VectorKeyframe, Vector3f> ROTATION = KeyframeType.Builder.<VectorKeyframe, Vector3f>of("rotation", VectorKeyframe::new)
.interpolator(
timeline -> new PrePostInterpolator<>(
(ctx, prev, next, ratio) -> standard(ctx, prev, next, ratio, StepFlag.ROTATION),
(ctx, vectorKeyframe) -> markStep(ctx, vectorKeyframe, StepFlag.ROTATION),
KeyframeTypes::derive
)
)
.registerBoneUpdater(IPriorityHandler.class, (handler, bone, data) -> {
IAnimationProperty property = (IAnimationProperty)data[0];
SafeTransform transform = bone.getLocalTransform();
Vector3f output = transform.getLeftEuler();
Vector3f val = property.getRotationFrame(bone);
if (!property.isOverride()) {
if (val == null) {
val = new Vector3f();
}
switch (property.getPhase()) {
case LERPOUT:
val = TMath.slerp(val, new Vector3f(), property.getLerpOutRatio());
break;
case LERPIN:
val = TMath.slerp(new Vector3f(), val, property.getLerpInRatio());
}
output.add(val);
} else {
if (val == null && property.isEmptyZero()) {
val = new Vector3f();
}
if (val != null) {
Vector3f local = bone.getBlueprintBone().getLocalRotation();
switch (property.getPhase()) {
case PLAY:
output.set(local).add(val);
break;
case LERPOUT:
output.set(TMath.slerp(val.add(local), output, property.getLerpOutRatio()));
break;
case LERPIN:
output.set(TMath.slerp(output, val.add(local), property.getLerpInRatio()));
}
}
}
transform.setLeftEuler(output);
})
.registerBoneUpdater(IStateMachineHandler.class, (handler, bone, data) -> {
IAnimationProperty currProperty = (IAnimationProperty)data[0];
if (currProperty != null) {
SafeTransform transform = bone.getLocalTransform();
Vector3f currVal = new Vector3f(transform.getLeftEuler());
Vector3f val = currProperty.getRotationFrame(bone);
if (val == null && currProperty.isEmptyZero()) {
val = new Vector3f();
}
if (val != null) {
if (currProperty.isOverride()) {
currVal.set(bone.getBlueprintBone().getLocalRotation());
}
currVal.add(val);
}
switch (currProperty.getPhase()) {
case PLAY:
transform.setLeftEuler(currVal);
return;
case LERPOUT:
transform.setLeftEuler(TMath.slerp(currVal, transform.getLeftEuler(), currProperty.getLerpOutRatio()));
return;
default:
IAnimationProperty lastProperty = (IAnimationProperty)data[1];
if (lastProperty == null) {
transform.setLeftEuler(TMath.slerp(transform.getLeftEuler(), currVal, currProperty.getLerpInRatio()));
} else {
Vector3f lastVal = new Vector3f(transform.getLeftEuler());
Vector3f valx = lastProperty.getRotationFrame(bone);
if (valx == null && lastProperty.isEmptyZero()) {
valx = new Vector3f();
}
if (valx != null) {
if (lastProperty.isOverride()) {
lastVal.set(bone.getBlueprintBone().getLocalRotation());
}
lastVal.add(valx);
}
transform.setLeftEuler(TMath.slerp(lastVal, currVal, currProperty.getLerpInRatio()));
}
}
}
})
.build();
public static final KeyframeType<VectorKeyframe, Vector3f> SCALE = KeyframeType.Builder.<VectorKeyframe, Vector3f>of("scale", VectorKeyframe::new)
.interpolator(
timeline -> new PrePostInterpolator<>(
(ctx, prev, next, ratio) -> standard(ctx, prev, next, ratio, StepFlag.SCALE),
(ctx, vectorKeyframe) -> markStep(ctx, vectorKeyframe, StepFlag.SCALE),
KeyframeTypes::derive
)
)
.registerBoneUpdater(IPriorityHandler.class, (handler, bone, data) -> {
IAnimationProperty property = (IAnimationProperty)data[0];
SafeTransform transform = bone.getLocalTransform();
Vector3f output = transform.getScale();
Vector3f val = property.getScaleFrame(bone);
if (!property.isOverride()) {
if (val == null) {
val = new Vector3f(1.0F);
}
switch (property.getPhase()) {
case LERPOUT:
val = TMath.lerp(val, new Vector3f(1.0F), property.getLerpOutRatio());
break;
case LERPIN:
val = TMath.lerp(new Vector3f(1.0F), val, property.getLerpInRatio());
}
output.mul(val);
} else {
if (val == null && property.isEmptyZero()) {
val = new Vector3f(1.0F);
}
if (val != null) {
switch (property.getPhase()) {
case PLAY:
output.set(val);
break;
case LERPOUT:
output.set(TMath.lerp(val, output, property.getLerpOutRatio()));
break;
case LERPIN:
output.set(TMath.lerp(output, val, property.getLerpInRatio()));
}
}
}
transform.setScale(output);
})
.registerBoneUpdater(IStateMachineHandler.class, (handler, bone, data) -> {
IAnimationProperty currProperty = (IAnimationProperty)data[0];
if (currProperty != null) {
SafeTransform transform = bone.getLocalTransform();
Vector3f currVal = new Vector3f(transform.getScale());
Vector3f val = currProperty.getScaleFrame(bone);
if (val == null && currProperty.isEmptyZero()) {
val = new Vector3f(1.0F);
}
if (val != null) {
if (currProperty.isOverride()) {
currVal.set(1.0F);
}
currVal.mul(val);
}
switch (currProperty.getPhase()) {
case PLAY:
transform.setScale(currVal);
return;
case LERPOUT:
transform.setScale(TMath.lerp(currVal, transform.getScale(), currProperty.getLerpOutRatio()));
return;
default:
IAnimationProperty lastProperty = (IAnimationProperty)data[1];
if (lastProperty == null) {
transform.setScale(TMath.lerp(transform.getScale(), currVal, currProperty.getLerpInRatio()));
} else {
Vector3f lastVal = new Vector3f(transform.getScale());
Vector3f valx = lastProperty.getScaleFrame(bone);
if (valx == null && lastProperty.isEmptyZero()) {
valx = new Vector3f(1.0F);
}
if (valx != null) {
if (lastProperty.isOverride()) {
lastVal.set(1.0F);
}
lastVal.mul(valx);
}
transform.setScale(TMath.lerp(lastVal, currVal, currProperty.getLerpInRatio()));
}
}
}
})
.build();
public static final KeyframeType<ScriptKeyframe, List<ScriptKeyframe.Script>> SCRIPT = KeyframeType.Builder.<ScriptKeyframe, List<ScriptKeyframe.Script>>of(
"script", ScriptKeyframe::new
)
.interpolator(blueprintAnimation -> new ScriptInterpolator<>(ArrayList::new, List::addAll))
.registerModelUpdater(IPriorityHandler.class, KeyframeTypes::standardScript)
.registerModelUpdater(IStateMachineHandler.class, KeyframeTypes::standardScript)
.global()
.build();
private static Vector3f standard(KeyframeInterpolator.Context<VectorKeyframe, Vector3f> ctx, Vector3f prev, Vector3f next, float ratio, StepFlag stepFlag) {
String animation = ctx.property.getBlueprintAnimation().getName();
String prevMode = ctx.prevFrame.getInterpolation();
if (prevMode.equals("step")) {
ctx.bone.markStep(stepFlag, animation, ctx.prevKey);
return prev;
} else {
VectorKeyframe nextFrame = ctx.nextFrame;
if (nextFrame.isDiscontinuous() && ctx.property.getTime() + ctx.property.getSpeed() * 0.05 > ctx.nextKey) {
ctx.bone.markStep(stepFlag, animation, ctx.nextKey);
}
String nextMode = nextFrame.getInterpolation();
if (prevMode.equals("catmullrom") || nextMode.equals("catmullrom")) {
Entry<Float, VectorKeyframe> nextControlEntry = ctx.interpolator.higherEntry(ctx.nextKey);
if (nextControlEntry == null) {
nextControlEntry = ctx.interpolator.lastEntry();
}
Entry<Float, VectorKeyframe> lastControlEntry = ctx.interpolator.lowerEntry(ctx.prevKey);
if (lastControlEntry == null) {
lastControlEntry = ctx.interpolator.firstEntry();
}
VectorKeyframe nextControlVector = nextControlEntry.getValue();
VectorKeyframe lastControlVector = lastControlEntry.getValue();
return TMath.smoothLerp(lastControlVector.getValue(0, ctx.property), prev, next, nextControlVector.getValue(0, ctx.property), ratio);
} else {
return !ctx.prevFrame.isBezier() && !nextFrame.isBezier()
? prev.lerp(next, ratio, new Vector3f())
: bezierLerp(ctx, ctx.prevFrame, nextFrame, prev, next, ratio);
}
}
}
private static Vector3f bezierLerp(
KeyframeInterpolator.Context<VectorKeyframe, Vector3f> ctx, VectorKeyframe prevFrame, VectorKeyframe nextFrame, Vector3f prev, Vector3f next, float ratio
) {
float gap = ctx.nextKey - ctx.prevKey;
return new Vector3f(
bezierAxis(ratio, gap, prevFrame, nextFrame, prev.x, next.x, 0),
bezierAxis(ratio, gap, prevFrame, nextFrame, prev.y, next.y, 1),
bezierAxis(ratio, gap, prevFrame, nextFrame, prev.z, next.z, 2)
);
}
private static float bezierAxis(float t, float gap, VectorKeyframe prevFrame, VectorKeyframe nextFrame, float prev, float next, int axis) {
float prevOffset = prevFrame.getRightValue()[axis] * axisFactor(prevFrame, axis);
float nextOffset = nextFrame.getLeftValue()[axis] * axisFactor(nextFrame, axis);
if (prevOffset == 0.0F && nextOffset == 0.0F) {
return TMath.lerp(prev, next, t);
} else {
float u1 = TMath.clamp(prevFrame.isBezier() ? prevFrame.getRightTime()[axis] : 0.1F, 0.0F, gap) / gap;
float u2 = 1.0F + TMath.clamp(nextFrame.isBezier() ? nextFrame.getLeftTime()[axis] : -0.1F, -gap, 0.0F) / gap;
float s = TMath.cubicBezierSolve(u1, u2, t);
return TMath.cubicBezierValue(prev, prev + prevOffset, next + nextOffset, next, s);
}
}
private static float axisFactor(VectorKeyframe frame, int axis) {
return switch (axis) {
case 0 -> frame.getXFactor();
case 1 -> frame.getYFactor();
default -> frame.getZFactor();
};
}
private static void markStep(KeyframeInterpolator.Context<VectorKeyframe, Vector3f> ctx, VectorKeyframe frame, StepFlag stepFlag) {
String animation = ctx.property.getBlueprintAnimation().getName();
if ("step".equals(frame.getInterpolation()) || frame.isDiscontinuous()) {
ctx.bone.markStep(stepFlag, animation, ctx.nextKey);
}
}
private static Vector3f derive(@Nullable Vector3f prev, @Nullable Vector3f curr) {
return prev != null && curr != null ? curr.sub(prev, new Vector3f()) : new Vector3f();
}
private static void standardScript(AnimationHandler handler, ActiveModel model, Object... data) {
IAnimationProperty property = (IAnimationProperty)data[0];
List<ScriptKeyframe.Script> scripts = property.getScriptFrame();
if (scripts != null && !scripts.isEmpty()) {
for (ScriptKeyframe.Script script : scripts) {
ScriptReader reader = ModelEngineAPI.getAPI().getScriptReaderRegistry().get(script.reader());
if (reader != null) {
reader.read(property, script.script());
}
}
}
}
}
@@ -0,0 +1,16 @@
package com.ticxo.modelengine.api.animation.keyframe.data;
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
public class DoubleData implements IKeyframeData {
private final double data;
@Override
public double getValue(IAnimationProperty property) {
return this.data;
}
public DoubleData(double data) {
this.data = data;
}
}
@@ -0,0 +1,9 @@
package com.ticxo.modelengine.api.animation.keyframe.data;
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
public interface IKeyframeData {
IKeyframeData EMPTY = property -> 0.0;
double getValue(IAnimationProperty var1);
}
@@ -0,0 +1,52 @@
package com.ticxo.modelengine.api.animation.keyframe.data;
import com.ticxo.modelengine.api.utils.logger.TLogger;
import com.ticxo.modelengine.api.utils.registry.TUnaryRegistry;
import java.util.function.Function;
public class KeyframeReaderRegistry extends TUnaryRegistry<Function<String, IKeyframeData>> {
public IKeyframeData tryParse(String data) {
if (data == null) {
return IKeyframeData.EMPTY;
} else {
data = data.trim();
if (data.isEmpty()) {
return IKeyframeData.EMPTY;
} else {
try {
return new DoubleData(Double.parseDouble(data));
} catch (NumberFormatException var10) {
String[] value = data.split(":", 2);
if (value.length == 1) {
for (Function<String, IKeyframeData> func : this.registry.values()) {
try {
return func.apply(value[0]);
} catch (Throwable var8) {
}
}
} else {
Function<String, IKeyframeData> func = this.get(value[0]);
if (func != null) {
try {
return func.apply(value[1]);
} catch (Throwable var7) {
TLogger.error(2, "------An error occurred while parsing the keyframe: " + data);
var7.printStackTrace();
}
} else {
for (Function<String, IKeyframeData> func2 : this.registry.values()) {
try {
return func2.apply(data);
} catch (Throwable var9) {
}
}
}
}
TLogger.warn(2, "------Unknown keyframe data: " + data);
return IKeyframeData.EMPTY;
}
}
}
}
}
@@ -0,0 +1,105 @@
package com.ticxo.modelengine.api.animation.keyframe.type;
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public abstract class AbstractKeyframe<T> {
protected final float[] leftTime = new float[3];
protected final float[] leftValue = new float[3];
protected final float[] rightTime = new float[3];
protected final float[] rightValue = new float[3];
@NotNull
protected String interpolation = "";
public boolean isBezier() {
return "bezier".equalsIgnoreCase(this.interpolation);
}
public void setBezierLeftTime(@Nullable Float x, @Nullable Float y, @Nullable Float z) {
if (x != null) {
this.leftTime[0] = x;
}
if (y != null) {
this.leftTime[1] = y;
}
if (z != null) {
this.leftTime[2] = z;
}
}
public void setBezierLeftValue(@Nullable Float x, @Nullable Float y, @Nullable Float z) {
if (x != null) {
this.leftValue[0] = x;
}
if (y != null) {
this.leftValue[1] = y;
}
if (z != null) {
this.leftValue[2] = z;
}
}
public void setBezierRightTime(@Nullable Float x, @Nullable Float y, @Nullable Float z) {
if (x != null) {
this.rightTime[0] = x;
}
if (y != null) {
this.rightTime[1] = y;
}
if (z != null) {
this.rightTime[2] = z;
}
}
public void setBezierRightValue(@Nullable Float x, @Nullable Float y, @Nullable Float z) {
if (x != null) {
this.rightValue[0] = x;
}
if (y != null) {
this.rightValue[1] = y;
}
if (z != null) {
this.rightValue[2] = z;
}
}
public abstract T getValue(int var1, IAnimationProperty var2);
public float[] getLeftTime() {
return this.leftTime;
}
public float[] getLeftValue() {
return this.leftValue;
}
public float[] getRightTime() {
return this.rightTime;
}
public float[] getRightValue() {
return this.rightValue;
}
@NotNull
public String getInterpolation() {
return this.interpolation;
}
public void setInterpolation(@NotNull String interpolation) {
if (interpolation == null) {
throw new NullPointerException("interpolation is marked non-null but is null");
} else {
this.interpolation = interpolation;
}
}
}
@@ -0,0 +1,23 @@
package com.ticxo.modelengine.api.animation.keyframe.type;
import com.ticxo.modelengine.api.animation.keyframe.data.IKeyframeData;
public interface IVectorType {
IVectorType setX(IKeyframeData var1);
IVectorType setY(IKeyframeData var1);
IVectorType setZ(IKeyframeData var1);
IVectorType setPostX(IKeyframeData var1);
IVectorType setPostY(IKeyframeData var1);
IVectorType setPostZ(IKeyframeData var1);
IVectorType setXFactor(float var1);
IVectorType setYFactor(float var1);
IVectorType setZFactor(float var1);
}
@@ -0,0 +1,24 @@
package com.ticxo.modelengine.api.animation.keyframe.type;
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
import java.util.ArrayList;
import java.util.List;
public class ScriptKeyframe extends AbstractKeyframe<List<ScriptKeyframe.Script>> {
private final List<ScriptKeyframe.Script> script = new ArrayList<>();
public List<ScriptKeyframe.Script> getValue(int index, IAnimationProperty property) {
return this.script;
}
public List<ScriptKeyframe.Script> getScript() {
return this.script;
}
public record Script(String reader, String script) {
public static ScriptKeyframe.Script from(String full) {
String[] split = full.split(":", 2);
return split.length <= 1 ? new ScriptKeyframe.Script("meg", split[0]) : new ScriptKeyframe.Script(split[0], split[1]);
}
}
}
@@ -0,0 +1,104 @@
package com.ticxo.modelengine.api.animation.keyframe.type;
import com.ticxo.modelengine.api.animation.keyframe.data.IKeyframeData;
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
import org.joml.Vector3f;
public class VectorKeyframe extends AbstractKeyframe<Vector3f> implements IVectorType {
private final IKeyframeData[] preVector = new IKeyframeData[3];
private final IKeyframeData[] postVector = new IKeyframeData[3];
private boolean isDiscontinuous;
private float xFactor = 1.0F;
private float yFactor = 1.0F;
private float zFactor = 1.0F;
public VectorKeyframe setX(IKeyframeData x) {
this.preVector[0] = x;
return this;
}
public VectorKeyframe setY(IKeyframeData y) {
this.preVector[1] = y;
return this;
}
public VectorKeyframe setZ(IKeyframeData z) {
this.preVector[2] = z;
return this;
}
public VectorKeyframe setPostX(IKeyframeData x) {
this.postVector[0] = x;
return this;
}
public VectorKeyframe setPostY(IKeyframeData y) {
this.postVector[1] = y;
return this;
}
public VectorKeyframe setPostZ(IKeyframeData z) {
this.postVector[2] = z;
return this;
}
@Override
public IVectorType setXFactor(float x) {
this.xFactor = x;
return this;
}
@Override
public IVectorType setYFactor(float y) {
this.yFactor = y;
return this;
}
@Override
public IVectorType setZFactor(float z) {
this.zFactor = z;
return this;
}
public Vector3f getValue(int index, IAnimationProperty property) {
return index != 0 && this.isDiscontinuous
? new Vector3f(
(float)this.postVector[0].getValue(property) * this.xFactor,
(float)this.postVector[1].getValue(property) * this.yFactor,
(float)this.postVector[2].getValue(property) * this.zFactor
)
: new Vector3f(
(float)this.preVector[0].getValue(property) * this.xFactor,
(float)this.preVector[1].getValue(property) * this.yFactor,
(float)this.preVector[2].getValue(property) * this.zFactor
);
}
public IKeyframeData[] getPreVector() {
return this.preVector;
}
public IKeyframeData[] getPostVector() {
return this.postVector;
}
public boolean isDiscontinuous() {
return this.isDiscontinuous;
}
public float getXFactor() {
return this.xFactor;
}
public float getYFactor() {
return this.yFactor;
}
public float getZFactor() {
return this.zFactor;
}
public void setDiscontinuous(boolean isDiscontinuous) {
this.isDiscontinuous = isDiscontinuous;
}
}
@@ -0,0 +1,150 @@
package com.ticxo.modelengine.api.animation.property;
import com.ticxo.modelengine.api.animation.BlueprintAnimation;
import com.ticxo.modelengine.api.animation.keyframe.KeyframeType;
import com.ticxo.modelengine.api.animation.keyframe.type.ScriptKeyframe;
import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone;
import com.ticxo.modelengine.api.model.ActiveModel;
import com.ticxo.modelengine.api.model.bone.ModelBone;
import com.ticxo.modelengine.api.utils.data.io.DataIO;
import com.ticxo.modelengine.api.utils.math.Easing;
import java.util.List;
import java.util.UUID;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.joml.Vector3f;
public interface IAnimationProperty extends DataIO {
BlueprintAnimation getBlueprintAnimation();
boolean update();
void stop();
boolean isEnded();
boolean canReplace();
String getName();
boolean containsKeyframe(KeyframeType<?, ?> var1, UUID var2);
default Vector3f getPositionFrame(ModelBone bone) {
return this.getPositionFrame(bone, this.getBlueprintBone(bone));
}
Vector3f getPositionFrame(ModelBone var1, BlueprintBone var2);
default Vector3f getVelocityFrame(ModelBone bone) {
return this.getVelocityFrame(bone, this.getBlueprintBone(bone));
}
Vector3f getVelocityFrame(ModelBone var1, BlueprintBone var2);
default Vector3f getRotationFrame(ModelBone bone) {
return this.getRotationFrame(bone, this.getBlueprintBone(bone));
}
Vector3f getRotationFrame(ModelBone var1, BlueprintBone var2);
default Vector3f getScaleFrame(ModelBone bone) {
return this.getScaleFrame(bone, this.getBlueprintBone(bone));
}
Vector3f getScaleFrame(ModelBone var1, BlueprintBone var2);
List<ScriptKeyframe.Script> getScriptFrame();
double getLerpInRatio();
double getLerpOutRatio();
boolean isFinished();
ActiveModel getModel();
double getLerpIn();
default void setLerpIn(double lerpIn) {
}
double getLerpOut();
default void setLerpOut(double lerpOut) {
}
@NotNull
default Easing getLerpCurveIn() {
return Easing.LINEAR;
}
default void setLerpCurveIn(@Nullable Easing lerpCurveIn) {
}
@NotNull
default Easing getLerpCurveOut() {
return Easing.LINEAR;
}
default void setLerpCurveOut(@Nullable Easing lerpCurveOut) {
}
double getLerpInTime();
void setLerpInTime(double var1);
double getLerpOutTime();
void setLerpOutTime(double var1);
double getLastTime();
double getTime();
double getSpeed();
void setSpeed(double var1);
@NotNull
IAnimationProperty.Phase getPhase();
BlueprintAnimation.LoopMode getForceLoopMode();
void setForceLoopMode(BlueprintAnimation.LoopMode var1);
BlueprintAnimation.LoopMode getLoopMode();
boolean isOverride();
BlueprintAnimation.OverrideMode getForceOverride();
void setForceOverride(BlueprintAnimation.OverrideMode var1);
boolean isEmptyZero();
void setEmptyZero(boolean var1);
boolean isSkipLastFrame();
void setSkipLastFrame(boolean var1);
boolean isMergeLerp();
void setMergeLerp(boolean var1);
boolean isIgnoreDeath();
void setIgnoreDeath(boolean var1);
default BlueprintBone getBlueprintBone(ModelBone bone) {
BlueprintBone bBone = bone.getBlueprintBone();
BlueprintBone bBone2 = this.getBlueprintAnimation().getModelBlueprint().getFlatMap().get(bBone.getName());
return bBone2 == null ? bBone : bBone2;
}
public static enum Phase {
LERPIN,
PLAY,
LERPOUT;
}
}
@@ -0,0 +1,574 @@
package com.ticxo.modelengine.api.animation.property;
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.handler.AnimationHandler;
import com.ticxo.modelengine.api.animation.keyframe.KeyframeType;
import com.ticxo.modelengine.api.animation.keyframe.type.ScriptKeyframe;
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.ModelBone;
import com.ticxo.modelengine.api.utils.data.io.SavedData;
import com.ticxo.modelengine.api.utils.math.Easing;
import com.ticxo.modelengine.api.utils.math.TMath;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.joml.Vector3f;
public class SimpleProperty implements IAnimationProperty {
private final ActiveModel model;
private final BlueprintAnimation blueprintAnimation;
private final String name;
private double lerpIn;
private double lerpOut;
private double lerpInTime = 0.0;
private double lerpOutTime = 0.0;
private double lastTime = -1.0;
private double time = -1.0;
private double speed;
@NotNull
private IAnimationProperty.Phase phase = IAnimationProperty.Phase.LERPIN;
private BlueprintAnimation.LoopMode forceLoopMode = null;
private BlueprintAnimation.OverrideMode forceOverride = null;
@NotNull
private Easing lerpCurveIn = Easing.LINEAR;
@NotNull
private Easing lerpCurveOut = Easing.LINEAR;
private boolean emptyZero = ModelEngineAPI.getConfigCache().isEmptyZero();
private boolean skipLastFrame;
private boolean mergeLerp = false;
private boolean ignoreDeath = false;
private boolean stopping;
private boolean ended;
private Runnable onEndTask = null;
public SimpleProperty(ActiveModel model, BlueprintAnimation blueprintAnimation) {
this(model, blueprintAnimation, 0.0, 0.0, 1.0);
}
public SimpleProperty(ActiveModel model, BlueprintAnimation blueprintAnimation, double lerpIn, double lerpOut, double speed) {
if (blueprintAnimation == null) {
throw new IllegalArgumentException("BlueprintAnimation cannot be null");
} else {
this.model = model;
this.blueprintAnimation = blueprintAnimation;
if (blueprintAnimation.getModelBlueprint() != model.getBlueprint()) {
this.name = "ref[" + blueprintAnimation.getModelBlueprint().getName() + "." + blueprintAnimation.getName() + "]";
} else {
this.name = blueprintAnimation.getName();
}
this.lerpIn = lerpIn;
this.lerpOut = lerpOut;
this.speed = speed;
}
}
@Override
public boolean update() {
this.lastTime = this.time;
boolean var10000;
if (this.mergeLerp) {
var10000 = this.mergeUpdate();
} else {
switch (this.phase) {
case LERPIN:
var10000 = this.updateLerpIn();
break;
case PLAY:
var10000 = this.updateTime();
break;
case LERPOUT:
var10000 = this.updateLerpOut();
break;
default:
throw new IncompatibleClassChangeError();
}
}
return var10000;
}
private boolean mergeUpdate() {
this.time = Math.max(this.time, 0.0);
BlueprintAnimation.LoopMode mode = this.getLoopMode();
double delta = this.speed * 0.05;
double length = this.blueprintAnimation.getLength();
boolean infiniteLoop = length <= 0.0;
if (infiniteLoop) {
this.time += delta;
} else {
switch (mode) {
case ONCE:
case HOLD:
this.time = Math.min(this.time + delta, length);
break;
case LOOP:
this.time = (this.time + delta) % (length + (this.skipLastFrame ? 0.0 : delta));
}
}
boolean reprocess = true;
while (reprocess) {
reprocess = false;
switch (this.phase) {
case LERPIN:
this.lerpInTime += delta;
if (this.lerpInTime >= this.lerpIn - 1.0E-5F) {
this.phase = this.stopping ? IAnimationProperty.Phase.LERPOUT : IAnimationProperty.Phase.PLAY;
reprocess = true;
}
break;
case PLAY:
if (this.stopping || !infiniteLoop && mode == BlueprintAnimation.LoopMode.ONCE && length - this.time <= this.lerpOut) {
this.phase = IAnimationProperty.Phase.LERPOUT;
reprocess = true;
}
break;
case LERPOUT:
this.lerpOutTime += delta;
if (this.lerpOutTime >= this.lerpOut - 1.0E-5F) {
this.ended = true;
}
}
}
return !this.ended;
}
private boolean updateLerpIn() {
if (this.lerpInTime >= this.lerpIn - 1.0E-5F) {
this.time = 0.0;
return this.stopping ? this.updateLerpOut() : this.updateTime();
} else {
this.lerpInTime = this.lerpInTime + this.speed * 0.05;
return this.playingOrLerpOut();
}
}
private boolean updateTime() {
if (this.phase == IAnimationProperty.Phase.LERPIN) {
this.phase = IAnimationProperty.Phase.PLAY;
return this.playingOrLerpOut();
} else {
double delta = this.speed * 0.05;
double length = this.blueprintAnimation.getLength();
boolean infiniteLoop = length <= 0.0;
if (infiniteLoop) {
this.time += delta;
return this.playingOrLerpOut();
} else {
BlueprintAnimation.LoopMode mode = this.getLoopMode();
switch (mode) {
case ONCE:
if (this.time < length) {
this.time = Math.min(this.time + delta, length);
return this.playingOrLerpOut();
}
return this.updateLerpOut();
case HOLD:
this.time = Math.min(this.time + delta, length);
return this.playingOrLerpOut();
case LOOP:
this.time = (this.time + delta) % (this.skipLastFrame ? length : length + delta);
return this.playingOrLerpOut();
default:
return false;
}
}
}
}
private boolean updateLerpOut() {
if (this.phase != IAnimationProperty.Phase.LERPOUT && this.lerpOut > 1.0E-5F) {
this.phase = IAnimationProperty.Phase.LERPOUT;
return true;
} else if (this.lerpOutTime >= this.lerpOut - 1.0E-5F) {
this.ended = true;
return false;
} else {
this.lerpOutTime = this.lerpOutTime + this.speed * 0.05;
return true;
}
}
private boolean playingOrLerpOut() {
return !this.stopping || this.updateLerpOut();
}
@Override
public void stop() {
this.stopping = true;
}
@Override
public boolean canReplace() {
return this.stopping || this.phase == IAnimationProperty.Phase.LERPOUT || this.ended;
}
@Override
public boolean containsKeyframe(KeyframeType<?, ?> type, UUID boneUuid) {
Timeline timeline = this.blueprintAnimation.getTimelines().get(boneUuid);
return timeline == null ? false : timeline.hasInterpolator(type) && !timeline.getInterpolator(type).isEmpty();
}
@Override
public Vector3f getPositionFrame(ModelBone bone, BlueprintBone blueprintBone) {
return this.blueprintAnimation.getPosition(bone, blueprintBone, this);
}
@Override
public Vector3f getVelocityFrame(ModelBone bone, BlueprintBone blueprintBone) {
return this.blueprintAnimation.getVelocity(bone, blueprintBone, this);
}
@Override
public Vector3f getRotationFrame(ModelBone bone, BlueprintBone blueprintBone) {
return this.blueprintAnimation.getRotation(bone, blueprintBone, this);
}
@Override
public Vector3f getScaleFrame(ModelBone bone, BlueprintBone blueprintBone) {
return this.blueprintAnimation.getScale(bone, blueprintBone, this);
}
@Override
public List<ScriptKeyframe.Script> getScriptFrame() {
return this.blueprintAnimation.getScript(this);
}
@Override
public double getLerpInRatio() {
double ratio = TMath.clamp(this.lerpInTime / this.lerpIn, 0.0, 1.0);
return this.lerpCurveIn == Easing.LINEAR ? ratio : this.lerpCurveIn.apply(ratio);
}
@Override
public double getLerpOutRatio() {
double ratio = TMath.clamp(this.lerpOutTime / this.lerpOut, 0.0, 1.0);
return this.lerpCurveOut == Easing.LINEAR ? ratio : this.lerpCurveOut.apply(ratio);
}
@Override
public void setLerpCurveIn(@Nullable Easing lerpCurveIn) {
this.lerpCurveIn = lerpCurveIn == null ? Easing.LINEAR : lerpCurveIn;
}
@Override
public void setLerpCurveOut(@Nullable Easing lerpCurveOut) {
this.lerpCurveOut = lerpCurveOut == null ? Easing.LINEAR : lerpCurveOut;
}
@Override
public boolean isFinished() {
return this.phase == IAnimationProperty.Phase.LERPOUT || this.time >= this.blueprintAnimation.getLength();
}
@Override
public BlueprintAnimation.LoopMode getLoopMode() {
return this.forceLoopMode == null ? this.blueprintAnimation.getLoopMode() : this.forceLoopMode;
}
@Override
public boolean isOverride() {
return this.forceOverride == null && this.blueprintAnimation.isOverride() || this.forceOverride == BlueprintAnimation.OverrideMode.OVERRIDE;
}
@Override
public int hashCode() {
return Objects.hash(this.lerpIn, this.lerpOut, this.time, this.speed, this.phase, this.forceLoopMode, this.forceOverride);
}
@Override
public void save(SavedData data) {
data.putString("id", "simple");
data.putString("name", this.getName());
data.putDouble("lerp_in", this.lerpIn);
data.putDouble("lerp_out", this.lerpOut);
data.putDouble("lerp_in_time", this.lerpInTime);
data.putDouble("lerp_out_time", this.lerpOutTime);
data.putDouble("last_time", this.lastTime);
data.putDouble("time", this.time);
data.putDouble("speed", this.speed);
data.putString("phase", this.phase.name());
if (this.forceLoopMode != null) {
data.putString("force_loop_mode", this.forceLoopMode.name());
}
if (this.forceOverride != null) {
data.putString("force_override", this.forceOverride.name());
}
if (this.lerpCurveIn != Easing.LINEAR) {
data.putString("lerp_curve_in", this.lerpCurveIn.name());
}
if (this.lerpCurveOut != Easing.LINEAR) {
data.putString("lerp_curve_out", this.lerpCurveOut.name());
}
}
@Override
public void load(SavedData data) {
this.lerpInTime = data.getDouble("lerp_in_time");
this.lerpOutTime = data.getDouble("lerp_out_time");
this.lastTime = data.getDouble("last_time");
this.time = data.getDouble("time");
this.phase = IAnimationProperty.Phase.valueOf(data.getString("phase"));
data.loadIfExist("force_loop_mode", SavedData::getString, val -> this.forceLoopMode = BlueprintAnimation.LoopMode.getOrNull(val));
data.loadIfExist("force_override", SavedData::getString, val -> {
if (Boolean.parseBoolean(val)) {
this.forceOverride = BlueprintAnimation.OverrideMode.OVERRIDE;
}
this.forceOverride = BlueprintAnimation.OverrideMode.getOrNull(val);
});
data.loadIfExist("lerp_curve_in", SavedData::getString, val -> this.setLerpCurveIn(Easing.getOrNull(val)));
data.loadIfExist("lerp_curve_out", SavedData::getString, val -> this.setLerpCurveOut(Easing.getOrNull(val)));
}
public static SimpleProperty create(AnimationHandler handler, SavedData data) {
ActiveModel model = handler.getActiveModel();
ModelBlueprint blueprint = model.getBlueprint();
BlueprintAnimation animation = blueprint.getAnimationOrRef(data.getString("name"));
SimpleProperty property = new SimpleProperty(
model, animation, data.getDouble("lerp_in", 0.0), data.getDouble("lerp_out", 0.0), data.getDouble("speed", 1.0)
);
property.load(data);
return property;
}
@Override
public String toString() {
return "SimpleProperty(model="
+ this.getModel()
+ ", blueprintAnimation="
+ this.getBlueprintAnimation()
+ ", name="
+ this.getName()
+ ", lerpIn="
+ this.getLerpIn()
+ ", lerpOut="
+ this.getLerpOut()
+ ", lerpInTime="
+ this.getLerpInTime()
+ ", lerpOutTime="
+ this.getLerpOutTime()
+ ", lastTime="
+ this.getLastTime()
+ ", time="
+ this.getTime()
+ ", speed="
+ this.getSpeed()
+ ", phase="
+ this.getPhase()
+ ", forceLoopMode="
+ this.getForceLoopMode()
+ ", forceOverride="
+ this.getForceOverride()
+ ", lerpCurveIn="
+ this.getLerpCurveIn()
+ ", lerpCurveOut="
+ this.getLerpCurveOut()
+ ", emptyZero="
+ this.isEmptyZero()
+ ", skipLastFrame="
+ this.isSkipLastFrame()
+ ", mergeLerp="
+ this.isMergeLerp()
+ ", ignoreDeath="
+ this.isIgnoreDeath()
+ ", stopping="
+ this.isStopping()
+ ", ended="
+ this.isEnded()
+ ", onEndTask="
+ this.getOnEndTask()
+ ")";
}
@Override
public ActiveModel getModel() {
return this.model;
}
@Override
public BlueprintAnimation getBlueprintAnimation() {
return this.blueprintAnimation;
}
@Override
public String getName() {
return this.name;
}
@Override
public double getLerpIn() {
return this.lerpIn;
}
@Override
public double getLerpOut() {
return this.lerpOut;
}
@Override
public double getLerpInTime() {
return this.lerpInTime;
}
@Override
public double getLerpOutTime() {
return this.lerpOutTime;
}
@Override
public double getLastTime() {
return this.lastTime;
}
@Override
public double getTime() {
return this.time;
}
@Override
public double getSpeed() {
return this.speed;
}
@NotNull
@Override
public IAnimationProperty.Phase getPhase() {
return this.phase;
}
@Override
public BlueprintAnimation.LoopMode getForceLoopMode() {
return this.forceLoopMode;
}
@Override
public BlueprintAnimation.OverrideMode getForceOverride() {
return this.forceOverride;
}
@NotNull
@Override
public Easing getLerpCurveIn() {
return this.lerpCurveIn;
}
@NotNull
@Override
public Easing getLerpCurveOut() {
return this.lerpCurveOut;
}
@Override
public boolean isEmptyZero() {
return this.emptyZero;
}
@Override
public boolean isSkipLastFrame() {
return this.skipLastFrame;
}
@Override
public boolean isMergeLerp() {
return this.mergeLerp;
}
@Override
public boolean isIgnoreDeath() {
return this.ignoreDeath;
}
public boolean isStopping() {
return this.stopping;
}
@Override
public boolean isEnded() {
return this.ended;
}
@Override
public void setLerpIn(double lerpIn) {
this.lerpIn = lerpIn;
}
@Override
public void setLerpOut(double lerpOut) {
this.lerpOut = lerpOut;
}
@Override
public void setLerpInTime(double lerpInTime) {
this.lerpInTime = lerpInTime;
}
@Override
public void setLerpOutTime(double lerpOutTime) {
this.lerpOutTime = lerpOutTime;
}
@Override
public void setSpeed(double speed) {
this.speed = speed;
}
public void setPhase(@NotNull IAnimationProperty.Phase phase) {
if (phase == null) {
throw new NullPointerException("phase is marked non-null but is null");
} else {
this.phase = phase;
}
}
@Override
public void setForceLoopMode(BlueprintAnimation.LoopMode forceLoopMode) {
this.forceLoopMode = forceLoopMode;
}
@Override
public void setForceOverride(BlueprintAnimation.OverrideMode forceOverride) {
this.forceOverride = forceOverride;
}
@Override
public void setEmptyZero(boolean emptyZero) {
this.emptyZero = emptyZero;
}
@Override
public void setSkipLastFrame(boolean skipLastFrame) {
this.skipLastFrame = skipLastFrame;
}
@Override
public void setMergeLerp(boolean mergeLerp) {
this.mergeLerp = mergeLerp;
}
@Override
public void setIgnoreDeath(boolean ignoreDeath) {
this.ignoreDeath = ignoreDeath;
}
public Runnable getOnEndTask() {
return this.onEndTask;
}
public void setOnEndTask(Runnable onEndTask) {
this.onEndTask = onEndTask;
}
}
@@ -0,0 +1,319 @@
package com.ticxo.modelengine.api.animation.property;
import com.ticxo.modelengine.api.animation.BlueprintAnimation;
import com.ticxo.modelengine.api.animation.keyframe.KeyframeType;
import com.ticxo.modelengine.api.animation.keyframe.type.ScriptKeyframe;
import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone;
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.math.Easing;
import com.ticxo.modelengine.api.utils.math.TMath;
import java.util.List;
import java.util.UUID;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.joml.Vector3f;
public class SubTickProperty implements IAnimationProperty {
private final IAnimationProperty base;
private final double alpha;
private final double time;
private final double lastTime;
@Nullable
public static SubTickProperty at(@Nullable IAnimationProperty base, double alpha) {
return base == null ? null : new SubTickProperty(base, alpha);
}
public SubTickProperty(IAnimationProperty base, double alpha) {
this.base = base;
this.alpha = alpha;
double curr = base.getTime();
double prev = base.getLastTime();
double delta = base.getSpeed() * 0.05;
if (prev < 0.0 || curr < 0.0) {
this.time = Math.max(curr, 0.0);
} else if (curr >= prev) {
this.time = prev + alpha * (curr - prev);
} else if (delta > 0.0) {
double modulus = prev + delta - curr;
double shifted = prev + alpha * delta;
this.time = shifted >= modulus ? shifted - modulus : shifted;
} else {
this.time = prev + alpha * (curr - prev);
}
this.lastTime = Math.max(prev, 0.0);
}
public IAnimationProperty getBase() {
return this.base;
}
public double getAlpha() {
return this.alpha;
}
@Override
public double getTime() {
return this.time;
}
@Override
public double getLastTime() {
return this.lastTime;
}
@Override
public double getLerpInRatio() {
double lerpIn = this.base.getLerpIn();
if (lerpIn <= 0.0) {
return this.base.getLerpInRatio();
} else {
double ratio = TMath.clamp((this.base.getLerpInTime() - (1.0 - this.alpha) * this.base.getSpeed() * 0.05) / lerpIn, 0.0, 1.0);
Easing curve = this.base.getLerpCurveIn();
return curve == Easing.LINEAR ? ratio : curve.apply(ratio);
}
}
@Override
public double getLerpOutRatio() {
double lerpOut = this.base.getLerpOut();
if (lerpOut <= 0.0) {
return this.base.getLerpOutRatio();
} else {
double ratio = TMath.clamp((this.base.getLerpOutTime() - (1.0 - this.alpha) * this.base.getSpeed() * 0.05) / lerpOut, 0.0, 1.0);
Easing curve = this.base.getLerpCurveOut();
return curve == Easing.LINEAR ? ratio : curve.apply(ratio);
}
}
@Override
public Vector3f getPositionFrame(ModelBone bone, BlueprintBone blueprintBone) {
return this.base.getBlueprintAnimation().getPosition(bone, blueprintBone, this);
}
@Override
public Vector3f getVelocityFrame(ModelBone bone, BlueprintBone blueprintBone) {
return this.base.getBlueprintAnimation().getVelocity(bone, blueprintBone, this);
}
@Override
public Vector3f getRotationFrame(ModelBone bone, BlueprintBone blueprintBone) {
return this.base.getBlueprintAnimation().getRotation(bone, blueprintBone, this);
}
@Override
public Vector3f getScaleFrame(ModelBone bone, BlueprintBone blueprintBone) {
return this.base.getBlueprintAnimation().getScale(bone, blueprintBone, this);
}
@Override
public List<ScriptKeyframe.Script> getScriptFrame() {
return this.base.getBlueprintAnimation().getScript(this);
}
@Override
public BlueprintAnimation getBlueprintAnimation() {
return this.base.getBlueprintAnimation();
}
@Override
public boolean update() {
return this.base.update();
}
@Override
public void stop() {
this.base.stop();
}
@Override
public boolean isEnded() {
return this.base.isEnded();
}
@Override
public boolean canReplace() {
return this.base.canReplace();
}
@Override
public String getName() {
return this.base.getName();
}
@Override
public boolean containsKeyframe(KeyframeType<?, ?> type, UUID bone) {
return this.base.containsKeyframe(type, bone);
}
@Override
public boolean isFinished() {
return this.base.isFinished();
}
@Override
public ActiveModel getModel() {
return this.base.getModel();
}
@Override
public double getLerpIn() {
return this.base.getLerpIn();
}
@Override
public void setLerpIn(double lerpIn) {
this.base.setLerpIn(lerpIn);
}
@Override
public double getLerpOut() {
return this.base.getLerpOut();
}
@Override
public void setLerpOut(double lerpOut) {
this.base.setLerpOut(lerpOut);
}
@NotNull
@Override
public Easing getLerpCurveIn() {
return this.base.getLerpCurveIn();
}
@Override
public void setLerpCurveIn(@Nullable Easing lerpCurveIn) {
this.base.setLerpCurveIn(lerpCurveIn);
}
@NotNull
@Override
public Easing getLerpCurveOut() {
return this.base.getLerpCurveOut();
}
@Override
public void setLerpCurveOut(@Nullable Easing lerpCurveOut) {
this.base.setLerpCurveOut(lerpCurveOut);
}
@Override
public double getLerpInTime() {
return this.base.getLerpInTime();
}
@Override
public void setLerpInTime(double lerpInTime) {
this.base.setLerpInTime(lerpInTime);
}
@Override
public double getLerpOutTime() {
return this.base.getLerpOutTime();
}
@Override
public void setLerpOutTime(double lerpOutTime) {
this.base.setLerpOutTime(lerpOutTime);
}
@Override
public double getSpeed() {
return this.base.getSpeed();
}
@Override
public void setSpeed(double speed) {
this.base.setSpeed(speed);
}
@NotNull
@Override
public IAnimationProperty.Phase getPhase() {
return this.base.getPhase();
}
@Override
public BlueprintAnimation.LoopMode getForceLoopMode() {
return this.base.getForceLoopMode();
}
@Override
public void setForceLoopMode(BlueprintAnimation.LoopMode forceLoopMode) {
this.base.setForceLoopMode(forceLoopMode);
}
@Override
public BlueprintAnimation.LoopMode getLoopMode() {
return this.base.getLoopMode();
}
@Override
public boolean isOverride() {
return this.base.isOverride();
}
@Override
public BlueprintAnimation.OverrideMode getForceOverride() {
return this.base.getForceOverride();
}
@Override
public void setForceOverride(BlueprintAnimation.OverrideMode mode) {
this.base.setForceOverride(mode);
}
@Override
public boolean isEmptyZero() {
return this.base.isEmptyZero();
}
@Override
public void setEmptyZero(boolean flag) {
this.base.setEmptyZero(flag);
}
@Override
public boolean isSkipLastFrame() {
return this.base.isSkipLastFrame();
}
@Override
public void setSkipLastFrame(boolean skipLastFrame) {
this.base.setSkipLastFrame(skipLastFrame);
}
@Override
public boolean isMergeLerp() {
return this.base.isMergeLerp();
}
@Override
public void setMergeLerp(boolean mergeLerp) {
this.base.setMergeLerp(mergeLerp);
}
@Override
public boolean isIgnoreDeath() {
return this.base.isIgnoreDeath();
}
@Override
public void setIgnoreDeath(boolean ignoreDeath) {
this.base.setIgnoreDeath(ignoreDeath);
}
@Override
public void save(SavedData data) {
this.base.save(data);
}
@Override
public void load(SavedData data) {
this.base.load(data);
}
}
@@ -0,0 +1,10 @@
package com.ticxo.modelengine.api.animation.rootmotion;
import org.bukkit.util.Vector;
import org.joml.Vector3f;
public record RootMotion(Vector3f velocity, float yaw, boolean boneOnGround) {
public Vector delta() {
return Vector.fromJOML(this.velocity).rotateAroundY(-this.yaw * (float) (Math.PI / 180.0));
}
}
@@ -0,0 +1,6 @@
package com.ticxo.modelengine.api.animation.rootmotion;
import org.bukkit.util.Vector;
public record RootMotionDelta(Vector delta, boolean onGround) {
}
@@ -0,0 +1,86 @@
package com.ticxo.modelengine.api.animation.rootmotion;
import com.ticxo.modelengine.api.model.ModeledEntity;
import com.ticxo.modelengine.api.model.bone.ModelBone;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.bukkit.util.Vector;
public class RootMotionHandler {
private final ModeledEntity modeledEntity;
private final Queue<RootMotion> velocityQueue = new ConcurrentLinkedQueue<>();
private ModelBone rootBone;
private double baseWeight = 1.0;
private double weight = 0.0;
private boolean override;
private int queued;
public void queueVelocity(RootMotion rootMotion) {
this.queued = 2;
this.velocityQueue.add(rootMotion);
}
public boolean isQueued() {
return this.queued > 0;
}
public RootMotionDelta calculateRootMotion(Vector base) {
if (this.isQueued()) {
this.queued--;
}
if (!this.velocityQueue.isEmpty() && this.rootBone != null) {
double total = this.baseWeight + this.weight;
RootMotion vel = this.velocityQueue.poll();
base.multiply(this.override ? 0.0 : this.baseWeight / total);
Vector delta = vel.delta().multiply(this.override ? 1.0 : this.weight / total);
return new RootMotionDelta(delta, vel.boneOnGround());
} else {
return null;
}
}
public ModeledEntity getModeledEntity() {
return this.modeledEntity;
}
public Queue<RootMotion> getVelocityQueue() {
return this.velocityQueue;
}
public ModelBone getRootBone() {
return this.rootBone;
}
public double getBaseWeight() {
return this.baseWeight;
}
public double getWeight() {
return this.weight;
}
public boolean isOverride() {
return this.override;
}
public void setRootBone(ModelBone rootBone) {
this.rootBone = rootBone;
}
public void setBaseWeight(double baseWeight) {
this.baseWeight = baseWeight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public void setOverride(boolean override) {
this.override = override;
}
public RootMotionHandler(ModeledEntity modeledEntity) {
this.modeledEntity = modeledEntity;
}
}
@@ -0,0 +1,7 @@
package com.ticxo.modelengine.api.animation.script;
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
public interface ScriptReader {
void read(IAnimationProperty var1, String var2);
}
@@ -0,0 +1,6 @@
package com.ticxo.modelengine.api.animation.script;
import com.ticxo.modelengine.api.utils.registry.TUnaryRegistry;
public class ScriptReaderRegistry extends TUnaryRegistry<ScriptReader> {
}
@@ -0,0 +1,96 @@
package com.ticxo.modelengine.api.command;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.StringUtil;
import org.jetbrains.annotations.NotNull;
public abstract class AbstractCommand implements TabExecutor {
protected final JavaPlugin plugin;
private final Map<String, AbstractCommand> subCommands = new HashMap<>();
private final Map<String, AbstractCommand> subCommandAliases = new HashMap<>();
public AbstractCommand(AbstractCommand parent) {
this(parent.getPlugin());
}
public AbstractCommand(JavaPlugin plugin) {
this.plugin = plugin;
}
public final void addSubCommands(AbstractCommand... commands) {
for (AbstractCommand command : commands) {
this.subCommands.put(command.getName(), command);
for (String alias : command.getAliases()) {
this.subCommandAliases.put(alias, command);
}
}
}
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, String[] args) {
if (this.getPermissionNode() != null && !sender.hasPermission(this.getPermissionNode()) && !sender.hasPermission("modelengine.admin")) {
sender.sendMessage(Component.text("You don't have permission to do this!").color(NamedTextColor.RED));
return true;
} else if (!this.isConsoleFriendly() && !(sender instanceof Player)) {
sender.sendMessage(Component.text("Only players can do this!").color(NamedTextColor.RED));
return true;
} else if (args.length > 0 && this.subCommands.get(args[0].toLowerCase()) != null) {
AbstractCommand sub = this.subCommands.get(args[0].toLowerCase());
return sub.onCommand(sender, cmd, label, Arrays.copyOfRange(args, 1, args.length));
} else if (args.length > 0 && this.subCommandAliases.get(args[0].toLowerCase()) != null) {
AbstractCommand sub = this.subCommandAliases.get(args[0].toLowerCase());
return sub.onCommand(sender, cmd, label, Arrays.copyOfRange(args, 1, args.length));
} else {
return this.onCommand(sender, args);
}
}
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, String[] args) {
if (this.getPermissionNode() != null && !sender.hasPermission(this.getPermissionNode())) {
return null;
} else if (args.length > 1 && this.subCommands.get(args[0].toLowerCase()) != null) {
AbstractCommand sub = this.subCommands.get(args[0].toLowerCase());
return sub.onTabComplete(sender, cmd, label, Arrays.copyOfRange(args, 1, args.length));
} else if (args.length > 1 && this.subCommandAliases.get(args[0].toLowerCase()) != null) {
AbstractCommand sub = this.subCommandAliases.get(args[0].toLowerCase());
return sub.onTabComplete(sender, cmd, label, Arrays.copyOfRange(args, 1, args.length));
} else {
List<String> result = this.onTabComplete(sender, args);
if (result == null && args.length == 1) {
result = new ArrayList<>();
StringUtil.copyPartialMatches(args[0], this.subCommands.keySet(), result);
}
return result;
}
}
public abstract boolean onCommand(CommandSender var1, String[] var2);
public abstract List<String> onTabComplete(CommandSender var1, String[] var2);
public abstract String getPermissionNode();
public abstract boolean isConsoleFriendly();
public String[] getAliases() {
return new String[0];
}
public abstract String getName();
protected JavaPlugin getPlugin() {
return this.plugin;
}
}
@@ -0,0 +1,118 @@
package com.ticxo.modelengine.api.entity;
import com.ticxo.modelengine.api.entity.data.IEntityData;
import com.ticxo.modelengine.api.nms.entity.EntityHandler;
import com.ticxo.modelengine.api.nms.entity.HitboxEntity;
import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController;
import com.ticxo.modelengine.api.nms.entity.wrapper.LookController;
import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController;
import com.ticxo.modelengine.api.utils.data.io.DataIO;
import com.ticxo.modelengine.api.utils.data.io.SavedData;
import java.util.List;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.util.BoundingBox;
import org.jetbrains.annotations.Nullable;
public interface BaseEntity<T> extends DataIO {
T getOriginal();
IEntityData getData();
void registerData();
boolean isVisible();
void setVisible(boolean var1);
boolean isRemoved();
boolean isAlive();
boolean isForcedAlive();
void setForcedAlive(boolean var1);
int getEntityId();
UUID getUUID();
default Location getLocation() {
return this.getData().getLocation();
}
default List<Entity> getPassengers() {
return this.getData().getPassengers();
}
double getMaxStepHeight();
void setMaxStepHeight(double var1);
int getRenderRadius();
void setRenderRadius(int var1);
void setCollidableWith(Entity var1, boolean var2);
BodyRotationController getBodyRotationController();
MoveController getMoveController();
LookController getLookController();
boolean isGlowing();
int getGlowColor();
boolean isOnFire();
boolean hurt(@Nullable HumanEntity var1, Object var2, float var3);
boolean hurt(HitboxEntity var1, @Nullable HumanEntity var2, Object var3, float var4);
EntityHandler.InteractionResult interact(HumanEntity var1, EquipmentSlot var2);
EntityHandler.InteractionResult interact(HitboxEntity var1, HumanEntity var2, EquipmentSlot var3);
float getYRot();
float getYHeadRot();
float getXHeadRot();
float getYBodyRot();
boolean isWalking();
boolean isStrafing();
boolean isJumping();
boolean isFlying();
float getHealth();
float getMaxHealth();
BoundingBox getBoundingBox();
@Override
default void save(SavedData data) {
data.putInt("render_radius", this.getRenderRadius());
data.putDouble("step", this.getMaxStepHeight());
this.getData().save().ifPresent(entityData -> data.putData("entity_data", entityData));
this.getBodyRotationController().save().ifPresent(controllerData -> data.putData("body_rotation", controllerData));
}
@Override
default void load(SavedData data) {
this.setRenderRadius(data.getInt("render_radius"));
this.setMaxStepHeight(data.getDouble("step"));
data.getData("entity_data").ifPresent(entityData -> this.getData().load(entityData));
data.getData("body_rotation").ifPresent(controllerData -> this.getBodyRotationController().load(controllerData));
}
}
@@ -0,0 +1,363 @@
package com.ticxo.modelengine.api.entity;
import com.ticxo.modelengine.api.ModelEngineAPI;
import com.ticxo.modelengine.api.ServerInfo;
import com.ticxo.modelengine.api.entity.data.BukkitEntityData;
import com.ticxo.modelengine.api.nms.entity.EntityHandler;
import com.ticxo.modelengine.api.nms.entity.HitboxEntity;
import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController;
import com.ticxo.modelengine.api.nms.entity.wrapper.LookController;
import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController;
import com.ticxo.modelengine.api.nms.impl.DefaultBodyRotationController;
import com.ticxo.modelengine.api.nms.impl.EmptyLookController;
import com.ticxo.modelengine.api.nms.impl.EmptyMoveController;
import com.ticxo.modelengine.api.utils.data.io.SavedData;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.util.BoundingBox;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.Nullable;
public class BukkitEntity implements BaseEntity<Entity> {
protected final EntityHandler entityHandler;
protected final Entity original;
protected final BukkitEntityData data;
protected final BodyRotationController bodyRotationController;
protected final MoveController moveController;
protected final LookController lookController;
protected boolean isVisible = true;
protected int entityId;
public BukkitEntity(Entity original) {
this.entityHandler = ModelEngineAPI.getNMSHandler().getEntityHandler();
this.original = original;
this.entityId = this.entityHandler.getEntityId(original);
this.data = this.createEntityData(original);
this.bodyRotationController = this.entityHandler.wrapBodyRotationControl(original, () -> new DefaultBodyRotationController(this));
this.moveController = this.entityHandler.wrapMoveController(original, EmptyMoveController::new);
this.lookController = this.entityHandler.wrapLookController(original, EmptyLookController::new);
this.entityHandler.wrapNavigation(original);
}
protected BukkitEntityData createEntityData(Entity original) {
return new BukkitEntityData(original, this);
}
@Override
public void registerData() {
ModelEngineAPI.getAPI().getDataTrackers().execute(this.getUUID(), (uuid, tracker) -> tracker.putEntityData(uuid, this.data));
}
@Override
public void setVisible(boolean flag) {
if (this.isVisible != flag) {
this.isVisible = flag;
if (this.isVisible) {
for (UUID player : this.data.getTracking().keySet()) {
if (!player.equals(this.original.getUniqueId())) {
this.entityHandler.forceSpawn(this, Bukkit.getPlayer(player));
}
}
} else if (ModelEngineAPI.getPivotOverrideRegistry().get(this.original.getUniqueId()).isEmpty()) {
for (UUID playerx : this.data.getTracking().keySet()) {
if (!playerx.equals(this.original.getUniqueId())) {
this.entityHandler.forceDespawn(this, Bukkit.getPlayer(playerx));
}
}
}
}
}
public void onWorldChanged() {
int oldId = this.entityId;
int newId = this.entityHandler.getEntityId(this.original);
if (newId != oldId) {
this.entityId = newId;
ModelEngineAPI.getAPI().getModelUpdaters().rekeyEntityId(this.getUUID(), oldId, newId);
}
if (!this.isVisible && ModelEngineAPI.getPivotOverrideRegistry().get(this.original.getUniqueId()).isEmpty()) {
for (UUID player : this.data.getTracked().getTrackedPlayer()) {
if (!player.equals(this.original.getUniqueId())) {
this.entityHandler.forceDespawn(this, Bukkit.getPlayer(player));
}
}
}
}
@Override
public boolean isRemoved() {
return this.data.isRemoved();
}
@Override
public boolean isAlive() {
return this.data.isEntityValid();
}
@Override
public boolean isForcedAlive() {
return this.data.isForcedAlive();
}
@Override
public void setForcedAlive(boolean flag) {
this.data.setForcedAlive(flag);
}
@Override
public int getEntityId() {
return this.entityId;
}
@Override
public UUID getUUID() {
return this.original.getUniqueId();
}
@Override
public double getMaxStepHeight() {
return this.entityHandler.getStepHeight(this.original);
}
@Override
public void setMaxStepHeight(double stepHeight) {
this.entityHandler.setStepHeight(this.original, stepHeight);
}
@Override
public int getRenderRadius() {
return this.data.getTracked().getBaseRange();
}
@Override
public void setRenderRadius(int radius) {
this.data.getTracked().setBaseRange(radius);
}
@Override
public void setCollidableWith(Entity entity, boolean flag) {
if (this.original instanceof LivingEntity livingEntity) {
if (ServerInfo.IS_FOLIA) {
this.original.getScheduler().run(ModelEngineAPI.getAPI(), task -> {
if (this.original.isValid()) {
Set<UUID> set = livingEntity.getCollidableExemptions();
if (set != null) {
if (flag) {
set.remove(entity.getUniqueId());
} else {
set.add(entity.getUniqueId());
}
}
}
}, null);
} else {
Set<UUID> set = livingEntity.getCollidableExemptions();
if (set == null) {
return;
}
if (flag) {
set.remove(entity.getUniqueId());
} else {
set.add(entity.getUniqueId());
}
}
}
}
@Override
public boolean isGlowing() {
return ServerInfo.IS_FOLIA ? this.data.isBaseGlowing() : this.original.isGlowing();
}
@Override
public int getGlowColor() {
return this.data.getGlowColor();
}
@Override
public boolean isOnFire() {
return ServerInfo.IS_FOLIA ? this.data.isOnFire() : this.original.isVisualFire() || this.original.getFireTicks() > 0;
}
@Override
public boolean hurt(@Nullable HumanEntity player, Object nmsDamageCause, float damage) {
return this.entityHandler.hurt(this.original, nmsDamageCause, damage);
}
@Override
public boolean hurt(HitboxEntity hitbox, @Nullable HumanEntity player, Object nmsDamageCause, float damage) {
if (this.original.hasMetadata("skill-damage")) {
List<MetadataValue> metadataList = this.original.getMetadata("skill-damage");
MetadataValue metadata = metadataList.get(0);
this.original.setMetadata("skill-damage", metadata);
this.original.setMetadata("hitbox", new FixedMetadataValue(ModelEngineAPI.getAPI(), hitbox.getBone().getBoneId()));
boolean var7;
try {
var7 = this.entityHandler.hurt(this.original, nmsDamageCause, damage);
} finally {
this.original.removeMetadata("hitbox", ModelEngineAPI.getAPI());
this.original.removeMetadata("skill-damage", metadata.getOwningPlugin());
}
return var7;
} else {
this.original.setMetadata("hitbox", new FixedMetadataValue(ModelEngineAPI.getAPI(), hitbox.getBone().getBoneId()));
boolean metadataList;
try {
metadataList = this.entityHandler.hurt(this.original, nmsDamageCause, damage);
} finally {
this.original.removeMetadata("hitbox", ModelEngineAPI.getAPI());
}
return metadataList;
}
}
@Override
public EntityHandler.InteractionResult interact(HumanEntity player, EquipmentSlot slot) {
if (player instanceof Player serverPlayer) {
PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent(serverPlayer, this.original, new Vector(0, 0, 0), slot);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) {
return EntityHandler.InteractionResult.FAIL;
}
}
return this.entityHandler.interact(this.original, player, slot);
}
@Override
public EntityHandler.InteractionResult interact(HitboxEntity hitbox, HumanEntity player, EquipmentSlot slot) {
this.original.setMetadata("hitbox", new FixedMetadataValue(ModelEngineAPI.getAPI(), hitbox.getBone().getBoneId()));
EntityHandler.InteractionResult var4;
try {
var4 = this.interact(player, slot);
} finally {
this.original.removeMetadata("hitbox", ModelEngineAPI.getAPI());
}
return var4;
}
@Override
public float getYRot() {
return ServerInfo.IS_FOLIA ? this.data.getYRot() : this.entityHandler.getYRot(this.original);
}
@Override
public float getYHeadRot() {
return ServerInfo.IS_FOLIA ? this.data.getYHeadRot() : this.entityHandler.getYHeadRot(this.original);
}
@Override
public float getXHeadRot() {
return ServerInfo.IS_FOLIA ? this.data.getXHeadRot() : this.entityHandler.getXHeadRot(this.original);
}
@Override
public float getYBodyRot() {
return ServerInfo.IS_FOLIA ? this.data.getYBodyRot() : this.entityHandler.getYBodyRot(this.original);
}
@Override
public boolean isWalking() {
return ServerInfo.IS_FOLIA ? this.data.isWalking() : this.entityHandler.isWalking(this.original);
}
@Override
public boolean isStrafing() {
return ServerInfo.IS_FOLIA ? this.data.isStrafing() : this.entityHandler.isStrafing(this.original);
}
@Override
public boolean isJumping() {
return ServerInfo.IS_FOLIA ? this.data.isJumping() : this.entityHandler.isJumping(this.original);
}
@Override
public boolean isFlying() {
return ServerInfo.IS_FOLIA ? this.data.isFlying() : this.entityHandler.isFlying(this.original);
}
@Override
public float getHealth() {
return ServerInfo.IS_FOLIA ? this.data.getHealth() : this.entityHandler.getHealth(this.original);
}
@Override
public float getMaxHealth() {
return ServerInfo.IS_FOLIA ? this.data.getMaxHealth() : this.entityHandler.getMaxHealth(this.original);
}
@Override
public BoundingBox getBoundingBox() {
return ServerInfo.IS_FOLIA ? this.data.getBoundingBox() : this.original.getBoundingBox().clone();
}
@Override
public void save(SavedData data) {
data.putInt("render_radius", this.getRenderRadius());
double step = this.data.getStepHeight();
data.putDouble("step", Double.isNaN(step) ? this.getMaxStepHeight() : step);
this.getData().save().ifPresent(entityData -> data.putData("entity_data", entityData));
this.getBodyRotationController().save().ifPresent(controllerData -> data.putData("body_rotation", controllerData));
Set<UUID> exemptions = this.data.getCollidableExemptions();
if (exemptions != null) {
data.putList("collide_exemption", exemptions);
}
}
@Override
public void load(SavedData data) {
BaseEntity.super.load(data);
Set<UUID> exemptions = this.entityHandler.getCollidableExemptions(this.original);
if (exemptions != null) {
exemptions.addAll(data.getList("collide_exemption"));
}
this.data.refreshSaveSnapshots();
}
public Entity getOriginal() {
return this.original;
}
public BukkitEntityData getData() {
return this.data;
}
@Override
public BodyRotationController getBodyRotationController() {
return this.bodyRotationController;
}
@Override
public MoveController getMoveController() {
return this.moveController;
}
@Override
public LookController getLookController() {
return this.lookController;
}
@Override
public boolean isVisible() {
return this.isVisible;
}
}
@@ -0,0 +1,71 @@
package com.ticxo.modelengine.api.entity;
import com.ticxo.modelengine.api.entity.data.BukkitEntityData;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
public class BukkitPlayer extends BukkitEntity {
public BukkitPlayer(Player original) {
super(original);
}
@Override
protected BukkitEntityData createEntityData(Entity original) {
return new BukkitPlayer.BukkitPlayerData(original, this);
}
@Override
public boolean isWalking() {
return ((BukkitPlayer.BukkitPlayerData)this.getData()).getWalkTick() > 0;
}
@Override
public boolean isJumping() {
return ((BukkitPlayer.BukkitPlayerData)this.getData()).getJumpTick() > 0;
}
@Override
public boolean isFlying() {
return ((BukkitPlayer.BukkitPlayerData)this.getData()).isFlying;
}
public static class BukkitPlayerData extends BukkitEntityData {
private int walkTick;
private int jumpTick;
private boolean isFlying;
public BukkitPlayerData(Entity entity, BukkitPlayer player) {
super(entity, player);
}
@Override
protected void safeSyncUpdate() {
super.safeSyncUpdate();
if (this.walkTick > 0) {
this.walkTick--;
}
if (this.jumpTick > 0 && this.entity.isOnGround()) {
this.jumpTick--;
}
this.isFlying = ((Player)this.entity).isFlying();
}
public int getWalkTick() {
return this.walkTick;
}
public void setWalkTick(int walkTick) {
this.walkTick = walkTick;
}
public int getJumpTick() {
return this.jumpTick;
}
public void setJumpTick(int jumpTick) {
this.jumpTick = jumpTick;
}
}
}
@@ -0,0 +1,17 @@
package com.ticxo.modelengine.api.entity;
import java.util.Locale;
public enum CullType {
NO_CULL,
MOVEMENT_ONLY,
CULLED;
public static CullType get(String value) {
try {
return valueOf(value.toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException var2) {
return NO_CULL;
}
}
}
@@ -0,0 +1,339 @@
package com.ticxo.modelengine.api.entity;
import com.ticxo.modelengine.api.ModelEngineAPI;
import com.ticxo.modelengine.api.entity.data.DummyEntityData;
import com.ticxo.modelengine.api.nms.entity.EntityHandler;
import com.ticxo.modelengine.api.nms.entity.HitboxEntity;
import com.ticxo.modelengine.api.nms.entity.wrapper.LookController;
import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController;
import com.ticxo.modelengine.api.nms.impl.DefaultBodyRotationController;
import com.ticxo.modelengine.api.nms.impl.EmptyLookController;
import com.ticxo.modelengine.api.nms.impl.EmptyMoveController;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.util.BoundingBox;
import org.jetbrains.annotations.Nullable;
public class Dummy<T> implements BaseEntity<T> {
protected final int entityId;
protected final UUID uuid;
protected final T original;
protected final DummyEntityData<T> data;
protected final DefaultBodyRotationController bodyRotationController;
protected final MoveController moveController;
protected final LookController lookController;
protected boolean detectingPlayers = true;
protected boolean isRemoved;
protected boolean isWalking;
protected boolean isStrafing;
protected boolean isJumping;
protected boolean isFlying;
protected boolean isGlowing;
protected int glowColor;
protected boolean isOnFire;
protected float yHeadRot;
protected float xHeadRot;
protected float yBodyRot;
protected Hitbox hitbox = new Hitbox(0.0, 0.0, 0.0, 0.0);
protected BoundingBox boundingBox = new BoundingBox();
public Dummy() {
this(null);
}
public Dummy(T original) {
this(UUID.randomUUID(), original);
}
public Dummy(UUID uuid, T original) {
this(ModelEngineAPI.getEntityHandler().getNextEntityId(), uuid, original);
}
public Dummy(int id, UUID uuid, T original) {
this.entityId = id;
this.uuid = uuid;
this.original = original;
this.data = new DummyEntityData<>(this);
this.bodyRotationController = new DefaultBodyRotationController(this);
this.moveController = new EmptyMoveController();
this.lookController = new EmptyLookController();
}
@Override
public boolean isAlive() {
return !this.isRemoved;
}
@Override
public UUID getUUID() {
return this.uuid;
}
@Override
public int getRenderRadius() {
return this.data.getRenderRadius();
}
@Override
public void setRenderRadius(int radius) {
this.data.setRenderRadius(radius);
}
@Override
public float getYRot() {
return this.yHeadRot;
}
@Override
public float getHealth() {
return 20.0F;
}
@Override
public float getMaxHealth() {
return 20.0F;
}
public void setLocation(Location location) {
this.data.setLocation(location);
this.boundingBox = this.hitbox.createBoundingBox(location.toVector());
}
public void syncLocation(Location location) {
this.setLocation(location);
this.setYBodyRot(location.getYaw());
this.setYHeadRot(location.getYaw());
this.setXHeadRot(location.getPitch());
this.bodyRotationController.syncFromBase();
}
public void setForceViewing(Player player, boolean flag) {
if (flag) {
this.setForceHidden(player, false);
this.data.getTracked().addForcedPairing(player.getUniqueId());
} else {
this.data.getTracked().removeForcedPairing(player.getUniqueId());
}
}
public void setForceHidden(Player player, boolean flag) {
if (flag) {
this.setForceViewing(player, false);
this.data.getTracked().addForcedHidden(player.getUniqueId());
} else {
this.data.getTracked().removeForcedHidden(player.getUniqueId());
}
}
@Override
public void registerData() {
ModelEngineAPI.getAPI().getDataTrackers().execute(this.getUUID(), (uuid, tracker) -> tracker.putEntityData(uuid, this.data));
}
@Override
public boolean isVisible() {
return true;
}
@Override
public void setVisible(boolean flag) {
}
@Override
public boolean isForcedAlive() {
return false;
}
@Override
public void setForcedAlive(boolean flag) {
}
@Override
public double getMaxStepHeight() {
return 0.0;
}
@Override
public void setMaxStepHeight(double stepHeight) {
}
@Override
public void setCollidableWith(Entity entity, boolean flag) {
}
@Override
public boolean hurt(@Nullable HumanEntity player, Object nmsDamageCause, float damage) {
return false;
}
@Override
public boolean hurt(HitboxEntity hitbox, @Nullable HumanEntity player, Object nmsDamageCause, float damage) {
return false;
}
@Override
public EntityHandler.InteractionResult interact(HumanEntity player, EquipmentSlot slot) {
return EntityHandler.InteractionResult.SUCCESS_NO_ITEM_USED;
}
@Override
public EntityHandler.InteractionResult interact(HitboxEntity hitbox, HumanEntity player, EquipmentSlot slot) {
return EntityHandler.InteractionResult.SUCCESS_NO_ITEM_USED;
}
@Override
public int getEntityId() {
return this.entityId;
}
@Override
public T getOriginal() {
return this.original;
}
public DummyEntityData<T> getData() {
return this.data;
}
public DefaultBodyRotationController getBodyRotationController() {
return this.bodyRotationController;
}
@Override
public MoveController getMoveController() {
return this.moveController;
}
@Override
public LookController getLookController() {
return this.lookController;
}
public boolean isDetectingPlayers() {
return this.detectingPlayers;
}
@Override
public boolean isRemoved() {
return this.isRemoved;
}
@Override
public boolean isWalking() {
return this.isWalking;
}
@Override
public boolean isStrafing() {
return this.isStrafing;
}
@Override
public boolean isJumping() {
return this.isJumping;
}
@Override
public boolean isFlying() {
return this.isFlying;
}
@Override
public boolean isGlowing() {
return this.isGlowing;
}
@Override
public int getGlowColor() {
return this.glowColor;
}
@Override
public boolean isOnFire() {
return this.isOnFire;
}
@Override
public float getYHeadRot() {
return this.yHeadRot;
}
@Override
public float getXHeadRot() {
return this.xHeadRot;
}
@Override
public float getYBodyRot() {
return this.yBodyRot;
}
public Hitbox getHitbox() {
return this.hitbox;
}
@Override
public BoundingBox getBoundingBox() {
return this.boundingBox;
}
public void setDetectingPlayers(boolean detectingPlayers) {
this.detectingPlayers = detectingPlayers;
}
public void setRemoved(boolean isRemoved) {
this.isRemoved = isRemoved;
}
public void setWalking(boolean isWalking) {
this.isWalking = isWalking;
}
public void setStrafing(boolean isStrafing) {
this.isStrafing = isStrafing;
}
public void setJumping(boolean isJumping) {
this.isJumping = isJumping;
}
public void setFlying(boolean isFlying) {
this.isFlying = isFlying;
}
public void setGlowing(boolean isGlowing) {
this.isGlowing = isGlowing;
}
public void setGlowColor(int glowColor) {
this.glowColor = glowColor;
}
public void setOnFire(boolean isOnFire) {
this.isOnFire = isOnFire;
}
public void setYHeadRot(float yHeadRot) {
this.yHeadRot = yHeadRot;
}
public void setXHeadRot(float xHeadRot) {
this.xHeadRot = xHeadRot;
}
public void setYBodyRot(float yBodyRot) {
this.yBodyRot = yBodyRot;
}
public void setHitbox(Hitbox hitbox) {
this.hitbox = hitbox;
}
public void setBoundingBox(BoundingBox boundingBox) {
this.boundingBox = boundingBox;
}
}
@@ -0,0 +1,24 @@
package com.ticxo.modelengine.api.entity;
import com.ticxo.modelengine.api.utils.math.Box;
import org.bukkit.util.BoundingBox;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull;
public class DynamicBox implements Box {
private final BoundingBox box = new BoundingBox();
public void reset() {
this.box.resize(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
}
public void expand(@NotNull BoundingBox other) {
this.box.union(other);
}
@NotNull
@Override
public BoundingBox createBoundingBox(Vector vector) {
return this.box.clone().shift(vector);
}
}
@@ -0,0 +1,177 @@
package com.ticxo.modelengine.api.entity;
import com.google.common.collect.Maps;
import com.ticxo.modelengine.api.ModelEngineAPI;
import com.ticxo.modelengine.api.entity.data.IEntityData;
import com.ticxo.modelengine.api.utils.config.ConfigProperty;
import com.ticxo.modelengine.api.utils.logger.TLogger;
import com.ticxo.modelengine.api.utils.scheduling.PlatformScheduler;
import com.ticxo.modelengine.api.utils.ticker.AbstractLoadBalancer;
import com.ticxo.modelengine.api.utils.ticker.DualTicker;
import com.ticxo.modelengine.api.utils.ticker.LoadBalancer;
import com.ticxo.modelengine.api.utils.ticker.PseudoThread;
import com.ticxo.modelengine.api.utils.ticker.Task;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.plugin.java.JavaPlugin;
public class EntityDataTrackers extends AbstractLoadBalancer<UUID, EntityDataTrackers.Tracker> {
private final Map<EntityDataTrackers.Tracker, PseudoThread> threads = new ConcurrentHashMap<>();
private final JavaPlugin plugin;
private final PlatformScheduler scheduler;
private final int maximumThreads;
private int trackerCount = 0;
private volatile boolean started;
public EntityDataTrackers(JavaPlugin plugin, PlatformScheduler scheduler) {
super(ConfigProperty.CULLING_THREADS.getInt());
this.plugin = plugin;
this.scheduler = scheduler;
this.maximumThreads = Math.max(ConfigProperty.MAX_CULLING_THREADS.getInt(), this.available.size());
this.available.forEach(this::setup);
}
public EntityDataTrackers.Tracker supply() {
return new EntityDataTrackers.Tracker();
}
public void start() {
this.started = true;
for (Entry<EntityDataTrackers.Tracker, PseudoThread> entry : this.threads.entrySet()) {
entry.getValue().start();
}
}
public void end() {
for (Entry<EntityDataTrackers.Tracker, PseudoThread> entry : this.threads.entrySet()) {
entry.getValue().end();
}
}
private void setup(EntityDataTrackers.Tracker tracker) {
tracker.setId("data_tracker_" + this.trackerCount);
PseudoThread thread = new PseudoThread(tracker.getId(), this.scheduler, this.plugin, true, 0, 0, true, false);
thread.registerOverloadCallback(skipped -> {
TLogger.debug(tracker.getId() + " is overloaded with " + tracker.getLoad() + " targets.");
if (this.available.size() < this.maximumThreads) {
this.growAndBalance(tracker, skipped);
}
});
thread.queueTask(new Task(task -> tracker.asyncFetchEntityData(), 0, 0, true));
DualTicker.queueRepeatingSyncTask(tracker::fetchEntityData, 0, 0);
this.threads.put(tracker, thread);
if (this.started) {
thread.start();
}
this.trackerCount++;
}
private void growAndBalance(EntityDataTrackers.Tracker request, int skipped) {
TLogger.debug(request.id + " has skipped " + skipped + " ticks. Requested a new server.");
EntityDataTrackers.Tracker handle = this.supply();
int moved = request.dataTrackers.size() / 2;
for (Entry<UUID, IEntityData> entry : request.dataTrackers.entrySet()) {
if (moved <= 0) {
break;
}
handle.putEntityData(entry.getKey(), entry.getValue());
this.reference.put(entry.getKey(), handle);
moved--;
}
handle.dataTrackers.keySet().forEach(uuid -> {
request.dataTrackers.remove(uuid);
request.unverified.remove(uuid);
});
this.available.add(handle);
this.setup(handle);
TLogger.debug("- Created " + handle.id + ".");
}
public class Tracker implements LoadBalancer.Server {
private final Map<UUID, IEntityData> dataTrackers = Maps.newConcurrentMap();
private String id = "Unknown";
private volatile int lastSize = 0;
private long timings;
private long verifiedEpoch = -1L;
private final Set<UUID> unverified = ConcurrentHashMap.newKeySet();
public void fetchEntityData() {
long epoch = ModelEngineAPI.getAPI().getModelUpdaters().getRemovalEpoch() + ModelEngineAPI.getAPI().getVFXUpdater().getRemovalEpoch();
boolean recheckAll = epoch != this.verifiedEpoch;
boolean hasUnverified = !this.unverified.isEmpty();
for (Entry<UUID, IEntityData> entry : this.dataTrackers.entrySet()) {
IEntityData data = entry.getValue();
boolean checkRegistry = (hasUnverified && this.unverified.remove(entry.getKey())) | recheckAll;
if (data.isDataValid() && (!checkRegistry || ModelEngineAPI.isModeledEntity(entry.getKey()) || ModelEngineAPI.isVFX(entry.getKey()))) {
data.syncUpdate();
} else {
data.destroy();
this.dataTrackers.remove(entry.getKey());
this.unverified.remove(entry.getKey());
EntityDataTrackers.this.unregister(entry.getKey());
}
}
this.verifiedEpoch = epoch;
}
public void asyncFetchEntityData() {
long time = System.currentTimeMillis();
for (IEntityData data : this.dataTrackers.values()) {
data.cullUpdate();
}
this.timings = System.currentTimeMillis() - time;
if (this.lastSize != this.dataTrackers.size()) {
this.lastSize = this.dataTrackers.size();
TLogger.debug(this.id + ": " + this.lastSize + " - " + this.timings);
}
}
public void putEntityData(UUID uuid, IEntityData dataTracker) {
this.unverified.add(uuid);
this.dataTrackers.put(uuid, dataTracker);
}
public IEntityData getEntityData(UUID uuid) {
return this.dataTrackers.get(uuid);
}
public IEntityData removeEntityData(UUID uuid) {
this.unverified.remove(uuid);
EntityDataTrackers.this.unregister(uuid);
return this.dataTrackers.remove(uuid);
}
@Override
public int getLoad() {
return this.lastSize;
}
public Map<UUID, IEntityData> getDataTrackers() {
return this.dataTrackers;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public long getTimings() {
return this.timings;
}
}
}
@@ -0,0 +1,106 @@
package com.ticxo.modelengine.api.entity;
import com.ticxo.modelengine.api.utils.MiscUtils;
import com.ticxo.modelengine.api.utils.math.Box;
import org.bukkit.util.BoundingBox;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull;
public class Hitbox implements Box {
private final double width;
private final double height;
private final double depth;
private final double eyeHeight;
public Hitbox clone() {
return new Hitbox(this.width, this.height, this.depth, this.eyeHeight);
}
public double getMaxWidth() {
return Math.max(this.width, this.depth);
}
@NotNull
@Override
public BoundingBox createBoundingBox(Vector vector) {
return new BoundingBox(
vector.getX() - this.width * 0.5,
vector.getY(),
vector.getZ() - this.depth * 0.5,
vector.getX() + this.width * 0.5,
vector.getY() + this.height,
vector.getZ() + this.depth * 0.5
);
}
public String toSimpleString() {
return MiscUtils.FORMATTER.format(this.width) + " x " + MiscUtils.FORMATTER.format(this.height) + " x " + MiscUtils.FORMATTER.format(this.width);
}
public String toEyeHeightString() {
return MiscUtils.FORMATTER.format(this.eyeHeight);
}
public Hitbox(double width, double height, double depth, double eyeHeight) {
this.width = width;
this.height = height;
this.depth = depth;
this.eyeHeight = eyeHeight;
}
public double getWidth() {
return this.width;
}
public double getHeight() {
return this.height;
}
public double getDepth() {
return this.depth;
}
public double getEyeHeight() {
return this.eyeHeight;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof Hitbox other)) {
return false;
} else if (!other.canEqual(this)) {
return false;
} else if (Double.compare(this.getWidth(), other.getWidth()) != 0) {
return false;
} else if (Double.compare(this.getHeight(), other.getHeight()) != 0) {
return false;
} else {
return Double.compare(this.getDepth(), other.getDepth()) != 0 ? false : Double.compare(this.getEyeHeight(), other.getEyeHeight()) == 0;
}
}
protected boolean canEqual(Object other) {
return other instanceof Hitbox;
}
@Override
public int hashCode() {
int PRIME = 59;
int result = 1;
long $width = Double.doubleToLongBits(this.getWidth());
result = result * 59 + (int)($width >>> 32 ^ $width);
long $height = Double.doubleToLongBits(this.getHeight());
result = result * 59 + (int)($height >>> 32 ^ $height);
long $depth = Double.doubleToLongBits(this.getDepth());
result = result * 59 + (int)($depth >>> 32 ^ $depth);
long $eyeHeight = Double.doubleToLongBits(this.getEyeHeight());
return result * 59 + (int)($eyeHeight >>> 32 ^ $eyeHeight);
}
@Override
public String toString() {
return "Hitbox(width=" + this.getWidth() + ", height=" + this.getHeight() + ", depth=" + this.getDepth() + ", eyeHeight=" + this.getEyeHeight() + ")";
}
}
@@ -0,0 +1,141 @@
package com.ticxo.modelengine.api.entity.cull;
import com.ticxo.modelengine.api.ModelEngineAPI;
import com.ticxo.modelengine.api.entity.CullType;
import com.ticxo.modelengine.api.entity.data.IEntityData;
import com.ticxo.modelengine.api.model.ActiveModel;
import com.ticxo.modelengine.api.mount.MountPairManager;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.util.BoundingBox;
import org.bukkit.util.Vector;
public class BasicCulling implements ModelCuller {
private static final Set<UUID> GLOBAL_EXEMPT = ConcurrentHashMap.newKeySet();
protected IEntityData data;
protected int lastCulled;
protected int culledCount;
public static void setGlobalCullExempt(UUID uuid, boolean exempt) {
if (exempt) {
GLOBAL_EXEMPT.add(uuid);
} else {
GLOBAL_EXEMPT.remove(uuid);
}
}
public static boolean isGlobalCullExempt(UUID uuid) {
return !GLOBAL_EXEMPT.isEmpty() && GLOBAL_EXEMPT.contains(uuid);
}
@Override
public void updateCulledPlayer() {
if (this.data != null && --this.lastCulled <= 0) {
this.lastCulled = this.data.cullInterval();
MountPairManager pairManager = ModelEngineAPI.getMountPairManager();
Location location = this.data.getLocation();
BoundingBox box = this.data.getCullHitbox() == null
? this.data.getBaseEntity().getBoundingBox()
: this.data.getCullHitbox().createBoundingBox(location.toVector());
for (UUID uuid : this.data.getMutableTracking().keySet()) {
Player player = Bukkit.getPlayer(uuid);
if (player != null) {
if (!isGlobalCullExempt(uuid) && !this.data.isCullExempt(uuid)) {
ActiveModel mounted = pairManager.getMountedPair(player.getUniqueId());
if (mounted != null && mounted.getModeledEntity().getBase().getData() == this.data) {
this.put(player.getUniqueId(), CullType.NO_CULL);
} else if (location.getWorld() != player.getWorld()) {
this.put(player.getUniqueId(), CullType.CULLED);
} else {
Location eyeLoc = ((IEntityData.CullCameraOverride)PLAYER_CALLBACK.invoker()).calculate(this.data, player, player.getEyeLocation());
if (this.data.verticalCull()) {
double distance = Math.max(eyeLoc.getY() - box.getMaxY(), box.getMinY() - eyeLoc.getY());
if (distance > this.data.verticalCullDistance()) {
this.put(player.getUniqueId(), this.data.verticalCullType());
continue;
}
}
double deltaX = location.getX() - eyeLoc.getX();
double deltaY = location.getY() - eyeLoc.getY();
double deltaZ = location.getZ() - eyeLoc.getZ();
double deltaLengthSquared = deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;
if (this.data.blockedCull()
&& !this.data.isBaseGlowing()
&& !this.data.isModelGlowing()
&& deltaLengthSquared > this.data.blockedCullIgnoreRadius()
&& ModelEngineAPI.getEntityHandler().shouldCull(player, eyeLoc, box)) {
this.put(player.getUniqueId(), this.data.blockedCullType());
} else {
if (this.data.backCull()) {
if (box.contains(eyeLoc.getX(), eyeLoc.getY(), eyeLoc.getZ())) {
this.put(player.getUniqueId(), CullType.NO_CULL);
continue;
}
double deltaLength = Math.sqrt(deltaLengthSquared);
Vector direction = eyeLoc.getDirection();
double dot = direction.getX() * (deltaX / deltaLength)
+ direction.getY() * (deltaY / deltaLength)
+ direction.getZ() * (deltaZ / deltaLength);
if (deltaLengthSquared > this.data.backCullIgnoreRadius() && dot <= this.data.backCullAngle()) {
this.put(player.getUniqueId(), this.data.backCullType());
continue;
}
}
this.put(player.getUniqueId(), CullType.NO_CULL);
}
}
} else {
this.put(uuid, CullType.NO_CULL);
}
}
}
}
}
@Override
public CullType put(UUID uuid, CullType type) {
CullType last = this.data.getMutableTracking().put(uuid, type);
if (last == CullType.CULLED) {
this.culledCount--;
}
if (type == CullType.CULLED) {
this.culledCount++;
}
return last;
}
@Override
public CullType remove(UUID uuid) {
CullType removed = this.data.getMutableTracking().remove(uuid);
if (removed == CullType.CULLED) {
this.culledCount--;
}
return removed;
}
@Override
public IEntityData getData() {
return this.data;
}
@Override
public void setData(IEntityData data) {
this.data = data;
}
@Override
public int getCulledCount() {
return this.culledCount;
}
}
@@ -0,0 +1,31 @@
package com.ticxo.modelengine.api.entity.cull;
import com.ticxo.modelengine.api.entity.CullType;
import com.ticxo.modelengine.api.entity.data.IEntityData;
import com.ticxo.modelengine.api.utils.callback.Callback;
import java.util.UUID;
import org.bukkit.Location;
public interface ModelCuller {
Callback<IEntityData.CullCameraOverride> PLAYER_CALLBACK = new Callback<>(cullCameraOverrides -> (data, player, lastLocation) -> {
Location location = lastLocation;
for (IEntityData.CullCameraOverride override : cullCameraOverrides) {
location = override.calculate(data, player, location);
}
return location;
});
void setData(IEntityData var1);
IEntityData getData();
void updateCulledPlayer();
CullType put(UUID var1, CullType var2);
CullType remove(UUID var1);
int getCulledCount();
}
@@ -0,0 +1,274 @@
package com.ticxo.modelengine.api.entity.data;
import com.ticxo.modelengine.api.entity.CullType;
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.math.Box;
import com.ticxo.modelengine.api.utils.math.TMath;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public abstract class AbstractEntityData implements IEntityData {
private static int CULL_INTERVAL;
private static boolean CULL_VERTICAL;
private static double CULL_VERTICAL_DISTANCE;
private static CullType CULL_VERTICAL_TYPE;
private static boolean CULL_BEHIND;
private static double VIEW_ANGLE;
private static double UPDATE_BEHIND_RADIUS_SQR;
private static CullType CULL_BEHIND_TYPE;
private static boolean CULL_BLOCKED;
private static double FORCE_UNBLOCKED_RADIUS_SQR;
private static CullType CULL_BLOCKED_TYPE;
private final Set<ActiveModel> glowingModel = new HashSet<>();
private final Set<ModelBone> glowingBone = new HashSet<>();
private final Set<UUID> cullExempt = ConcurrentHashMap.newKeySet();
private Box cullHitbox;
private Integer cullInterval;
private Boolean verticalCull;
private Double verticalCullDistance;
private CullType verticalCullType;
private Boolean backCull;
private Double backCullAngle;
private Double backCullIgnoreRadius;
private CullType backCullType;
private Boolean blockedCull;
private Double blockedCullIgnoreRadius;
private CullType blockedCullType;
public static void updateConfig() {
CULL_INTERVAL = Math.max(ConfigProperty.CULL_INTERVAL.getInt(), 1);
CULL_VERTICAL = ConfigProperty.VERTICAL_CULL_ENABLE.getBoolean();
CULL_VERTICAL_DISTANCE = ConfigProperty.VERTICAL_CULL_DISTANCE.getDouble();
CULL_VERTICAL_TYPE = ConfigProperty.VERTICAL_CULL_TYPE.getCullType();
CULL_BEHIND = ConfigProperty.BACKWARDS_CULL_ENABLED.getBoolean();
VIEW_ANGLE = Math.cos(TMath.clamp(ConfigProperty.BACKWARDS_CULL_ANGLE.getDouble(), 0.0, 360.0) * 0.5 * (float) (Math.PI / 180.0));
UPDATE_BEHIND_RADIUS_SQR = ConfigProperty.BACKWARDS_CULL_IGNORE_RADIUS.getDouble();
UPDATE_BEHIND_RADIUS_SQR = UPDATE_BEHIND_RADIUS_SQR * UPDATE_BEHIND_RADIUS_SQR;
CULL_BEHIND_TYPE = ConfigProperty.BACKWARDS_CULL_TYPE.getCullType();
CULL_BLOCKED = ConfigProperty.BLOCK_CULL_ENABLE.getBoolean();
FORCE_UNBLOCKED_RADIUS_SQR = ConfigProperty.BLOCK_CULL_IGNORE_RADIUS.getDouble();
FORCE_UNBLOCKED_RADIUS_SQR = FORCE_UNBLOCKED_RADIUS_SQR * FORCE_UNBLOCKED_RADIUS_SQR;
CULL_BLOCKED_TYPE = ConfigProperty.BLOCK_CULL_TYPE.getCullType();
}
@Override
public int cullInterval() {
return this.cullInterval == null ? CULL_INTERVAL : this.cullInterval;
}
@Override
public boolean verticalCull() {
return this.verticalCull == null ? CULL_VERTICAL : this.verticalCull;
}
@Override
public double verticalCullDistance() {
return this.verticalCullDistance == null ? CULL_VERTICAL_DISTANCE : this.verticalCullDistance;
}
@Override
public CullType verticalCullType() {
return this.verticalCullType == null ? CULL_VERTICAL_TYPE : this.verticalCullType;
}
@Override
public boolean backCull() {
return this.backCull == null ? CULL_BEHIND : this.backCull;
}
@Override
public double backCullAngle() {
return this.backCullAngle == null ? VIEW_ANGLE : this.backCullAngle;
}
@Override
public double backCullIgnoreRadius() {
return this.backCullIgnoreRadius == null ? UPDATE_BEHIND_RADIUS_SQR : this.backCullIgnoreRadius * this.backCullIgnoreRadius;
}
@Override
public CullType backCullType() {
return this.backCullType == null ? CULL_BEHIND_TYPE : this.backCullType;
}
@Override
public boolean blockedCull() {
return this.blockedCull == null ? CULL_BLOCKED : this.blockedCull;
}
@Override
public double blockedCullIgnoreRadius() {
return this.blockedCullIgnoreRadius == null ? FORCE_UNBLOCKED_RADIUS_SQR : this.blockedCullIgnoreRadius * this.blockedCullIgnoreRadius;
}
@Override
public CullType blockedCullType() {
return this.blockedCullType == null ? CULL_BLOCKED_TYPE : this.blockedCullType;
}
@Override
public void setCullExempt(UUID uuid, boolean exempt) {
if (exempt) {
this.cullExempt.add(uuid);
} else {
this.cullExempt.remove(uuid);
}
}
@Override
public boolean isCullExempt(UUID uuid) {
return !this.cullExempt.isEmpty() && this.cullExempt.contains(uuid);
}
@Override
public Set<UUID> getCullExempt() {
return this.cullExempt;
}
@Override
public void markModelGlowing(ActiveModel model, boolean flag) {
if (flag) {
this.glowingModel.add(model);
} else {
this.glowingModel.remove(model);
}
}
@Override
public void markBoneGlowing(ModelBone bone, boolean flag) {
if (flag) {
this.glowingBone.add(bone);
} else {
this.glowingBone.remove(bone);
}
}
@Override
public boolean isModelGlowing() {
return !this.glowingBone.isEmpty() || !this.glowingModel.isEmpty();
}
@Override
public Box getCullHitbox() {
return this.cullHitbox;
}
@Override
public void setCullHitbox(Box cullHitbox) {
this.cullHitbox = cullHitbox;
}
@Override
public Integer getCullInterval() {
return this.cullInterval;
}
@Override
public void setCullInterval(Integer cullInterval) {
this.cullInterval = cullInterval;
}
@Override
public Boolean getVerticalCull() {
return this.verticalCull;
}
@Override
public void setVerticalCull(Boolean verticalCull) {
this.verticalCull = verticalCull;
}
@Override
public Double getVerticalCullDistance() {
return this.verticalCullDistance;
}
@Override
public void setVerticalCullDistance(Double verticalCullDistance) {
this.verticalCullDistance = verticalCullDistance;
}
@Override
public CullType getVerticalCullType() {
return this.verticalCullType;
}
@Override
public void setVerticalCullType(CullType verticalCullType) {
this.verticalCullType = verticalCullType;
}
@Override
public Boolean getBackCull() {
return this.backCull;
}
@Override
public void setBackCull(Boolean backCull) {
this.backCull = backCull;
}
@Override
public Double getBackCullAngle() {
return this.backCullAngle;
}
@Override
public void setBackCullAngle(Double backCullAngle) {
this.backCullAngle = backCullAngle;
}
@Override
public Double getBackCullIgnoreRadius() {
return this.backCullIgnoreRadius;
}
@Override
public void setBackCullIgnoreRadius(Double backCullIgnoreRadius) {
this.backCullIgnoreRadius = backCullIgnoreRadius;
}
@Override
public CullType getBackCullType() {
return this.backCullType;
}
@Override
public void setBackCullType(CullType backCullType) {
this.backCullType = backCullType;
}
@Override
public Boolean getBlockedCull() {
return this.blockedCull;
}
@Override
public void setBlockedCull(Boolean blockedCull) {
this.blockedCull = blockedCull;
}
@Override
public Double getBlockedCullIgnoreRadius() {
return this.blockedCullIgnoreRadius;
}
@Override
public void setBlockedCullIgnoreRadius(Double blockedCullIgnoreRadius) {
this.blockedCullIgnoreRadius = blockedCullIgnoreRadius;
}
@Override
public CullType getBlockedCullType() {
return this.blockedCullType;
}
@Override
public void setBlockedCullType(CullType blockedCullType) {
this.blockedCullType = blockedCullType;
}
}
@@ -0,0 +1,547 @@
package com.ticxo.modelengine.api.entity.data;
import com.google.common.collect.ImmutableSet;
import com.ticxo.modelengine.api.ModelEngineAPI;
import com.ticxo.modelengine.api.ServerInfo;
import com.ticxo.modelengine.api.entity.BukkitEntity;
import com.ticxo.modelengine.api.entity.CullType;
import com.ticxo.modelengine.api.entity.Hitbox;
import com.ticxo.modelengine.api.entity.cull.BasicCulling;
import com.ticxo.modelengine.api.entity.cull.ModelCuller;
import com.ticxo.modelengine.api.nms.entity.AttributeAccessor;
import com.ticxo.modelengine.api.nms.entity.EntityHandler;
import com.ticxo.modelengine.api.nms.entity.EntityState;
import com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity;
import com.ticxo.modelengine.api.nms.impl.TempTrackedEntity;
import com.ticxo.modelengine.api.utils.data.QueuedAtomic;
import com.ticxo.modelengine.api.utils.data.QueuedBoolean;
import com.ticxo.modelengine.api.utils.data.QueuedFloat;
import com.ticxo.modelengine.api.utils.data.QueuedInt;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Predicate;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.util.BoundingBox;
public class BukkitEntityData extends AbstractEntityData {
protected final EntityHandler entityHandler = ModelEngineAPI.getEntityHandler();
protected final Entity entity;
protected final BukkitEntity baseEntity;
protected final ModelCuller culler;
protected final QueuedBoolean isEntityValid = new QueuedBoolean(false);
protected final QueuedBoolean isDataValid = new QueuedBoolean(false);
protected final QueuedBoolean isForcedAlive = new QueuedBoolean(true);
protected final QueuedAtomic<Location> location = QueuedAtomic.<Location>builder()
.value(() -> new Location(null, 0.0, 0.0, 0.0))
.passer((a, b) -> b.set(a.get().clone()))
.build();
protected final QueuedAtomic<List<Entity>> passengers = QueuedAtomic.<List<Entity>>builder().value(ArrayList::new).setter((v, r) -> {
r.get().clear();
r.get().addAll(v);
}).passer((a, b) -> {
b.get().clear();
b.get().addAll(a.get());
}).build();
protected final QueuedInt glowColor = new QueuedInt(-1);
protected volatile Hitbox hitbox;
protected final QueuedFloat yRot = new QueuedFloat(0.0F);
protected final QueuedFloat yHeadRot = new QueuedFloat(0.0F);
protected final QueuedFloat xHeadRot = new QueuedFloat(0.0F);
protected final QueuedFloat yBodyRot = new QueuedFloat(0.0F);
protected final QueuedBoolean isWalking = new QueuedBoolean(false);
protected final QueuedBoolean isStrafing = new QueuedBoolean(false);
protected final QueuedBoolean isJumping = new QueuedBoolean(false);
protected final QueuedBoolean isFlying = new QueuedBoolean(false);
protected final QueuedFloat health = new QueuedFloat(0.0F);
protected final QueuedFloat maxHealth = new QueuedFloat(0.0F);
protected final QueuedBoolean isRemoved = new QueuedBoolean(false);
protected final QueuedBoolean isBaseGlowing = new QueuedBoolean(false);
protected final QueuedBoolean isOnFire = new QueuedBoolean(false);
protected final QueuedAtomic<BoundingBox> boundingBox = QueuedAtomic.<BoundingBox>builder()
.value(() -> new BoundingBox(0.0, 0.0, 0.0, 0.0, 0.0, 0.0))
.build();
protected final Set<UUID> syncTracking = new HashSet<>();
private final TrackingMap trackingMap = new TrackingMap();
protected final Map<UUID, CullType> asyncTracking = this.trackingMap;
protected final Queue<Queue<UUID>> startTrackingQueue = new ConcurrentLinkedQueue<>();
protected final Set<UUID> startTracking = new HashSet<>();
protected final Queue<Queue<UUID>> stopTrackingQueue = new ConcurrentLinkedQueue<>();
protected final Set<UUID> stopTracking = new HashSet<>();
protected final Predicate<Player> trackingPredicate;
protected volatile TrackedEntity tracked;
protected final AttributeAccessor attributeAccessor;
protected int syncTick;
protected boolean wasValid;
protected int foliaExecuteFailures;
protected final Location reuseLoc = new Location(null, 0.0, 0.0, 0.0);
protected final EntityState reuseState = new EntityState();
protected final Set<UUID> reuseTracking = new HashSet<>();
private long lastTrackingVersion = -1L;
protected volatile Set<UUID> collidableExemptions;
protected volatile double stepHeight = Double.NaN;
private static final int SAVE_SNAPSHOT_INTERVAL = 20;
private int saveSnapshotCooldown;
public BukkitEntityData(Entity entity, BukkitEntity base) {
this(entity, base, new BasicCulling());
}
public BukkitEntityData(Entity entity, BukkitEntity base, ModelCuller culler) {
this.entity = entity;
this.baseEntity = base;
this.culler = culler;
culler.setData(this);
this.tracked = this.entityHandler.wrapTrackedEntity(entity);
this.attributeAccessor = this.entityHandler.createAttributeAccessor(entity);
this.trackingPredicate = player -> culler.getCulledCount() == 0 ? true : this.asyncTracking.get(player.getUniqueId()) != CullType.CULLED;
boolean offThread = ServerInfo.IS_FOLIA && !this.isRegionThread();
if (offThread) {
this.entityHandler.getLocation(entity, this.reuseLoc);
} else {
entity.getLocation(this.reuseLoc);
}
this.location.set(this.reuseLoc.clone());
if (offThread) {
this.isEntityValid.set(true);
this.isDataValid.set(true);
} else {
for (UUID uuid : this.tracked.getTrackedPlayer(this.trackingPredicate)) {
this.asyncTracking.put(uuid, CullType.NO_CULL);
this.syncTracking.add(uuid);
this.startTracking.add(uuid);
culler.put(uuid, CullType.NO_CULL);
}
if (ServerInfo.IS_FOLIA) {
this.internalSyncUpdate();
} else {
this.syncUpdate();
}
}
this.readEntityState();
this.asyncUpdate();
}
private void readEntityState() {
if (!ServerInfo.IS_FOLIA) {
this.isRemoved.set(this.entityHandler.isRemoved(this.entity));
} else {
this.entityHandler.readEntityState(this.entity, this.reuseState);
this.isRemoved.set(this.reuseState.removed);
this.yRot.set(this.reuseState.yRot);
this.yHeadRot.set(this.reuseState.yHeadRot);
this.xHeadRot.set(this.reuseState.xHeadRot);
this.yBodyRot.set(this.reuseState.yBodyRot);
this.isWalking.set(this.reuseState.walking);
this.isStrafing.set(this.reuseState.strafing);
this.isJumping.set(this.reuseState.jumping);
this.isFlying.set(this.reuseState.flying);
this.health.set(this.reuseState.health);
this.maxHealth.set(this.attributeAccessor.getMaxHealth());
this.isBaseGlowing.set(this.reuseState.glowing);
this.isOnFire.set(this.reuseState.onFire);
if (!this.reuseState.boundingBox.equals(this.boundingBox.getUnsafe())) {
this.boundingBox.set(this.reuseState.boundingBox.clone());
}
}
}
@Override
public void asyncUpdate() {
this.isEntityValid.pass();
this.isDataValid.pass();
this.isForcedAlive.pass();
this.location.pass();
this.passengers.pass();
this.glowColor.pass();
this.yRot.pass();
this.yHeadRot.pass();
this.xHeadRot.pass();
this.yBodyRot.pass();
this.isWalking.pass();
this.isStrafing.pass();
this.isJumping.pass();
this.isFlying.pass();
this.health.pass();
this.maxHealth.pass();
this.isRemoved.pass();
this.isBaseGlowing.pass();
this.isOnFire.pass();
this.boundingBox.pass();
while (!this.startTrackingQueue.isEmpty() || !this.stopTrackingQueue.isEmpty()) {
if (!this.startTrackingQueue.isEmpty()) {
Queue<UUID> playerQueue = this.startTrackingQueue.poll();
if (playerQueue != null) {
while (!playerQueue.isEmpty()) {
UUID player = playerQueue.poll();
this.startTracking.add(player);
this.stopTracking.remove(player);
this.culler.put(player, CullType.NO_CULL);
}
}
}
if (!this.stopTrackingQueue.isEmpty()) {
Queue<UUID> playerQueue = this.stopTrackingQueue.poll();
if (playerQueue != null) {
while (!playerQueue.isEmpty()) {
UUID player = playerQueue.poll();
this.stopTracking.add(player);
this.startTracking.remove(player);
if (this.asyncTracking.get(player) != CullType.CULLED) {
this.culler.remove(player);
}
}
}
}
}
}
@Override
public void syncUpdate() {
if (ServerInfo.IS_FOLIA) {
boolean scheduled = this.entity.getScheduler().execute(ModelEngineAPI.getAPI(), this::internalSyncUpdate, null, 1L);
if (scheduled) {
this.foliaExecuteFailures = 0;
} else {
Location loc = this.location.getUnsafe();
if (loc != null && loc.getWorld() != null) {
Bukkit.getRegionScheduler().execute(ModelEngineAPI.getAPI(), loc, this::internalSyncUpdate);
this.foliaExecuteFailures = 0;
} else {
this.foliaExecuteFailures++;
if (this.foliaExecuteFailures > 20) {
this.isEntityValid.set(false);
this.isDataValid.set(false);
}
}
}
} else {
this.internalSyncUpdate();
}
}
private void internalSyncUpdate() {
this.syncTick++;
boolean valid = this.entity.isValid();
this.wasValid = this.wasValid | (valid || this.syncTick > 20);
valid |= !this.wasValid;
if (this.isEntityValid.getUnsafe() != valid) {
this.isEntityValid.set(valid);
}
boolean removed = this.entityHandler.isRemoved(this.entity);
if (this.isForcedAlive()) {
this.entityHandler.setDeathTick(this.entity, 0);
} else if (!this.isEntityValid()) {
this.entityHandler.setDeathTick(this.entity, 20);
}
Location prevLoc = this.location.getUnsafe();
World prevWorld = prevLoc == null ? null : prevLoc.getWorld();
this.entity.getLocation(this.reuseLoc);
boolean worldChanged = false;
if (prevWorld != null) {
World newWorld = this.reuseLoc.getWorld();
worldChanged = newWorld != null && prevWorld != newWorld;
}
if (!this.reuseLoc.equals(prevLoc)) {
this.location.set(this.reuseLoc.clone());
}
this.passengers.set(this.entity.getPassengers());
this.safeSyncUpdate();
if (this.isDataValid.getUnsafe() != !removed) {
this.isDataValid.set(!removed);
}
this.updateTracking();
if (worldChanged) {
this.baseEntity.onWorldChanged();
}
}
private void updateTracking() {
boolean viewersUnchanged = this.getTracked().isViewerSetUnchanged();
long trackingVersion = this.trackingMap.getVersion();
if (!viewersUnchanged || trackingVersion != this.lastTrackingVersion) {
this.lastTrackingVersion = trackingVersion;
Set<UUID> updatedTracking = this.getTracked().getTrackedPlayer(this.trackingPredicate, this.reuseTracking);
Queue<UUID> startTrack = null;
Queue<UUID> stopTrack = null;
int seen = 0;
for (UUID player : updatedTracking) {
seen++;
if (this.syncTracking.add(player)) {
if (startTrack == null) {
startTrack = new ConcurrentLinkedQueue<>();
}
startTrack.add(player);
}
}
if (updatedTracking != this.reuseTracking || this.syncTracking.size() != seen) {
Iterator<UUID> it = this.syncTracking.iterator();
while (it.hasNext()) {
UUID playerx = it.next();
if (!updatedTracking.contains(playerx)) {
if (stopTrack == null) {
stopTrack = new ConcurrentLinkedQueue<>();
}
stopTrack.add(playerx);
it.remove();
}
}
}
if (stopTrack != null) {
this.stopTrackingQueue.add(stopTrack);
}
if (startTrack != null) {
this.startTrackingQueue.add(startTrack);
}
}
}
private boolean isRegionThread() {
return ServerInfo.IS_FOLIA ? Bukkit.isOwnedByCurrentRegion(this.entity) : Bukkit.isPrimaryThread();
}
protected void safeSyncUpdate() {
this.glowColor.set(this.entityHandler.getGlowColor(this.entity));
Hitbox hitbox = this.hitbox;
if (hitbox != null && ((float)this.entity.getWidth() != (float)hitbox.getMaxWidth() || (float)this.entity.getHeight() != (float)hitbox.getHeight())) {
this.entityHandler.setHitbox(this.entity, hitbox);
}
this.readEntityState();
if (ServerInfo.IS_FOLIA || --this.saveSnapshotCooldown <= 0) {
this.saveSnapshotCooldown = 20;
this.refreshSaveSnapshots();
}
}
public void setHitbox(Hitbox hitbox) {
this.entityHandler.setHitbox(this.entity, hitbox);
if (!(this.entity instanceof Player)) {
this.hitbox = hitbox;
}
}
public void refreshSaveSnapshots() {
Set<UUID> exemptions = this.entityHandler.getCollidableExemptions(this.entity);
if (exemptions != null && !exemptions.equals(this.collidableExemptions)) {
this.collidableExemptions = Set.copyOf(exemptions);
}
if (ServerInfo.IS_FOLIA) {
this.stepHeight = this.entityHandler.getStepHeight(this.entity);
}
}
public Set<UUID> getCollidableExemptions() {
return this.collidableExemptions;
}
public double getStepHeight() {
return ServerInfo.IS_FOLIA ? this.stepHeight : this.entityHandler.getStepHeight(this.entity);
}
@Override
public void cullUpdate() {
this.culler.updateCulledPlayer();
}
@Override
public void cleanup() {
this.startTracking.clear();
this.stopTracking.clear();
}
@Override
public void destroy() {
this.startTrackingQueue.forEach(Collection::clear);
this.startTrackingQueue.clear();
this.stopTrackingQueue.forEach(Collection::clear);
this.stopTrackingQueue.clear();
}
@Override
public boolean isDataValid() {
return this.isDataValid.get();
}
public boolean isEntityValid() {
return this.isEntityValid.get();
}
public boolean isForcedAlive() {
return this.isForcedAlive.get();
}
public void setForcedAlive(boolean flag) {
this.isForcedAlive.set(flag);
}
public int getGlowColor() {
return this.glowColor.get();
}
@Override
public Location getLocation() {
return this.location.get().clone();
}
@Override
public List<Entity> getPassengers() {
return this.passengers.get();
}
@Override
public void markViewersDirty() {
TrackedEntity current = this.tracked;
if (current != null) {
current.markViewersDirty();
}
}
@Override
public Set<UUID> getStartTracking() {
return ImmutableSet.copyOf(this.startTracking);
}
public void resendTracking(UUID player) {
if (this.asyncTracking.containsKey(player)) {
Queue<UUID> queue = new ConcurrentLinkedQueue<>();
queue.add(player);
this.startTrackingQueue.add(queue);
}
}
@Override
public Map<UUID, CullType> getMutableTracking() {
return this.asyncTracking;
}
@Override
public Map<UUID, CullType> getTracking() {
return this.trackingMap.snapshot();
}
@Override
public Set<UUID> getStopTracking() {
return ImmutableSet.copyOf(this.stopTracking);
}
@Override
public boolean hasTracking() {
return !this.asyncTracking.isEmpty() && this.culler.getCulledCount() != this.asyncTracking.size();
}
@Override
public boolean isBaseGlowing() {
return ServerInfo.IS_FOLIA ? this.isBaseGlowing.get() : this.entityHandler.isGlowing(this.entity);
}
public boolean isOnFire() {
return ServerInfo.IS_FOLIA ? this.isOnFire.get() : this.entityHandler.isVisualFire(this.entity) || this.entityHandler.getFireTicks(this.entity) > 0;
}
public TrackedEntity getTracked() {
if (this.tracked instanceof TempTrackedEntity tempTracked) {
TrackedEntity newTracked = this.entityHandler.wrapTrackedEntity(this.entity);
if (!(newTracked instanceof TempTrackedEntity)) {
if (tempTracked.getBaseRange() != -1) {
newTracked.setBaseRange(tempTracked.getBaseRange());
}
newTracked.setPlayerPredicate(tempTracked.getPlayerPredicate());
for (UUID player : tempTracked.getForcePaired()) {
newTracked.addForcedPairing(player);
}
for (UUID player : tempTracked.getForceHidden()) {
newTracked.addForcedHidden(player);
}
this.tracked = newTracked;
}
}
return this.tracked;
}
public float getYRot() {
return ServerInfo.IS_FOLIA ? this.yRot.get() : this.entityHandler.getYRot(this.entity);
}
public float getYHeadRot() {
return ServerInfo.IS_FOLIA ? this.yHeadRot.get() : this.entityHandler.getYHeadRot(this.entity);
}
public float getXHeadRot() {
return ServerInfo.IS_FOLIA ? this.xHeadRot.get() : this.entityHandler.getXHeadRot(this.entity);
}
public float getYBodyRot() {
return ServerInfo.IS_FOLIA ? this.yBodyRot.get() : this.entityHandler.getYBodyRot(this.entity);
}
public boolean isWalking() {
return ServerInfo.IS_FOLIA ? this.isWalking.get() : this.entityHandler.isWalking(this.entity);
}
public boolean isStrafing() {
return ServerInfo.IS_FOLIA ? this.isStrafing.get() : this.entityHandler.isStrafing(this.entity);
}
public boolean isJumping() {
return ServerInfo.IS_FOLIA ? this.isJumping.get() : this.entityHandler.isJumping(this.entity);
}
public boolean isFlying() {
return ServerInfo.IS_FOLIA ? this.isFlying.get() : this.entityHandler.isFlying(this.entity);
}
public float getHealth() {
return ServerInfo.IS_FOLIA ? this.health.get() : this.entityHandler.getHealth(this.entity);
}
public float getMaxHealth() {
return ServerInfo.IS_FOLIA ? this.maxHealth.get() : this.attributeAccessor.getMaxHealth();
}
public boolean isRemoved() {
return this.isRemoved.get();
}
public BoundingBox getBoundingBox() {
return ServerInfo.IS_FOLIA ? this.boundingBox.get().clone() : this.entityHandler.getBoundingBox(this.entity);
}
public BukkitEntity getBaseEntity() {
return this.baseEntity;
}
}
@@ -0,0 +1,186 @@
package com.ticxo.modelengine.api.entity.data;
import com.google.common.collect.ImmutableSet;
import com.ticxo.modelengine.api.entity.BaseEntity;
import com.ticxo.modelengine.api.entity.CullType;
import com.ticxo.modelengine.api.entity.Dummy;
import com.ticxo.modelengine.api.entity.cull.BasicCulling;
import com.ticxo.modelengine.api.entity.cull.ModelCuller;
import com.ticxo.modelengine.api.nms.impl.DummyTrackedEntity;
import com.ticxo.modelengine.api.utils.callback.Callback;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
public class DummyEntityData<T> extends AbstractEntityData {
protected final Dummy<T> dummy;
protected final DummyTrackedEntity tracked;
protected final ModelCuller culler;
protected final Set<UUID> syncTracking = new HashSet<>();
private final TrackingMap trackingMap = new TrackingMap();
protected final Map<UUID, CullType> asyncTracking = this.trackingMap;
protected final Queue<UUID> startTrackingQueue = new ConcurrentLinkedQueue<>();
protected final Set<UUID> startTracking = new HashSet<>();
protected final Queue<UUID> stopTrackingQueue = new ConcurrentLinkedQueue<>();
protected final Set<UUID> stopTracking = new HashSet<>();
protected final Callback<Runnable> syncUpdateCallback = new Callback<>(runnables -> () -> runnables.forEach(Runnable::run));
protected final Callback<Runnable> asyncUpdateCallback = new Callback<>(runnables -> () -> runnables.forEach(Runnable::run));
protected Location location;
protected boolean baseGlowing;
public DummyEntityData(Dummy<T> dummy) {
this(dummy, new BasicCulling());
}
public DummyEntityData(Dummy<T> dummy, ModelCuller culler) {
this.dummy = dummy;
this.culler = culler;
culler.setData(this);
this.tracked = new DummyTrackedEntity();
this.syncUpdate();
this.asyncUpdate();
}
@Override
public void asyncUpdate() {
while (!this.startTrackingQueue.isEmpty()) {
UUID player = this.startTrackingQueue.poll();
this.startTracking.add(player);
this.asyncTracking.put(player, CullType.NO_CULL);
}
while (!this.stopTrackingQueue.isEmpty()) {
UUID player = this.stopTrackingQueue.poll();
this.stopTracking.add(player);
if (this.asyncTracking.get(player) != CullType.CULLED) {
this.asyncTracking.remove(player);
}
}
this.asyncUpdateCallback.invoker().run();
}
@Override
public void syncUpdate() {
if (this.dummy.isDetectingPlayers() && this.location != null) {
this.tracked.detectPlayers(this.location);
}
Set<UUID> updatedTracking = this.tracked.getTrackedPlayer(playerx -> this.asyncTracking.get(playerx.getUniqueId()) != CullType.CULLED);
for (UUID player : updatedTracking) {
if (!this.syncTracking.contains(player)) {
this.startTrackingQueue.add(player);
}
}
for (UUID playerx : this.syncTracking) {
if (!updatedTracking.contains(playerx)) {
this.stopTrackingQueue.add(playerx);
}
}
this.syncTracking.clear();
this.syncTracking.addAll(updatedTracking);
this.syncUpdateCallback.invoker().run();
}
@Override
public void cullUpdate() {
this.culler.updateCulledPlayer();
}
@Override
public void cleanup() {
this.startTracking.clear();
this.stopTracking.clear();
}
@Override
public void destroy() {
}
@Override
public BaseEntity<?> getBaseEntity() {
return this.dummy;
}
@Override
public boolean isDataValid() {
return this.dummy.isAlive();
}
@Override
public List<Entity> getPassengers() {
return List.of();
}
@Override
public Set<UUID> getStartTracking() {
return ImmutableSet.copyOf(this.startTracking);
}
@Override
public Map<UUID, CullType> getMutableTracking() {
return this.asyncTracking;
}
@Override
public Map<UUID, CullType> getTracking() {
return this.trackingMap.snapshot();
}
@Override
public Set<UUID> getStopTracking() {
return ImmutableSet.copyOf(this.stopTracking);
}
@Override
public boolean hasTracking() {
return !this.asyncTracking.isEmpty();
}
public int getRenderRadius() {
return this.tracked.getBaseRange();
}
public void setRenderRadius(int radius) {
this.tracked.setBaseRange(radius);
}
public DummyTrackedEntity getTracked() {
return this.tracked;
}
public Callback<Runnable> getSyncUpdateCallback() {
return this.syncUpdateCallback;
}
public Callback<Runnable> getAsyncUpdateCallback() {
return this.asyncUpdateCallback;
}
@Override
public Location getLocation() {
return this.location;
}
public void setLocation(Location location) {
this.location = location;
}
@Override
public boolean isBaseGlowing() {
return this.baseGlowing;
}
public void setBaseGlowing(boolean baseGlowing) {
this.baseGlowing = baseGlowing;
}
}
@@ -0,0 +1,176 @@
package com.ticxo.modelengine.api.entity.data;
import com.ticxo.modelengine.api.entity.BaseEntity;
import com.ticxo.modelengine.api.entity.CullType;
import com.ticxo.modelengine.api.model.ActiveModel;
import com.ticxo.modelengine.api.model.bone.ModelBone;
import com.ticxo.modelengine.api.utils.data.io.DataIO;
import com.ticxo.modelengine.api.utils.data.io.SavedData;
import com.ticxo.modelengine.api.utils.math.Box;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.ApiStatus.Internal;
public interface IEntityData extends DataIO {
SavedData.DataSaver<CullType> CULL_TYPE_DATA_SAVER = (data, s, cullType) -> data.putString(s, cullType.name());
SavedData.DataLoader<CullType> CULL_TYPE_DATA_LOADER = (data, key) -> {
String s = data.getString(key);
return s == null ? null : CullType.get(s);
};
void asyncUpdate();
void syncUpdate();
void cullUpdate();
void cleanup();
void destroy();
BaseEntity<?> getBaseEntity();
boolean isDataValid();
Location getLocation();
List<Entity> getPassengers();
default void markViewersDirty() {
}
Set<UUID> getStartTracking();
@Internal
Map<UUID, CullType> getMutableTracking();
Map<UUID, CullType> getTracking();
Set<UUID> getStopTracking();
boolean hasTracking();
Box getCullHitbox();
void setCullHitbox(Box var1);
Integer getCullInterval();
void setCullInterval(Integer var1);
int cullInterval();
Boolean getVerticalCull();
void setVerticalCull(Boolean var1);
boolean verticalCull();
Double getVerticalCullDistance();
void setVerticalCullDistance(Double var1);
double verticalCullDistance();
CullType getVerticalCullType();
void setVerticalCullType(CullType var1);
CullType verticalCullType();
Boolean getBackCull();
void setBackCull(Boolean var1);
boolean backCull();
Double getBackCullAngle();
void setBackCullAngle(Double var1);
double backCullAngle();
Double getBackCullIgnoreRadius();
void setBackCullIgnoreRadius(Double var1);
double backCullIgnoreRadius();
CullType getBackCullType();
void setBackCullType(CullType var1);
CullType backCullType();
Boolean getBlockedCull();
void setBlockedCull(Boolean var1);
boolean blockedCull();
Double getBlockedCullIgnoreRadius();
void setBlockedCullIgnoreRadius(Double var1);
double blockedCullIgnoreRadius();
CullType getBlockedCullType();
void setBlockedCullType(CullType var1);
CullType blockedCullType();
void setCullExempt(UUID var1, boolean var2);
boolean isCullExempt(UUID var1);
Set<UUID> getCullExempt();
void markModelGlowing(ActiveModel var1, boolean var2);
void markBoneGlowing(ModelBone var1, boolean var2);
boolean isModelGlowing();
boolean isBaseGlowing();
@Override
default void save(SavedData data) {
data.saveIfExist("cull_interval", this::getCullInterval, SavedData::putInt);
data.saveIfExist("vertical_cull", this::getVerticalCull, SavedData::putBoolean);
data.saveIfExist("vertical_cull_distance", this::getVerticalCullDistance, SavedData::putDouble);
data.saveIfExist("vertical_cull_type", this::getVerticalCullType, CULL_TYPE_DATA_SAVER);
data.saveIfExist("back_cull", this::getBackCull, SavedData::putBoolean);
data.saveIfExist("back_cull_angle", this::getBackCullAngle, SavedData::putDouble);
data.saveIfExist("back_cull_ignore_radius", this::getBackCullIgnoreRadius, SavedData::putDouble);
data.saveIfExist("back_cull_type", this::getBackCullType, CULL_TYPE_DATA_SAVER);
data.saveIfExist("blocked_cull", this::getBlockedCull, SavedData::putBoolean);
data.saveIfExist("blocked_cull_ignore_radius", this::getBlockedCullIgnoreRadius, SavedData::putDouble);
data.saveIfExist("blocked_cull_type", this::getBlockedCullType, CULL_TYPE_DATA_SAVER);
}
@Override
default void load(SavedData data) {
data.loadIfExist("cull_interval", SavedData::getInt, this::setCullInterval);
data.loadIfExist("vertical_cull", SavedData::getBoolean, this::setVerticalCull);
data.loadIfExist("vertical_cull_distance", SavedData::getDouble, this::setVerticalCullDistance);
data.loadIfExist("vertical_cull_type", CULL_TYPE_DATA_LOADER, this::setVerticalCullType);
data.loadIfExist("back_cull", SavedData::getBoolean, this::setBackCull);
data.loadIfExist("back_cull_angle", SavedData::getDouble, this::setBackCullAngle);
data.loadIfExist("back_cull_ignore_radius", SavedData::getDouble, this::setBackCullIgnoreRadius);
data.loadIfExist("back_cull_type", CULL_TYPE_DATA_LOADER, this::setBackCullType);
data.loadIfExist("blocked_cull", SavedData::getBoolean, this::setBlockedCull);
data.loadIfExist("blocked_cull_ignore_radius", SavedData::getDouble, this::setBlockedCullIgnoreRadius);
data.loadIfExist("blocked_cull_type", CULL_TYPE_DATA_LOADER, this::setBlockedCullType);
}
@FunctionalInterface
public interface CullCameraOverride {
Location calculate(IEntityData var1, Player var2, Location var3);
}
}
@@ -0,0 +1,173 @@
package com.ticxo.modelengine.api.entity.data;
import com.ticxo.modelengine.api.entity.CullType;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
import java.util.function.Function;
public class TrackingMap extends ConcurrentHashMap<UUID, CullType> {
private static final long serialVersionUID = 1L;
private final AtomicLong version = new AtomicLong();
private transient volatile TrackingMap.Snapshot snapshot;
public Map<UUID, CullType> snapshot() {
long current = this.version.get();
TrackingMap.Snapshot cached = this.snapshot;
if (cached != null && cached.version == current && cached.map.size() == this.size()) {
return cached.map;
} else {
Map<UUID, CullType> copy = Collections.unmodifiableMap(new HashMap<>(this));
this.snapshot = new TrackingMap.Snapshot(current, copy);
return copy;
}
}
public long getVersion() {
return this.version.get();
}
private void touch() {
this.version.incrementAndGet();
}
public CullType put(UUID key, CullType value) {
CullType previous = super.put(key, value);
if (previous != value) {
this.touch();
}
return previous;
}
public CullType putIfAbsent(UUID key, CullType value) {
CullType previous = super.putIfAbsent(key, value);
if (previous == null) {
this.touch();
}
return previous;
}
@Override
public void putAll(Map<? extends UUID, ? extends CullType> m) {
try {
super.putAll(m);
} finally {
this.touch();
}
}
public CullType remove(Object key) {
CullType previous = (CullType)super.remove(key);
if (previous != null) {
this.touch();
}
return previous;
}
@Override
public boolean remove(Object key, Object value) {
boolean removed = super.remove(key, value);
if (removed) {
this.touch();
}
return removed;
}
public CullType replace(UUID key, CullType value) {
CullType previous = super.replace(key, value);
if (previous != null && previous != value) {
this.touch();
}
return previous;
}
public boolean replace(UUID key, CullType oldValue, CullType newValue) {
boolean replaced = super.replace(key, oldValue, newValue);
if (replaced && oldValue != newValue) {
this.touch();
}
return replaced;
}
@Override
public void clear() {
try {
super.clear();
} finally {
this.touch();
}
}
public CullType compute(UUID key, BiFunction<? super UUID, ? super CullType, ? extends CullType> function) {
CullType var3;
try {
var3 = super.compute(key, function);
} finally {
this.touch();
}
return var3;
}
public CullType computeIfAbsent(UUID key, Function<? super UUID, ? extends CullType> function) {
CullType var3;
try {
var3 = super.computeIfAbsent(key, function);
} finally {
this.touch();
}
return var3;
}
public CullType computeIfPresent(UUID key, BiFunction<? super UUID, ? super CullType, ? extends CullType> function) {
CullType var3;
try {
var3 = super.computeIfPresent(key, function);
} finally {
this.touch();
}
return var3;
}
public CullType merge(UUID key, CullType value, BiFunction<? super CullType, ? super CullType, ? extends CullType> function) {
CullType var4;
try {
var4 = super.merge(key, value, function);
} finally {
this.touch();
}
return var4;
}
@Override
public void replaceAll(BiFunction<? super UUID, ? super CullType, ? extends CullType> function) {
try {
super.replaceAll(function);
} finally {
this.touch();
}
}
private static final class Snapshot {
private final long version;
private final Map<UUID, CullType> map;
private Snapshot(long version, Map<UUID, CullType> map) {
this.version = version;
this.map = map;
}
}
}
@@ -0,0 +1,43 @@
package com.ticxo.modelengine.api.error;
import com.ticxo.modelengine.api.utils.config.ConfigProperty;
import com.ticxo.modelengine.api.utils.logger.LogColor;
import com.ticxo.modelengine.api.utils.logger.TLogger;
import java.util.ArrayList;
import java.util.List;
public class ErrorCollector {
private final String fileName;
private final List<IError> errorList = new ArrayList<>();
public void collect(IError error) {
this.errorList.add(error);
}
public void logAll() {
if (!ConfigProperty.LOG_ONLY_ERROR.getBoolean() || !this.errorList.isEmpty()) {
if (!this.errorList.isEmpty()) {
TLogger.log();
}
TLogger.log(LogColor.CYAN + "Importing " + this.fileName + ".");
this.errorList.forEach(IError::log);
}
}
public boolean hasError() {
return !this.errorList.isEmpty();
}
public ErrorCollector(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
return this.fileName;
}
public List<IError> getErrorList() {
return this.errorList;
}
}
@@ -0,0 +1,26 @@
package com.ticxo.modelengine.api.error;
import com.ticxo.modelengine.api.utils.logger.LogColor;
public class ErrorIncompatibleBone extends IError.Error {
private final boolean rendering;
private final String boneName;
private final String id;
@Override
public String getErrorMessage() {
return String.format(
"Error: The %s bone behavior type %s is not compatible with %s %s.",
this.rendering ? "ghost" : "renderer",
LogColor.BLUE + this.id + LogColor.RED,
this.rendering ? "renderer bone" : "ghost bone",
LogColor.BLUE + this.boneName + LogColor.RED
);
}
public ErrorIncompatibleBone(boolean rendering, String boneName, String id) {
this.rendering = rendering;
this.boneName = boneName;
this.id = id;
}
}
@@ -0,0 +1,26 @@
package com.ticxo.modelengine.api.error;
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
import com.ticxo.modelengine.api.utils.logger.LogColor;
public class ErrorMissingBoneBehaviorData extends IError.Error {
private final String bone;
private final BoneBehaviorType<?> boneBehaviorType;
private final String key;
@Override
public String getErrorMessage() {
return String.format(
"Error: The bone behavior %s of %s is missing required data %s. Removing behavior.",
LogColor.BLUE + this.boneBehaviorType.getId() + LogColor.RED,
LogColor.BLUE + this.bone + LogColor.RED,
LogColor.BLUE + this.key + LogColor.RED
);
}
public ErrorMissingBoneBehaviorData(String bone, BoneBehaviorType<?> boneBehaviorType, String key) {
this.bone = bone;
this.boneBehaviorType = boneBehaviorType;
this.key = key;
}
}
@@ -0,0 +1,22 @@
package com.ticxo.modelengine.api.error;
import com.ticxo.modelengine.api.utils.logger.LogColor;
public class ErrorNoFaceCube extends IError.Error {
private final String bone;
private final String cube;
@Override
public String getErrorMessage() {
return String.format(
"Error: The cube %s in bone %s has no faces. This might be caused by all faces having UV size of 0. Excluding cube from bone.",
LogColor.BLUE + this.cube + LogColor.RED,
LogColor.BLUE + this.bone + LogColor.RED
);
}
public ErrorNoFaceCube(String bone, String cube) {
this.bone = bone;
this.cube = cube;
}
}
@@ -0,0 +1,18 @@
package com.ticxo.modelengine.api.error;
import com.ticxo.modelengine.api.utils.logger.LogColor;
public class ErrorUnknownBoneBehavior extends IError.Error {
private final String boneName;
private final String id;
@Override
public String getErrorMessage() {
return String.format("Error: Unknown bone behavior %s on bone %s.", LogColor.BLUE + this.id + LogColor.RED, LogColor.BLUE + this.boneName + LogColor.RED);
}
public ErrorUnknownBoneBehavior(String boneName, String id) {
this.boneName = boneName;
this.id = id;
}
}
@@ -0,0 +1,8 @@
package com.ticxo.modelengine.api.error;
public class ErrorUnknownFormat extends IError.Error {
@Override
public String getErrorMessage() {
return "Error: Unknown format.";
}
}
@@ -0,0 +1,32 @@
package com.ticxo.modelengine.api.error;
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
import com.ticxo.modelengine.api.utils.logger.LogColor;
public class ErrorWrongBoneBehaviorDataType extends IError.Error {
private final String bone;
private final BoneBehaviorType<?> boneBehaviorType;
private final String key;
private final Class<?> expects;
private final Class<?> provided;
@Override
public String getErrorMessage() {
return String.format(
"Error: The bone behavior %s of %s was given the wrong data type for %s. Expected %s, provided %s. Removing behavior.",
LogColor.BLUE + this.boneBehaviorType.getId() + LogColor.RED,
LogColor.BLUE + this.bone + LogColor.RED,
LogColor.BLUE + this.key + LogColor.RED,
LogColor.BLUE + this.expects.getSimpleName() + LogColor.RED,
LogColor.BLUE + this.provided.getSimpleName() + LogColor.RED
);
}
public ErrorWrongBoneBehaviorDataType(String bone, BoneBehaviorType<?> boneBehaviorType, String key, Class<?> expects, Class<?> provided) {
this.bone = bone;
this.boneBehaviorType = boneBehaviorType;
this.key = key;
this.expects = expects;
this.provided = provided;
}
}
@@ -0,0 +1,50 @@
package com.ticxo.modelengine.api.error;
import com.ticxo.modelengine.api.utils.config.ConfigProperty;
import com.ticxo.modelengine.api.utils.logger.TLogger;
public interface IError {
ErrorUnknownFormat UNKNOWN_FORMAT = new ErrorUnknownFormat();
WarnBoxUV BOX_UV = new WarnBoxUV();
WarnBadEyeHeight BAD_EYE_HEIGHT = new WarnBadEyeHeight();
WarnNoHitbox NO_HITBOX = new WarnNoHitbox();
String getErrorMessage();
IError.Severity getSeverity();
default void log(ErrorCollector collector) {
collector.collect(this);
}
default void log() {
if (ConfigProperty.ERROR.getBoolean()) {
switch (this.getSeverity()) {
case WARN:
TLogger.warn("--" + this.getErrorMessage());
break;
case ERROR:
TLogger.error("--" + this.getErrorMessage());
}
}
}
public abstract static class Error implements IError {
@Override
public IError.Severity getSeverity() {
return IError.Severity.ERROR;
}
}
public static enum Severity {
WARN,
ERROR;
}
public abstract static class Warn implements IError {
@Override
public IError.Severity getSeverity() {
return IError.Severity.WARN;
}
}
}
@@ -0,0 +1,25 @@
package com.ticxo.modelengine.api.error;
import com.ticxo.modelengine.api.utils.logger.LogColor;
public class WarnBadAngle extends IError.Warn {
private final String bone;
private final String cube;
private final double angle;
@Override
public String getErrorMessage() {
return String.format(
"Warning: The cube %s in bone %s has illegal rotations. Cube rotation can only be -45, -22.5, 0, 22.5 and 45. [ %s ]",
LogColor.BLUE + this.cube + LogColor.YELLOW,
LogColor.BLUE + this.bone + LogColor.YELLOW,
this.angle
);
}
public WarnBadAngle(String bone, String cube, double angle) {
this.bone = bone;
this.cube = cube;
this.angle = angle;
}
}
@@ -0,0 +1,8 @@
package com.ticxo.modelengine.api.error;
public class WarnBadEyeHeight extends IError.Warn {
@Override
public String getErrorMessage() {
return "Warning: Eye height is below 0. Entity might suffocate.";
}
}
@@ -0,0 +1,15 @@
package com.ticxo.modelengine.api.error;
public class WarnBadNamespace extends IError.Warn {
private final String namespace;
@Override
public String getErrorMessage() {
return "Warning: Namespace contains characters other than a-z_0-9. Using default namespace.[" + this.namespace + "]";
}
public WarnBadNamespace(String namespace) {
this.namespace = namespace;
}
}
@@ -0,0 +1,23 @@
package com.ticxo.modelengine.api.error;
import com.ticxo.modelengine.api.utils.data.ResourceLocation;
import com.ticxo.modelengine.api.utils.logger.LogColor;
public class WarnBadTexture extends IError.Warn {
private final ResourceLocation name;
private final ResourceLocation correct;
@Override
public String getErrorMessage() {
return String.format(
"Warn: Texture name %s contains non [a-z0-9/._-] characters. Using alternative texture name %s.",
LogColor.BLUE + this.name.toString() + LogColor.YELLOW,
LogColor.BLUE + this.correct.toString() + LogColor.YELLOW
);
}
public WarnBadTexture(ResourceLocation name, ResourceLocation correct) {
this.name = name;
this.correct = correct;
}
}
@@ -0,0 +1,37 @@
package com.ticxo.modelengine.api.error;
import com.ticxo.modelengine.api.utils.logger.LogColor;
public class WarnBadTranslation extends IError.Warn {
private final String bone;
private double x;
private double y;
private double z;
@Override
public String getErrorMessage() {
return String.format(
"Warning: The bone %s is translated too far away from the pivot. Maximum translation is 80x80x80. [ %s, %s, %s ]",
LogColor.BLUE + this.bone + LogColor.YELLOW,
this.x,
this.y,
this.z
);
}
public WarnBadTranslation(String bone) {
this.bone = bone;
}
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
public void setZ(double z) {
this.z = z;
}
}
@@ -0,0 +1,33 @@
package com.ticxo.modelengine.api.error;
import com.ticxo.modelengine.api.utils.logger.LogColor;
public class WarnBoneTooLarge extends IError.Warn {
private final String bone;
private double x;
private double y;
private double z;
@Override
public String getErrorMessage() {
return String.format(
"Warning: The bone %s exceeds the maximum size of 120x120x120. [ %s, %s, %s ]", LogColor.BLUE + this.bone + LogColor.YELLOW, this.x, this.y, this.z
);
}
public WarnBoneTooLarge(String bone) {
this.bone = bone;
}
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
public void setZ(double z) {
this.z = z;
}
}
@@ -0,0 +1,8 @@
package com.ticxo.modelengine.api.error;
public class WarnBoxUV extends IError.Warn {
@Override
public String getErrorMessage() {
return "Warning: Box UV detected. Cube UVs might not generate correctly if Box UV is used.";
}
}
@@ -0,0 +1,23 @@
package com.ticxo.modelengine.api.error;
import com.ticxo.modelengine.api.utils.data.ResourceLocation;
import com.ticxo.modelengine.api.utils.logger.LogColor;
public class WarnDuplicateTexture extends IError.Warn {
private final ResourceLocation name;
private final ResourceLocation correct;
@Override
public String getErrorMessage() {
return String.format(
"Warn: Texture name %s already exists. Using alternative texture name %s.",
LogColor.BLUE + this.name.toString() + LogColor.YELLOW,
LogColor.BLUE + this.correct.toString() + LogColor.YELLOW
);
}
public WarnDuplicateTexture(ResourceLocation name, ResourceLocation correct) {
this.name = name;
this.correct = correct;
}
}
@@ -0,0 +1,22 @@
package com.ticxo.modelengine.api.error;
import com.ticxo.modelengine.api.utils.logger.LogColor;
public class WarnIncompatibleBoneBehavior extends IError.Warn {
private final String boneName;
private final String id;
@Override
public String getErrorMessage() {
return String.format(
"Warning: Bone behavior %s on bone %s detected incompatibility with other bone behaviors. Beware of bugs and glitches.",
LogColor.BLUE + this.id + LogColor.YELLOW,
LogColor.BLUE + this.boneName + LogColor.YELLOW
);
}
public WarnIncompatibleBoneBehavior(String boneName, String id) {
this.boneName = boneName;
this.id = id;
}
}
@@ -0,0 +1,22 @@
package com.ticxo.modelengine.api.error;
import com.ticxo.modelengine.api.utils.logger.LogColor;
public class WarnMultipleAngle extends IError.Warn {
private final String bone;
private final String cube;
@Override
public String getErrorMessage() {
return String.format(
"Warning: The cube %s in bone %s is rotated in multiple axis. Choosing one axis.",
LogColor.BLUE + this.cube + LogColor.YELLOW,
LogColor.BLUE + this.bone + LogColor.YELLOW
);
}
public WarnMultipleAngle(String bone, String cube) {
this.bone = bone;
this.cube = cube;
}
}
@@ -0,0 +1,8 @@
package com.ticxo.modelengine.api.error;
public class WarnNoHitbox extends IError.Warn {
@Override
public String getErrorMessage() {
return "Warning: Missing hitbox.";
}
}
@@ -0,0 +1,23 @@
package com.ticxo.modelengine.api.error;
import com.ticxo.modelengine.api.utils.logger.LogColor;
import java.util.UUID;
public class WarningDuplicateBoneName extends IError.Warn {
private final String bone;
private final UUID uuid;
@Override
public String getErrorMessage() {
return String.format(
"Warning: Model contains duplicate bone names %s. Naming bone with UUID %s",
LogColor.BLUE + this.bone + LogColor.YELLOW,
LogColor.BLUE + this.uuid.toString() + LogColor.YELLOW
);
}
public WarningDuplicateBoneName(String bone, UUID uuid) {
this.bone = bone;
this.uuid = uuid;
}
}
@@ -0,0 +1,10 @@
package com.ticxo.modelengine.api.events;
import org.bukkit.Bukkit;
import org.bukkit.event.Event;
public abstract class AbstractEvent extends Event {
public AbstractEvent() {
super(!Bukkit.isPrimaryThread());
}
}
@@ -0,0 +1,54 @@
package com.ticxo.modelengine.api.events;
import com.ticxo.modelengine.api.model.ActiveModel;
import com.ticxo.modelengine.api.model.ModeledEntity;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class AddModelEvent extends AbstractEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final ModeledEntity target;
private final ActiveModel model;
private boolean overrideHitbox;
private boolean cancelled;
@NotNull
public static HandlerList getHandlerList() {
return handlers;
}
@NotNull
public HandlerList getHandlers() {
return handlers;
}
public ModeledEntity getTarget() {
return this.target;
}
public ActiveModel getModel() {
return this.model;
}
public boolean isOverrideHitbox() {
return this.overrideHitbox;
}
public boolean isCancelled() {
return this.cancelled;
}
public void setOverrideHitbox(boolean overrideHitbox) {
this.overrideHitbox = overrideHitbox;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public AddModelEvent(ModeledEntity target, ActiveModel model) {
this.target = target;
this.model = model;
}
}
@@ -0,0 +1,35 @@
package com.ticxo.modelengine.api.events;
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
import com.ticxo.modelengine.api.model.ActiveModel;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class AnimationEndEvent extends AbstractEvent {
private static final HandlerList handlers = new HandlerList();
private final ActiveModel model;
private final IAnimationProperty property;
@NotNull
public static HandlerList getHandlerList() {
return handlers;
}
@NotNull
public HandlerList getHandlers() {
return handlers;
}
public ActiveModel getModel() {
return this.model;
}
public IAnimationProperty getProperty() {
return this.property;
}
public AnimationEndEvent(ActiveModel model, IAnimationProperty property) {
this.model = model;
this.property = property;
}
}
@@ -0,0 +1,45 @@
package com.ticxo.modelengine.api.events;
import com.ticxo.modelengine.api.animation.property.IAnimationProperty;
import com.ticxo.modelengine.api.model.ActiveModel;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class AnimationPlayEvent extends AbstractEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final ActiveModel model;
private final IAnimationProperty property;
private boolean cancelled;
@NotNull
public static HandlerList getHandlerList() {
return handlers;
}
@NotNull
public HandlerList getHandlers() {
return handlers;
}
public ActiveModel getModel() {
return this.model;
}
public IAnimationProperty getProperty() {
return this.property;
}
public boolean isCancelled() {
return this.cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public AnimationPlayEvent(ActiveModel model, IAnimationProperty property) {
this.model = model;
this.property = property;
}
}
@@ -0,0 +1,138 @@
package com.ticxo.modelengine.api.events;
import com.ticxo.modelengine.api.entity.BaseEntity;
import com.ticxo.modelengine.api.model.ActiveModel;
import com.ticxo.modelengine.api.model.bone.ModelBone;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class BaseEntityInteractEvent extends AbstractEvent {
private static final HandlerList handlers = new HandlerList();
private final Player player;
private final BaseEntity<?> baseEntity;
private final ActiveModel model;
private final BaseEntityInteractEvent.Action action;
private final EquipmentSlot slot;
private final boolean isSecondary;
private final ItemStack item;
@Nullable
private final Vector clickedPosition;
@Nullable
private final ModelBone hitBone;
public BaseEntityInteractEvent(
Player player,
BaseEntity<?> baseEntity,
ActiveModel model,
BaseEntityInteractEvent.Action action,
EquipmentSlot slot,
boolean isSecondary,
ItemStack item,
@Nullable Vector clickedPosition
) {
this(player, baseEntity, model, action, slot, isSecondary, item, clickedPosition, null);
}
public BaseEntityInteractEvent(
Player player,
BaseEntity<?> baseEntity,
ActiveModel model,
BaseEntityInteractEvent.Action action,
EquipmentSlot slot,
boolean isSecondary,
ItemStack item,
@Nullable Vector clickedPosition,
@Nullable ModelBone hitBone
) {
this.player = player;
this.baseEntity = baseEntity;
this.model = model;
this.action = action;
this.slot = slot;
this.isSecondary = isSecondary;
this.item = item;
this.clickedPosition = clickedPosition;
this.hitBone = hitBone;
}
@NotNull
public static HandlerList getHandlerList() {
return handlers;
}
@NotNull
public HandlerList getHandlers() {
return handlers;
}
public String toString() {
return "BaseEntityInteractEvent(player="
+ this.getPlayer()
+ ", baseEntity="
+ this.getBaseEntity()
+ ", model="
+ this.getModel()
+ ", action="
+ this.getAction()
+ ", slot="
+ this.getSlot()
+ ", isSecondary="
+ this.isSecondary()
+ ", item="
+ this.getItem()
+ ", clickedPosition="
+ this.getClickedPosition()
+ ", hitBone="
+ this.getHitBone()
+ ")";
}
public Player getPlayer() {
return this.player;
}
public BaseEntity<?> getBaseEntity() {
return this.baseEntity;
}
public ActiveModel getModel() {
return this.model;
}
public BaseEntityInteractEvent.Action getAction() {
return this.action;
}
public EquipmentSlot getSlot() {
return this.slot;
}
public boolean isSecondary() {
return this.isSecondary;
}
public ItemStack getItem() {
return this.item;
}
@Nullable
public Vector getClickedPosition() {
return this.clickedPosition;
}
@Nullable
public ModelBone getHitBone() {
return this.hitBone;
}
public static enum Action {
ATTACK,
INTERACT,
INTERACT_ON;
}
}
@@ -0,0 +1,54 @@
package com.ticxo.modelengine.api.events;
import com.ticxo.modelengine.api.model.bone.ModelBone;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
import org.joml.Quaternionf;
import org.joml.Vector3f;
public class BoneTransformReadEvent extends AbstractEvent {
private static final HandlerList handlers = new HandlerList();
private final ModelBone modelBone;
private final Vector3f position;
private final Quaternionf leftRotation;
private final Vector3f scale;
private final Quaternionf rightRotation;
@NotNull
public static HandlerList getHandlerList() {
return handlers;
}
@NotNull
public HandlerList getHandlers() {
return handlers;
}
public ModelBone getModelBone() {
return this.modelBone;
}
public Vector3f getPosition() {
return this.position;
}
public Quaternionf getLeftRotation() {
return this.leftRotation;
}
public Vector3f getScale() {
return this.scale;
}
public Quaternionf getRightRotation() {
return this.rightRotation;
}
public BoneTransformReadEvent(ModelBone modelBone, Vector3f position, Quaternionf leftRotation, Vector3f scale, Quaternionf rightRotation) {
this.modelBone = modelBone;
this.position = position;
this.leftRotation = leftRotation;
this.scale = scale;
this.rightRotation = rightRotation;
}
}
@@ -0,0 +1,58 @@
package com.ticxo.modelengine.api.events;
import com.ticxo.modelengine.api.model.ActiveModel;
import com.ticxo.modelengine.api.model.bone.type.Mount;
import org.bukkit.entity.Entity;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class ModelDismountEvent extends AbstractEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final ActiveModel vehicle;
private final Entity passenger;
private final boolean isDriver;
private final Mount seat;
private boolean cancelled;
@NotNull
public static HandlerList getHandlerList() {
return handlers;
}
@NotNull
public HandlerList getHandlers() {
return handlers;
}
public ActiveModel getVehicle() {
return this.vehicle;
}
public Entity getPassenger() {
return this.passenger;
}
public boolean isDriver() {
return this.isDriver;
}
public Mount getSeat() {
return this.seat;
}
public boolean isCancelled() {
return this.cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public ModelDismountEvent(ActiveModel vehicle, Entity passenger, boolean isDriver, Mount seat) {
this.vehicle = vehicle;
this.passenger = passenger;
this.isDriver = isDriver;
this.seat = seat;
}
}
@@ -0,0 +1,58 @@
package com.ticxo.modelengine.api.events;
import com.ticxo.modelengine.api.model.ActiveModel;
import com.ticxo.modelengine.api.model.bone.type.Mount;
import org.bukkit.entity.Entity;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class ModelMountEvent extends AbstractEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final ActiveModel vehicle;
private final Entity passenger;
private final boolean isDriver;
private final Mount seat;
private boolean cancelled;
@NotNull
public static HandlerList getHandlerList() {
return handlers;
}
@NotNull
public HandlerList getHandlers() {
return handlers;
}
public ActiveModel getVehicle() {
return this.vehicle;
}
public Entity getPassenger() {
return this.passenger;
}
public boolean isDriver() {
return this.isDriver;
}
public Mount getSeat() {
return this.seat;
}
public boolean isCancelled() {
return this.cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public ModelMountEvent(ActiveModel vehicle, Entity passenger, boolean isDriver, Mount seat) {
this.vehicle = vehicle;
this.passenger = passenger;
this.isDriver = isDriver;
this.seat = seat;
}
}
@@ -0,0 +1,28 @@
package com.ticxo.modelengine.api.events;
import com.ticxo.modelengine.api.generator.ModelGenerator;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class ModelRegistrationEvent extends AbstractEvent {
private static final HandlerList handlers = new HandlerList();
private final ModelGenerator.Phase phase;
@NotNull
public static HandlerList getHandlerList() {
return handlers;
}
@NotNull
public HandlerList getHandlers() {
return handlers;
}
public ModelGenerator.Phase getPhase() {
return this.phase;
}
public ModelRegistrationEvent(ModelGenerator.Phase phase) {
this.phase = phase;
}
}
@@ -0,0 +1,35 @@
package com.ticxo.modelengine.api.events;
import com.ticxo.modelengine.api.model.ActiveModel;
import com.ticxo.modelengine.api.model.ModeledEntity;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class ModelSetupEvent extends AbstractEvent {
private static final HandlerList handlers = new HandlerList();
private final ModeledEntity modeledEntity;
private final ActiveModel activeModel;
@NotNull
public static HandlerList getHandlerList() {
return handlers;
}
@NotNull
public HandlerList getHandlers() {
return handlers;
}
public ModeledEntity getModeledEntity() {
return this.modeledEntity;
}
public ActiveModel getActiveModel() {
return this.activeModel;
}
public ModelSetupEvent(ModeledEntity modeledEntity, ActiveModel activeModel) {
this.modeledEntity = modeledEntity;
this.activeModel = activeModel;
}
}
@@ -0,0 +1,39 @@
package com.ticxo.modelengine.api.events;
import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchBehaviorParser;
import java.util.Set;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class RegisterBehaviorParserEvent extends AbstractEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final Set<BlockbenchBehaviorParser> behaviorParsers;
private boolean cancelled;
@NotNull
public static HandlerList getHandlerList() {
return handlers;
}
@NotNull
public HandlerList getHandlers() {
return handlers;
}
public void register(BlockbenchBehaviorParser parser) {
this.behaviorParsers.add(parser);
}
public boolean isCancelled() {
return this.cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public RegisterBehaviorParserEvent(Set<BlockbenchBehaviorParser> behaviorParsers) {
this.behaviorParsers = behaviorParsers;
}
}
@@ -0,0 +1,39 @@
package com.ticxo.modelengine.api.events;
import com.ticxo.modelengine.api.generator.parser.ModelParser;
import java.util.List;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class RegisterParserEvent extends AbstractEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final List<ModelParser> parsers;
private boolean cancelled;
@NotNull
public static HandlerList getHandlerList() {
return handlers;
}
@NotNull
public HandlerList getHandlers() {
return handlers;
}
public void register(ModelParser parser) {
this.parsers.add(parser);
}
public boolean isCancelled() {
return this.cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public RegisterParserEvent(List<ModelParser> parsers) {
this.parsers = parsers;
}
}
@@ -0,0 +1,45 @@
package com.ticxo.modelengine.api.events;
import com.ticxo.modelengine.api.model.ActiveModel;
import com.ticxo.modelengine.api.model.ModeledEntity;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class RemoveModelEvent extends AbstractEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final ModeledEntity target;
private final ActiveModel model;
private boolean cancelled;
@NotNull
public static HandlerList getHandlerList() {
return handlers;
}
@NotNull
public HandlerList getHandlers() {
return handlers;
}
public ModeledEntity getTarget() {
return this.target;
}
public ActiveModel getModel() {
return this.model;
}
public boolean isCancelled() {
return this.cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public RemoveModelEvent(ModeledEntity target, ActiveModel model) {
this.target = target;
this.model = model;
}
}
@@ -0,0 +1,89 @@
package com.ticxo.modelengine.api.generator;
import java.util.function.BiConsumer;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.MapMeta;
import org.bukkit.inventory.meta.PotionMeta;
public enum BaseItemEnum {
FILLED_MAP(BaseItemEnum.Cons.MAP_CONSUMER, Material.FILLED_MAP),
LEATHER_BOOTS(BaseItemEnum.Cons.LEATHER_CONSUMER, Material.LEATHER_BOOTS),
LEATHER_CHESTPLATE(BaseItemEnum.Cons.LEATHER_CONSUMER, Material.LEATHER_CHESTPLATE),
LEATHER_HORSE_ARMOR(BaseItemEnum.Cons.LEATHER_CONSUMER, Material.LEATHER_HORSE_ARMOR),
LEATHER_LEGGINGS(BaseItemEnum.Cons.LEATHER_CONSUMER, Material.LEATHER_LEGGINGS),
LINGERING_POTION(BaseItemEnum.Cons.POTION_CONSUMER, Material.LINGERING_POTION),
POTION(BaseItemEnum.Cons.POTION_CONSUMER, Material.POTION),
SPLASH_POTION(BaseItemEnum.Cons.POTION_CONSUMER, Material.SPLASH_POTION),
TIPPED_ARROW(BaseItemEnum.Cons.POTION_CONSUMER, Material.TIPPED_ARROW);
private final BiConsumer<ItemMeta, Color> metaConsumer;
private final Material material;
public static BaseItemEnum get(String value) {
try {
return valueOf(value);
} catch (IllegalArgumentException var2) {
return LEATHER_HORSE_ARMOR;
}
}
public static BaseItemEnum fromMaterial(Material material) {
return switch (material) {
case FILLED_MAP -> FILLED_MAP;
case LEATHER_BOOTS -> LEATHER_BOOTS;
case LEATHER_CHESTPLATE -> LEATHER_CHESTPLATE;
case LEATHER_HORSE_ARMOR -> LEATHER_HORSE_ARMOR;
case LEATHER_LEGGINGS -> LEATHER_LEGGINGS;
case LINGERING_POTION -> LINGERING_POTION;
case POTION -> POTION;
case SPLASH_POTION -> SPLASH_POTION;
case TIPPED_ARROW -> TIPPED_ARROW;
default -> null;
};
}
public void color(ItemMeta meta, Color color) {
this.metaConsumer.accept(meta, color);
}
public ItemStack create() {
return new ItemStack(this.material);
}
public ItemStack create(Color color, int data) {
ItemStack stack = this.create();
ItemMeta meta = stack.getItemMeta();
meta.setCustomModelData(data);
this.color(meta, color);
stack.setItemMeta(meta);
return stack;
}
private BaseItemEnum(BiConsumer<ItemMeta, Color> metaConsumer, Material material) {
this.metaConsumer = metaConsumer;
this.material = material;
}
public Material getMaterial() {
return this.material;
}
private static class Cons {
private static final BiConsumer<ItemMeta, Color> MAP_CONSUMER = (meta, color) -> {
MapMeta map = (MapMeta)meta;
map.setColor(color);
};
private static final BiConsumer<ItemMeta, Color> LEATHER_CONSUMER = (meta, color) -> {
LeatherArmorMeta leather = (LeatherArmorMeta)meta;
leather.setColor(color);
};
private static final BiConsumer<ItemMeta, Color> POTION_CONSUMER = (meta, color) -> {
PotionMeta potion = (PotionMeta)meta;
potion.setColor(color);
};
}
}
@@ -0,0 +1,29 @@
package com.ticxo.modelengine.api.generator;
public interface ModelGenerator {
default void importModels() {
this.importModels(false);
}
boolean isInitialized();
void importModels(boolean var1);
void generateAssets(boolean var1);
void zipResourcePack(boolean var1);
void updateConfig();
void queueTask(ModelGenerator.Phase var1, Runnable var2);
public static enum Phase {
PRE_IMPORT,
POST_IMPORT,
PRE_ASSETS,
POST_ASSETS,
PRE_ZIPPING,
POST_ZIPPING,
FINISHED;
}
}
@@ -0,0 +1,134 @@
package com.ticxo.modelengine.api.generator.assets;
import com.ticxo.modelengine.api.utils.data.ResourceLocation;
import java.util.ArrayList;
import java.util.List;
public class BlueprintTexture {
private int id;
private int frameWidth;
private int frameHeight;
private ResourceLocation path;
private BlueprintTexture.MCMeta mcMeta;
private String source;
public int getId() {
return this.id;
}
public int getFrameWidth() {
return this.frameWidth;
}
public int getFrameHeight() {
return this.frameHeight;
}
public ResourceLocation getPath() {
return this.path;
}
public BlueprintTexture.MCMeta getMcMeta() {
return this.mcMeta;
}
public String getSource() {
return this.source;
}
public void setId(int id) {
this.id = id;
}
public void setFrameWidth(int frameWidth) {
this.frameWidth = frameWidth;
}
public void setFrameHeight(int frameHeight) {
this.frameHeight = frameHeight;
}
public void setPath(ResourceLocation path) {
this.path = path;
}
public void setMcMeta(BlueprintTexture.MCMeta mcMeta) {
this.mcMeta = mcMeta;
}
public void setSource(String source) {
this.source = source;
}
public static class MCMeta {
private transient boolean mustGenerate;
private Boolean interpolate;
private Integer width;
private Integer height;
private Integer frametime;
private List<Object> frames;
public void addFrame(int frame) {
if (this.frames == null) {
this.frames = new ArrayList<>();
}
this.frames.add(frame);
}
public void addFrame(int index, int time) {
if (this.frames == null) {
this.frames = new ArrayList<>();
}
this.frames.add(new BlueprintTexture.MCMeta.Frame(index, time));
}
public boolean isMustGenerate() {
return this.mustGenerate;
}
public Boolean getInterpolate() {
return this.interpolate;
}
public Integer getWidth() {
return this.width;
}
public Integer getHeight() {
return this.height;
}
public Integer getFrametime() {
return this.frametime;
}
public List<Object> getFrames() {
return this.frames;
}
public void setMustGenerate(boolean mustGenerate) {
this.mustGenerate = mustGenerate;
}
public void setInterpolate(Boolean interpolate) {
this.interpolate = interpolate;
}
public void setWidth(Integer width) {
this.width = width;
}
public void setHeight(Integer height) {
this.height = height;
}
public void setFrametime(Integer frametime) {
this.frametime = frametime;
}
public record Frame(int index, int time) {
}
}
}
@@ -0,0 +1,113 @@
package com.ticxo.modelengine.api.generator.assets;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.NamespacedKey;
public abstract class ItemModel {
protected final String type;
public static ItemModel.Composite composite(ItemModel... models) {
ItemModel.Composite composite = new ItemModel.Composite();
composite.models.addAll(List.of(models));
return composite;
}
public ItemModel(String type) {
this.type = type;
}
public static class Composite extends ItemModel {
protected final List<ItemModel> models = new ArrayList<>();
public Composite() {
super("minecraft:composite");
}
public List<ItemModel> getModels() {
return this.models;
}
}
public static class Model extends ItemModel {
protected final String model;
protected final List<TintSource> tints = new ArrayList<>();
public Model(NamespacedKey model) {
super("minecraft:model");
this.model = model.asString();
this.tints.add(new TintSource.CustomModelData(0));
}
public Model(String model) {
super("minecraft:model");
this.model = model;
}
public String getModel() {
return this.model;
}
public List<TintSource> getTints() {
return this.tints;
}
}
public static class RangeDispatch extends ItemModel {
protected final List<ItemModel.RangeDispatch.Entry> entries = new ArrayList<>();
protected ItemModel fallback;
protected final String property = "minecraft:custom_model_data";
public RangeDispatch() {
super("minecraft:range_dispatch");
}
public List<ItemModel.RangeDispatch.Entry> getEntries() {
return this.entries;
}
public ItemModel getFallback() {
return this.fallback;
}
public String getProperty() {
return this.property;
}
public void setFallback(ItemModel fallback) {
this.fallback = fallback;
}
public record Entry(ItemModel model, int threshold) {
}
}
public static class Select extends ItemModel {
protected final List<ItemModel.Select.Case> cases = new ArrayList<>();
protected ItemModel fallback;
protected final String property = "minecraft:custom_model_data";
public Select() {
super("minecraft:select");
}
public List<ItemModel.Select.Case> getCases() {
return this.cases;
}
public ItemModel getFallback() {
return this.fallback;
}
public String getProperty() {
return this.property;
}
public void setFallback(ItemModel fallback) {
this.fallback = fallback;
}
public record Case(ItemModel model, String when) {
}
}
}
@@ -0,0 +1,139 @@
package com.ticxo.modelengine.api.generator.assets;
import com.ticxo.modelengine.api.ModelEngineAPI;
import com.ticxo.modelengine.api.generator.BaseItemEnum;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import org.bukkit.Color;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Nullable;
public class ItemModelData {
private final ItemModelData.MultiModels multiModels = new ItemModelData.MultiModels();
private ItemModelData.SingleComposite singleComposite;
private String variant;
private boolean isTranslucent;
public static ItemModelData.Context.ContextBuilder context() {
return ItemModelData.Context.builder();
}
public Collection<ItemStack> createItemStack() {
return this.createItemStack(ItemModelData.Context.builder().color(Color.WHITE).build());
}
public Set<ItemStack> createItemStack(@Nullable ItemModelData.Context context) {
return ModelEngineAPI.getNMSHandler().createStack(this, context);
}
public ItemModelData.MultiModels getMultiModels() {
return this.multiModels;
}
public ItemModelData.SingleComposite getSingleComposite() {
return this.singleComposite;
}
public String getVariant() {
return this.variant;
}
public boolean isTranslucent() {
return this.isTranslucent;
}
public void setSingleComposite(ItemModelData.SingleComposite singleComposite) {
this.singleComposite = singleComposite;
}
public void setVariant(String variant) {
this.variant = variant;
}
public void setTranslucent(boolean isTranslucent) {
this.isTranslucent = isTranslucent;
}
public record Context(Color color) {
public static ItemModelData.Context.ContextBuilder builder() {
return new ItemModelData.Context.ContextBuilder();
}
public static class ContextBuilder {
private Color color;
ContextBuilder() {
}
public ItemModelData.Context.ContextBuilder color(Color color) {
this.color = color;
return this;
}
public ItemModelData.Context build() {
return new ItemModelData.Context(this.color);
}
@Override
public String toString() {
return "ItemModelData.Context.ContextBuilder(color=" + this.color + ")";
}
}
}
public static class MultiModels {
private final Map<String, ItemModelData.SubModel> map = new Object2ObjectOpenHashMap();
public void addSubModel(ItemModelData.SubModel model) {
this.map.put(model.id, model);
}
public ItemModelData.SubModel getSubModel(String id) {
return this.map.get(id);
}
public Collection<ItemModelData.SubModel> getSubModels() {
return this.map.values();
}
public Set<String> getKeys() {
return this.map.keySet();
}
}
public record SingleComposite(NamespacedKey model) {
}
public static class SubModel {
private final String id;
private BaseItemEnum item;
private int data;
public SubModel(String id) {
this.id = id;
}
public String getId() {
return this.id;
}
public BaseItemEnum getItem() {
return this.item;
}
public int getData() {
return this.data;
}
public void setItem(BaseItemEnum item) {
this.item = item;
}
public void setData(int data) {
this.data = data;
}
}
}
@@ -0,0 +1,61 @@
package com.ticxo.modelengine.api.generator.assets;
import com.ticxo.modelengine.api.utils.math.TMath;
import java.util.Locale;
import java.util.function.Consumer;
import java.util.function.Predicate;
public enum JavaDisplay {
THIRDPERSON_RIGHTHAND,
THIRDPERSON_LEFTHAND,
FIRSTPERSON_RIGHTHAND,
FIRSTPERSON_LEFTHAND,
GROUND,
GUI,
HEAD,
FIXED;
@Override
public String toString() {
return super.toString().toLowerCase(Locale.ENGLISH);
}
public static enum Transform {
ROTATION(vals -> {
vals[0] %= 360.0F;
vals[1] %= 360.0F;
vals[2] %= 360.0F;
}, vals -> TMath.isSimilar(vals[0], 0.0F) && TMath.isSimilar(vals[1], 0.0F) && TMath.isSimilar(vals[2], 0.0F)),
TRANSLATION(vals -> {
vals[0] = TMath.clamp(vals[0], -80.0F, 80.0F);
vals[1] = TMath.clamp(vals[1], -80.0F, 80.0F);
vals[2] = TMath.clamp(vals[2], -80.0F, 80.0F);
}, vals -> TMath.isSimilar(vals[0], 0.0F) && TMath.isSimilar(vals[1], 0.0F) && TMath.isSimilar(vals[2], 0.0F)),
SCALE(vals -> {
vals[0] = TMath.clamp(vals[0], 0.0F, 4.0F);
vals[1] = TMath.clamp(vals[1], 0.0F, 4.0F);
vals[2] = TMath.clamp(vals[2], 0.0F, 4.0F);
}, vals -> TMath.isSimilar(vals[0], 1.0F) && TMath.isSimilar(vals[1], 1.0F) && TMath.isSimilar(vals[2], 1.0F));
private final Consumer<float[]> sanitizer;
private final Predicate<float[]> isDirty;
public void sanitize(float[] val) {
this.sanitizer.accept(val);
}
public boolean isDefault(float[] val) {
return this.isDirty.test(val);
}
@Override
public String toString() {
return super.toString().toLowerCase(Locale.ENGLISH);
}
private Transform(Consumer<float[]> sanitizer, Predicate<float[]> isDirty) {
this.sanitizer = sanitizer;
this.isDirty = isDirty;
}
}
}
@@ -0,0 +1,284 @@
package com.ticxo.modelengine.api.generator.assets;
import com.ticxo.modelengine.api.utils.math.TMath;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JavaItemModel {
private static final float DIST_DIVIDER = 0.041666668F;
private final Map<String, String> textures = new HashMap<>();
private final List<JavaItemModel.JavaElement> elements = new ArrayList<>();
private transient String name;
private transient float maxDistToOrigin = 0.0F;
private Map<String, Map<String, float[]>> display = new HashMap<>();
public JavaItemModel() {
this.setDisplay(JavaDisplay.GUI, JavaDisplay.Transform.ROTATION, 30.0F, 225.0F, 0.0F);
}
public void setDisplay(JavaDisplay display, JavaDisplay.Transform transform, float x, float y, float z) {
float[] array = new float[]{x, y, z};
if (!transform.isDefault(array)) {
transform.sanitize(array);
this.display.computeIfAbsent(display.toString(), s -> new HashMap<>()).put(transform.toString(), array);
}
}
public void addElement(JavaItemModel.JavaElement element) {
this.elements.add(element);
for (int i = 0; i < 3; i++) {
this.maxDistToOrigin = Math.max(Math.max(Math.abs(element.from[i] - 8.0F), Math.abs(element.to[i] - 8.0F)), this.maxDistToOrigin);
}
}
public int scaleToFit() {
if (this.maxDistToOrigin <= 24.0F) {
return 1;
} else {
int size = (int)Math.ceil(this.maxDistToOrigin * 0.041666668F);
float scale = 1.0F / size;
for (JavaItemModel.JavaElement element : this.elements) {
float[] origin = element.getRotation() == null ? null : element.getRotation().getOrigin();
for (int i = 0; i < 3; i++) {
element.from[i] = TMath.clamp((element.from[i] - 8.0F) * scale + 8.0F, -16.0F, 32.0F);
element.to[i] = TMath.clamp((element.to[i] - 8.0F) * scale + 8.0F, -16.0F, 32.0F);
if (origin != null) {
origin[i] = (origin[i] - 8.0F) * scale + 8.0F;
}
}
}
return size;
}
}
public void finalizeModel() {
}
public Map<String, String> getTextures() {
return this.textures;
}
public List<JavaItemModel.JavaElement> getElements() {
return this.elements;
}
public String getName() {
return this.name;
}
public float getMaxDistToOrigin() {
return this.maxDistToOrigin;
}
public Map<String, Map<String, float[]>> getDisplay() {
return this.display;
}
public void setName(String name) {
this.name = name;
}
public void setMaxDistToOrigin(float maxDistToOrigin) {
this.maxDistToOrigin = maxDistToOrigin;
}
public void setDisplay(Map<String, Map<String, float[]>> display) {
this.display = display;
}
public static class JavaElement {
private final float[] from = new float[3];
private final float[] to = new float[3];
private final Map<String, JavaItemModel.JavaElement.Face> faces = new HashMap<>();
private JavaItemModel.JavaElement.JavaRotation rotation;
public void from(float[] origin, float[] globalFrom, float inflate) {
this.from[0] = globalFrom[0] - origin[0] + 8.0F - inflate;
this.from[1] = globalFrom[1] - origin[1] + 8.0F - inflate;
this.from[2] = globalFrom[2] - origin[2] + 8.0F - inflate;
}
public void from(float[] origin, float inflate) {
this.from[0] = origin[0] + 8.0F - inflate;
this.from[1] = origin[1] + 8.0F - inflate;
this.from[2] = origin[2] + 8.0F - inflate;
}
public void to(float[] origin, float[] globalTo, float inflate) {
this.to[0] = globalTo[0] - origin[0] + 8.0F + inflate;
this.to[1] = globalTo[1] - origin[1] + 8.0F + inflate;
this.to[2] = globalTo[2] - origin[2] + 8.0F + inflate;
}
public void to(float[] origin, float inflate) {
this.to[0] = origin[0] + 8.0F + inflate;
this.to[1] = origin[1] + 8.0F + inflate;
this.to[2] = origin[2] + 8.0F + inflate;
}
public float[] getFrom() {
return this.from;
}
public float[] getTo() {
return this.to;
}
public Map<String, JavaItemModel.JavaElement.Face> getFaces() {
return this.faces;
}
public JavaItemModel.JavaElement.JavaRotation getRotation() {
return this.rotation;
}
public void setRotation(JavaItemModel.JavaElement.JavaRotation rotation) {
this.rotation = rotation;
}
public static class Face {
private final float[] uv = new float[4];
private final int tintindex = 0;
private int rotation;
private String texture = "";
public void uv(int width, int height, float[] uv) {
float factorU = 16.0F / width;
float factorV = 16.0F / height;
this.uv[0] = TMath.clamp(uv[0] * factorU, 0.0F, 16.0F);
this.uv[1] = TMath.clamp(uv[1] * factorV, 0.0F, 16.0F);
this.uv[2] = TMath.clamp(uv[2] * factorU, 0.0F, 16.0F);
this.uv[3] = TMath.clamp(uv[3] * factorV, 0.0F, 16.0F);
}
public void setRotation(Integer rotation) {
if (rotation != null) {
this.rotation = rotation;
}
}
public float[] getUv() {
return this.uv;
}
public int getTintindex() {
return 0;
}
public int getRotation() {
return this.rotation;
}
public String getTexture() {
return this.texture;
}
public void setTexture(String texture) {
this.texture = texture;
}
}
interface JavaRotation {
float[] getOrigin();
}
public static class RotationFree implements JavaItemModel.JavaElement.JavaRotation {
private final float[] origin = new float[]{8.0F, 8.0F, 8.0F};
private float x;
private float y;
private float z;
public void origin(float[] origin, float[] globalOrigin) {
this.origin[0] = globalOrigin[0] - origin[0] + 8.0F;
this.origin[1] = globalOrigin[1] - origin[1] + 8.0F;
this.origin[2] = globalOrigin[2] - origin[2] + 8.0F;
}
public void origin(float[] origin) {
this.origin[0] = origin[0] + 8.0F;
this.origin[1] = origin[1] + 8.0F;
this.origin[2] = origin[2] + 8.0F;
}
public void rotation(float[] rotation) {
this.x = rotation[0];
this.y = rotation[1];
this.z = rotation[2];
}
@Override
public float[] getOrigin() {
return this.origin;
}
public float getX() {
return this.x;
}
public float getY() {
return this.y;
}
public float getZ() {
return this.z;
}
public void setX(float x) {
this.x = x;
}
public void setY(float y) {
this.y = y;
}
public void setZ(float z) {
this.z = z;
}
}
public static class RotationSingle implements JavaItemModel.JavaElement.JavaRotation {
private final float[] origin = new float[]{8.0F, 8.0F, 8.0F};
private float angle;
private String axis = "x";
public void origin(float[] origin, float[] globalOrigin) {
this.origin[0] = globalOrigin[0] - origin[0] + 8.0F;
this.origin[1] = globalOrigin[1] - origin[1] + 8.0F;
this.origin[2] = globalOrigin[2] - origin[2] + 8.0F;
}
public void origin(float[] origin) {
this.origin[0] = origin[0] + 8.0F;
this.origin[1] = origin[1] + 8.0F;
this.origin[2] = origin[2] + 8.0F;
}
@Override
public float[] getOrigin() {
return this.origin;
}
public float getAngle() {
return this.angle;
}
public String getAxis() {
return this.axis;
}
public void setAngle(float angle) {
this.angle = angle;
}
public void setAxis(String axis) {
this.axis = axis;
}
}
}
}
@@ -0,0 +1,29 @@
package com.ticxo.modelengine.api.generator.assets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ModelAssets {
private final List<BlueprintTexture> textures = new ArrayList<>();
private final Map<String, Collection<JavaItemModel>> models = new HashMap<>();
private String name;
public List<BlueprintTexture> getTextures() {
return this.textures;
}
public Map<String, Collection<JavaItemModel>> getModels() {
return this.models;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,73 @@
package com.ticxo.modelengine.api.generator.assets;
import com.google.gson.annotations.SerializedName;
public abstract class TintSource {
protected final String type;
public TintSource(String type) {
this.type = type;
}
public static class Constant extends TintSource {
protected final int value;
public Constant(int value) {
super("minecraft:constant");
this.value = value;
}
}
public static class CustomModelData extends TintSource {
protected final int index;
@SerializedName("default")
protected final int def = 16777215;
public CustomModelData(int index) {
super("minecraft:custom_model_data");
this.index = index;
}
}
public static class Dye extends TintSource {
@SerializedName("default")
protected final int def;
public Dye() {
this(-6265536);
}
public Dye(int def) {
super("minecraft:dye");
this.def = def;
}
}
public static class MapColor extends TintSource {
@SerializedName("default")
protected final int def;
public MapColor() {
this(4603950);
}
public MapColor(int def) {
super("minecraft:map_color");
this.def = def;
}
}
public static class Potion extends TintSource {
@SerializedName("default")
protected final int def;
public Potion() {
this(-13083194);
}
public Potion(int def) {
super("minecraft:potion");
this.def = def;
}
}
}
@@ -0,0 +1,207 @@
package com.ticxo.modelengine.api.generator.blueprint;
import com.ticxo.modelengine.api.generator.BaseItemEnum;
import com.ticxo.modelengine.api.generator.assets.ItemModelData;
import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import org.joml.Quaternionf;
import org.joml.Vector3f;
public class BlueprintBone {
private final Map<String, BlueprintBone> children = new LinkedHashMap<>();
private final Map<String, Map<String, Object>> behaviors = new LinkedHashMap<>();
private final transient Map<BoneBehaviorType<?>, BoneBehaviorType.CachedProvider<?>> cachedBehaviorProvider = new LinkedHashMap<>();
private String name;
private UUID uuid;
private ModelBlueprint modelBlueprint;
private boolean isRenderer;
private int scale = 1;
@Deprecated
private BaseItemEnum baseItem;
@Deprecated
private int dataId;
private final ItemModelData modelData = new ItemModelData();
private Vector3f localPosition;
private Vector3f localRotation;
private Quaternionf localQuaternion = new Quaternionf();
private Vector3f globalPosition;
private Vector3f rotatedGlobalPosition;
private Vector3f globalRotation;
private Quaternionf globalQuaternion = new Quaternionf();
private Quaternionf invGlobalQuaternion = new Quaternionf();
private BlueprintBone parent;
private Vector3f modelScale = new Vector3f(1.0F);
private BlueprintBone dupeTarget;
private boolean renderByDefault = true;
public void setGlobalQuaternion(Quaternionf globalQuaternion) {
this.globalQuaternion.set(globalQuaternion);
this.invGlobalQuaternion.set(globalQuaternion.invert());
}
public Map<String, BlueprintBone> getChildren() {
return this.children;
}
public Map<String, Map<String, Object>> getBehaviors() {
return this.behaviors;
}
public Map<BoneBehaviorType<?>, BoneBehaviorType.CachedProvider<?>> getCachedBehaviorProvider() {
return this.cachedBehaviorProvider;
}
public String getName() {
return this.name;
}
public UUID getUuid() {
return this.uuid;
}
public ModelBlueprint getModelBlueprint() {
return this.modelBlueprint;
}
public boolean isRenderer() {
return this.isRenderer;
}
public int getScale() {
return this.scale;
}
@Deprecated
public BaseItemEnum getBaseItem() {
return this.baseItem;
}
@Deprecated
public int getDataId() {
return this.dataId;
}
public ItemModelData getModelData() {
return this.modelData;
}
public Vector3f getLocalPosition() {
return this.localPosition;
}
public Vector3f getLocalRotation() {
return this.localRotation;
}
public Quaternionf getLocalQuaternion() {
return this.localQuaternion;
}
public Vector3f getGlobalPosition() {
return this.globalPosition;
}
public Vector3f getRotatedGlobalPosition() {
return this.rotatedGlobalPosition;
}
public Vector3f getGlobalRotation() {
return this.globalRotation;
}
public Quaternionf getGlobalQuaternion() {
return this.globalQuaternion;
}
public Quaternionf getInvGlobalQuaternion() {
return this.invGlobalQuaternion;
}
public BlueprintBone getParent() {
return this.parent;
}
public Vector3f getModelScale() {
return this.modelScale;
}
public BlueprintBone getDupeTarget() {
return this.dupeTarget;
}
public boolean isRenderByDefault() {
return this.renderByDefault;
}
public void setName(String name) {
this.name = name;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public void setModelBlueprint(ModelBlueprint modelBlueprint) {
this.modelBlueprint = modelBlueprint;
}
public void setRenderer(boolean isRenderer) {
this.isRenderer = isRenderer;
}
public void setScale(int scale) {
this.scale = scale;
}
@Deprecated
public void setBaseItem(BaseItemEnum baseItem) {
this.baseItem = baseItem;
}
@Deprecated
public void setDataId(int dataId) {
this.dataId = dataId;
}
public void setLocalPosition(Vector3f localPosition) {
this.localPosition = localPosition;
}
public void setLocalRotation(Vector3f localRotation) {
this.localRotation = localRotation;
}
public void setLocalQuaternion(Quaternionf localQuaternion) {
this.localQuaternion = localQuaternion;
}
public void setGlobalPosition(Vector3f globalPosition) {
this.globalPosition = globalPosition;
}
public void setRotatedGlobalPosition(Vector3f rotatedGlobalPosition) {
this.rotatedGlobalPosition = rotatedGlobalPosition;
}
public void setGlobalRotation(Vector3f globalRotation) {
this.globalRotation = globalRotation;
}
public void setParent(BlueprintBone parent) {
this.parent = parent;
}
public void setModelScale(Vector3f modelScale) {
this.modelScale = modelScale;
}
public void setDupeTarget(BlueprintBone dupeTarget) {
this.dupeTarget = dupeTarget;
}
public void setRenderByDefault(boolean renderByDefault) {
this.renderByDefault = renderByDefault;
}
}
@@ -0,0 +1,207 @@
package com.ticxo.modelengine.api.generator.blueprint;
import com.google.common.collect.ImmutableMap;
import com.ticxo.modelengine.api.ModelEngineAPI;
import com.ticxo.modelengine.api.animation.BlueprintAnimation;
import com.ticxo.modelengine.api.entity.Hitbox;
import com.ticxo.modelengine.api.error.ErrorCollector;
import com.ticxo.modelengine.api.error.ErrorIncompatibleBone;
import com.ticxo.modelengine.api.error.ErrorUnknownBoneBehavior;
import com.ticxo.modelengine.api.error.WarnIncompatibleBoneBehavior;
import com.ticxo.modelengine.api.error.WarningDuplicateBoneName;
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.render.IRenderType;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class ModelBlueprint {
private final Map<String, BlueprintBone> bones = new LinkedHashMap<>();
private final Map<String, BlueprintAnimation> animations = new LinkedHashMap<>();
private final transient Set<String> animationDescendingPriority = new LinkedHashSet<>();
private final Map<String, String> animationsPlaceholders = new LinkedHashMap<>();
private String name;
private Hitbox mainHitbox = new Hitbox(0.6, 1.8, 0.6, 1.44);
private float shadowRadius = 0.0F;
private transient Map<String, BlueprintBone> flatMap;
private transient boolean flatViewConstructed;
private transient boolean descendingAnimationConstructed;
private transient boolean boneBehaviorCached;
public void finalizeModel(ErrorCollector collector) {
this.constructFlatBoneMap(collector);
this.constructDescendingAnimation(collector);
this.cacheBoneBehaviors(collector);
}
public void constructFlatBoneMap(ErrorCollector collector) {
if (!this.flatViewConstructed) {
this.flatViewConstructed = true;
Map<String, BlueprintBone> tempMap = new LinkedHashMap<>();
Set<BlueprintBone> bones = new LinkedHashSet<>(this.bones.values());
Set<BlueprintBone> buffer = new LinkedHashSet<>();
while (!bones.isEmpty()) {
for (BlueprintBone bone : bones) {
buffer.addAll(bone.getChildren().values());
if (tempMap.containsKey(bone.getName())) {
new WarningDuplicateBoneName(bone.getName(), bone.getUuid()).log(collector);
bone.setName(bone.getUuid().toString());
}
tempMap.put(bone.getName(), bone);
}
bones.clear();
bones.addAll(buffer);
buffer.clear();
}
this.flatMap = ImmutableMap.copyOf(tempMap);
}
}
public void constructDescendingAnimation(ErrorCollector collector) {
if (!this.descendingAnimationConstructed) {
this.descendingAnimationConstructed = true;
ArrayList<String> list = new ArrayList<>();
this.animations.keySet().forEach(s -> list.add(0, s));
this.animationDescendingPriority.addAll(list);
}
}
public void cacheBoneBehaviors(ErrorCollector collector) {
if (!this.boneBehaviorCached) {
this.boneBehaviorCached = true;
assert this.flatMap != null : "Bone flat view map is null.";
BoneBehaviorRegistry behaviorRegistry = ModelEngineAPI.getAPI().getBoneBehaviorRegistry();
for (Entry<String, BlueprintBone> boneEntry : this.flatMap.entrySet()) {
String name = boneEntry.getKey();
BlueprintBone bone = boneEntry.getValue();
for (Entry<String, Map<String, Object>> entry : bone.getBehaviors().entrySet()) {
String bbId = entry.getKey();
BoneBehaviorType<?> behaviorType = behaviorRegistry.getById(bbId);
if (behaviorType == null) {
new ErrorUnknownBoneBehavior(name, bbId).log(collector);
} else if (!this.canBoneUseBehavior(bone, behaviorType)) {
new ErrorIncompatibleBone(bone.isRenderer(), name, bbId).log(collector);
} else {
if (!behaviorType.test(bone.getCachedBehaviorProvider().keySet())) {
new WarnIncompatibleBoneBehavior(name, bbId).log(collector);
}
behaviorType.assignCachedProvider(bone, entry.getValue());
}
}
for (String id : behaviorRegistry.getIds()) {
BoneBehaviorType<?> type = behaviorRegistry.getById(id);
if (type != null) {
type.assignForcedCachedProvider(bone);
}
}
}
}
}
public BlueprintAnimation getAnimationOrRef(String animation) {
if (animation.startsWith("ref[") && animation.endsWith("]")) {
animation = animation.substring(4, animation.length() - 1);
String[] split = animation.split("\\.", 2);
if (split.length >= 2) {
ModelBlueprint blueprint = ModelEngineAPI.getBlueprint(split[0]);
if (blueprint != null) {
return blueprint.animations.get(split[1]);
}
}
}
return this.animations.get(animation);
}
private boolean canBoneUseBehavior(BlueprintBone bone, BoneBehaviorType<?> type) {
IRenderType renderType = type.getRenderType();
if (renderType == DefaultRenderType.ANY) {
return true;
} else {
return renderType == DefaultRenderType.MODEL ? bone.isRenderer() : !bone.isRenderer();
}
}
public Map<String, BlueprintBone> getBones() {
return this.bones;
}
public Map<String, BlueprintAnimation> getAnimations() {
return this.animations;
}
public Set<String> getAnimationDescendingPriority() {
return this.animationDescendingPriority;
}
public Map<String, String> getAnimationsPlaceholders() {
return this.animationsPlaceholders;
}
public String getName() {
return this.name;
}
public Hitbox getMainHitbox() {
return this.mainHitbox;
}
public float getShadowRadius() {
return this.shadowRadius;
}
public Map<String, BlueprintBone> getFlatMap() {
return this.flatMap;
}
public boolean isFlatViewConstructed() {
return this.flatViewConstructed;
}
public boolean isDescendingAnimationConstructed() {
return this.descendingAnimationConstructed;
}
public boolean isBoneBehaviorCached() {
return this.boneBehaviorCached;
}
public void setName(String name) {
this.name = name;
}
public void setMainHitbox(Hitbox mainHitbox) {
this.mainHitbox = mainHitbox;
}
public void setShadowRadius(float shadowRadius) {
this.shadowRadius = shadowRadius;
}
public void setFlatViewConstructed(boolean flatViewConstructed) {
this.flatViewConstructed = flatViewConstructed;
}
public void setDescendingAnimationConstructed(boolean descendingAnimationConstructed) {
this.descendingAnimationConstructed = descendingAnimationConstructed;
}
public void setBoneBehaviorCached(boolean boneBehaviorCached) {
this.boneBehaviorCached = boneBehaviorCached;
}
}
@@ -0,0 +1,13 @@
package com.ticxo.modelengine.api.generator.parser;
import com.ticxo.modelengine.api.error.ErrorCollector;
import com.ticxo.modelengine.api.generator.assets.ModelAssets;
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
import it.unimi.dsi.fastutil.Pair;
import java.io.File;
public interface ModelParser {
boolean validateFile(File var1);
Pair<ModelBlueprint, ModelAssets> generate(File var1, ErrorCollector var2) throws Exception;
}
@@ -0,0 +1,11 @@
package com.ticxo.modelengine.api.generator.parser.blockbench;
import com.ticxo.modelengine.api.error.ErrorCollector;
import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone;
import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint;
public interface BlockbenchBehaviorParser {
void processModel(ErrorCollector var1, BlockbenchModel var2, ModelBlueprint var3);
void processBone(ErrorCollector var1, BlockbenchModel var2, BlockbenchModel.Group var3, BlueprintBone var4);
}
@@ -0,0 +1,24 @@
package com.ticxo.modelengine.api.generator.parser.blockbench;
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.utils.math.TMath;
import java.lang.reflect.Type;
public class BlockbenchDeserializer implements JsonDeserializer<BlockbenchModel> {
public BlockbenchModel deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject root = jsonElement.getAsJsonObject();
String version = root.getAsJsonObject("meta").get("format_version").getAsString();
String[] versionSplit = version.split("\\.");
int major = TMath.tryParse(versionSplit[0], 0);
int minor = TMath.tryParse(versionSplit[1], 0);
return switch (major) {
case 5 -> v5_0_Deserializer.deserialize(root);
default -> LegacyDeserializer.deserialize(root);
};
}
}
@@ -0,0 +1,591 @@
package com.ticxo.modelengine.api.generator.parser.blockbench;
import com.ticxo.modelengine.api.utils.math.TMath;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class BlockbenchModel {
protected BlockbenchModel.Resolution resolution;
protected Map<UUID, BlockbenchModel.Element> elements;
protected Map<UUID, BlockbenchModel.Group> outliner;
protected Map<Integer, BlockbenchModel.Texture> textures;
protected Map<String, BlockbenchModel.Animation> animations;
protected final transient Map<String, BlockbenchModel.Group> flatOutlinerByName = new HashMap<>();
protected final transient Map<UUID, BlockbenchModel.Group> flatOutlinerByUUID = new HashMap<>();
protected String animation_variable_placeholders;
public BlockbenchModel preprocess() {
LinkedList<BlockbenchModel.Group> queue = new LinkedList<>(this.outliner.values());
while (!queue.isEmpty()) {
BlockbenchModel.Group group = queue.poll();
this.flatOutlinerByName.put(group.name, group);
this.flatOutlinerByUUID.put(group.uuid, group);
queue.addAll(group.getChildGroup().values());
}
return this;
}
public BlockbenchModel.Group getGroup(@NotNull String group) {
return this.flatOutlinerByName.get(group);
}
public BlockbenchModel.Group getGroup(@NotNull UUID group) {
return this.flatOutlinerByUUID.get(group);
}
public BlockbenchModel.Group removeGroup(@NotNull String group) {
return this.getGroup(group);
}
public BlockbenchModel.Group removeGroup(@NotNull UUID group) {
return this.getGroup(group);
}
public BlockbenchModel.Group removeGroup(@Nullable BlockbenchModel.Group group) {
if (group == null) {
return null;
} else {
this.flatOutlinerByName.remove(group.name);
this.flatOutlinerByUUID.remove(group.uuid);
if (group.parentGroup != null) {
this.flatOutlinerByUUID.get(group.parentGroup).childGroup.remove(group.uuid);
} else {
this.outliner.remove(group.uuid);
}
return group;
}
}
public BlockbenchModel(
BlockbenchModel.Resolution resolution,
Map<UUID, BlockbenchModel.Element> elements,
Map<UUID, BlockbenchModel.Group> outliner,
Map<Integer, BlockbenchModel.Texture> textures,
Map<String, BlockbenchModel.Animation> animations,
String animation_variable_placeholders
) {
this.resolution = resolution;
this.elements = elements;
this.outliner = outliner;
this.textures = textures;
this.animations = animations;
this.animation_variable_placeholders = animation_variable_placeholders;
}
public BlockbenchModel.Resolution getResolution() {
return this.resolution;
}
public Map<UUID, BlockbenchModel.Element> getElements() {
return this.elements;
}
public Map<UUID, BlockbenchModel.Group> getOutliner() {
return this.outliner;
}
public Map<Integer, BlockbenchModel.Texture> getTextures() {
return this.textures;
}
public Map<String, BlockbenchModel.Animation> getAnimations() {
return this.animations;
}
public Map<String, BlockbenchModel.Group> getFlatOutlinerByName() {
return this.flatOutlinerByName;
}
public Map<UUID, BlockbenchModel.Group> getFlatOutlinerByUUID() {
return this.flatOutlinerByUUID;
}
public String getAnimation_variable_placeholders() {
return this.animation_variable_placeholders;
}
public interface AnimatableElement {
String getName();
UUID getUuid();
Float[] getOrigin();
Float[] getPosition();
@Nullable
Float[] getRotation();
}
public static class Animation {
protected UUID uuid;
protected String name;
protected String loop;
protected Boolean override;
protected Float length;
protected BlockbenchModel.Animator effects;
protected Map<UUID, BlockbenchModel.Animator> animators = new HashMap<>();
protected Map<String, BlockbenchModel.Animator> unknown_animators;
public UUID getUuid() {
return this.uuid;
}
public String getName() {
return this.name;
}
public String getLoop() {
return this.loop;
}
public Boolean getOverride() {
return this.override;
}
public Float getLength() {
return this.length;
}
public BlockbenchModel.Animator getEffects() {
return this.effects;
}
public Map<UUID, BlockbenchModel.Animator> getAnimators() {
return this.animators;
}
public Map<String, BlockbenchModel.Animator> getUnknown_animators() {
return this.unknown_animators;
}
}
public static class Animator {
protected String name;
@Nullable
protected UUID uuid;
protected Boolean rotation_global;
protected Map<String, Map<Float, BlockbenchModel.Keyframe>> channels = new HashMap<>();
public String getName() {
return this.name;
}
@Nullable
public UUID getUuid() {
return this.uuid;
}
public Boolean getRotation_global() {
return this.rotation_global;
}
public Map<String, Map<Float, BlockbenchModel.Keyframe>> getChannels() {
return this.channels;
}
}
public static class Camera extends BlockbenchModel.Element implements BlockbenchModel.AnimatableElement {
protected Float[] position;
protected Float[] rotation;
@Override
public Float[] getOrigin() {
return this.position;
}
@Override
public Float[] getPosition() {
return this.position;
}
@Override
public Float[] getRotation() {
return this.rotation;
}
}
public static class Cube extends BlockbenchModel.Element {
protected String render_order;
protected Float[] from;
protected Float[] to;
protected Float inflate = 0.0F;
protected Float[] rotation;
protected Float[] origin;
protected Map<String, BlockbenchModel.Face> faces;
public float width() {
return Math.abs(this.to[0] - this.from[0] + this.inflate * 2.0F);
}
public float height() {
return Math.abs(this.to[1] - this.from[1] + this.inflate * 2.0F);
}
public float depth() {
return Math.abs(this.to[2] - this.from[2] + this.inflate * 2.0F);
}
public float centerX() {
return TMath.lerp(this.from[0], this.to[0], 0.5F);
}
public float centerY() {
return TMath.lerp(this.from[1], this.to[1], 0.5F);
}
public float centerZ() {
return TMath.lerp(this.from[2], this.to[2], 0.5F);
}
public float minX() {
return Math.min(this.from[0], this.to[0]);
}
public float minY() {
return Math.min(this.from[1], this.to[1]);
}
public float minZ() {
return Math.min(this.from[2], this.to[2]);
}
public float maxX() {
return Math.max(this.from[0], this.to[0]);
}
public float maxY() {
return Math.max(this.from[1], this.to[1]);
}
public float maxZ() {
return Math.max(this.from[2], this.to[2]);
}
public boolean isTranslucent() {
return "in_front".equals(this.render_order);
}
public String getRender_order() {
return this.render_order;
}
public Float[] getFrom() {
return this.from;
}
public Float[] getTo() {
return this.to;
}
public Float getInflate() {
return this.inflate;
}
public Float[] getRotation() {
return this.rotation;
}
public Float[] getOrigin() {
return this.origin;
}
public Map<String, BlockbenchModel.Face> getFaces() {
return this.faces;
}
}
public static class Element {
protected String name;
protected UUID uuid;
protected String type;
public Element() {
}
public Element(String name, UUID uuid, String type) {
this.name = name;
this.uuid = uuid;
this.type = type;
}
public String getName() {
return this.name;
}
public UUID getUuid() {
return this.uuid;
}
public String getType() {
return this.type;
}
}
public static class Face {
protected Float[] uv;
protected Integer rotation;
protected Integer texture;
public boolean isEmpty() {
for (int i = 0; i < this.uv.length; i++) {
if (this.uv[i] == null) {
this.uv[i] = 0.0F;
}
}
return this.texture == null || TMath.isSimilar(this.uv[0], this.uv[2]) || TMath.isSimilar(this.uv[1], this.uv[3]);
}
public Float[] getUv() {
return this.uv;
}
public Integer getRotation() {
return this.rotation;
}
public Integer getTexture() {
return this.texture;
}
}
public static class Group {
protected String name;
protected Float[] origin;
protected Float[] rotation;
protected UUID uuid;
protected UUID parentGroup;
protected boolean export;
protected final Set<UUID> element = new HashSet<>();
protected final Map<UUID, BlockbenchModel.Group> childGroup = new HashMap<>();
public String getName() {
return this.name;
}
public Float[] getOrigin() {
return this.origin;
}
public Float[] getRotation() {
return this.rotation;
}
public UUID getUuid() {
return this.uuid;
}
public UUID getParentGroup() {
return this.parentGroup;
}
public boolean isExport() {
return this.export;
}
public Set<UUID> getElement() {
return this.element;
}
public Map<UUID, BlockbenchModel.Group> getChildGroup() {
return this.childGroup;
}
}
public static class Keyframe {
protected String channel;
protected List<Map<String, String>> data_points = new ArrayList<>();
protected Float time;
protected String interpolation;
protected Float[] bezier_left_time;
protected Float[] bezier_left_value;
protected Float[] bezier_right_time;
protected Float[] bezier_right_value;
public String getChannel() {
return this.channel;
}
public List<Map<String, String>> getData_points() {
return this.data_points;
}
public Float getTime() {
return this.time;
}
public String getInterpolation() {
return this.interpolation;
}
public Float[] getBezier_left_time() {
return this.bezier_left_time;
}
public Float[] getBezier_left_value() {
return this.bezier_left_value;
}
public Float[] getBezier_right_time() {
return this.bezier_right_time;
}
public Float[] getBezier_right_value() {
return this.bezier_right_value;
}
}
public static class Locator extends BlockbenchModel.Element {
protected Float[] position;
protected Float[] rotation;
protected Boolean ignore_inherited_scale;
public Float[] getPosition() {
return this.position;
}
public Float[] getRotation() {
return this.rotation;
}
public Boolean getIgnore_inherited_scale() {
return this.ignore_inherited_scale;
}
}
public static class NullObject extends BlockbenchModel.Element implements BlockbenchModel.AnimatableElement {
protected Float[] position;
protected String ik_target;
protected String ik_source;
protected Boolean lock_ik_target_rotation;
@Override
public Float[] getOrigin() {
return this.position;
}
@Nullable
@Override
public Float[] getRotation() {
return null;
}
@Override
public Float[] getPosition() {
return this.position;
}
public String getIk_target() {
return this.ik_target;
}
public String getIk_source() {
return this.ik_source;
}
public Boolean getLock_ik_target_rotation() {
return this.lock_ik_target_rotation;
}
}
public static class Resolution {
protected Integer width;
protected Integer height;
public Integer getWidth() {
return this.width;
}
public Integer getHeight() {
return this.height;
}
}
public static class Texture {
protected String name;
protected String folder;
protected String namespace;
protected String id;
protected Integer width;
protected Integer height;
protected Integer uv_width;
protected Integer uv_height;
protected Integer frame_time;
protected String frame_order;
protected Boolean frame_interpolate;
protected UUID uuid;
protected String raw_mcmeta;
protected String source;
public String getName() {
return this.name;
}
public String getFolder() {
return this.folder;
}
public String getNamespace() {
return this.namespace;
}
public String getId() {
return this.id;
}
public Integer getWidth() {
return this.width;
}
public Integer getHeight() {
return this.height;
}
public Integer getUv_width() {
return this.uv_width;
}
public Integer getUv_height() {
return this.uv_height;
}
public Integer getFrame_time() {
return this.frame_time;
}
public String getFrame_order() {
return this.frame_order;
}
public Boolean getFrame_interpolate() {
return this.frame_interpolate;
}
public UUID getUuid() {
return this.uuid;
}
public String getRaw_mcmeta() {
return this.raw_mcmeta;
}
public String getSource() {
return this.source;
}
}
public static class Unknown extends BlockbenchModel.Element {
}
}
@@ -0,0 +1,168 @@
package com.ticxo.modelengine.api.generator.parser.blockbench;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
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.utils.data.GSONUtils;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.TreeMap;
import java.util.UUID;
import java.util.Map.Entry;
public class LegacyDeserializer {
private static final Gson gson = new GsonBuilder()
.registerTypeAdapter(BlockbenchModel.Element.class, new LegacyDeserializer.ElementDeserializer())
.registerTypeAdapter(BlockbenchModel.Group.class, new LegacyDeserializer.GroupDeserializer())
.registerTypeAdapter(BlockbenchModel.Animation.class, new LegacyDeserializer.AnimationDeserializer())
.registerTypeAdapter(BlockbenchModel.Animator.class, new LegacyDeserializer.AnimatorDeserializer())
.registerTypeAdapter(BlockbenchModel.Face.class, new LegacyDeserializer.FaceDeserializer())
.create();
protected static BlockbenchModel deserialize(JsonObject root) {
BlockbenchModel.Resolution resolution = (BlockbenchModel.Resolution)gson.fromJson(root.get("resolution"), BlockbenchModel.Resolution.class);
HashMap<UUID, BlockbenchModel.Element> elements = new HashMap<>();
GSONUtils.ifArray(root, "elements", e -> {
BlockbenchModel.Element element = (BlockbenchModel.Element)gson.fromJson(e, BlockbenchModel.Element.class);
elements.put(element.uuid, element);
});
HashMap<UUID, BlockbenchModel.Group> outliner = new HashMap<>();
GSONUtils.ifArray(root, "outliner", e -> {
if (e.isJsonObject()) {
BlockbenchModel.Group group = (BlockbenchModel.Group)gson.fromJson(e, BlockbenchModel.Group.class);
outliner.put(group.uuid, group);
}
});
HashMap<Integer, BlockbenchModel.Texture> textures = new HashMap<>();
HashMap<UUID, BlockbenchModel.Texture> textureCache = new HashMap<>();
GSONUtils.ifArray(root, "textures", (index, e) -> {
BlockbenchModel.Texture texture = (BlockbenchModel.Texture)gson.fromJson(e, BlockbenchModel.Texture.class);
textures.put(index, texture);
textureCache.put(texture.uuid, texture);
});
LinkedHashMap<String, BlockbenchModel.Animation> animations = new LinkedHashMap<>();
GSONUtils.ifArray(root, "animations", e -> {
BlockbenchModel.Animation animation = (BlockbenchModel.Animation)gson.fromJson(e, BlockbenchModel.Animation.class);
animations.put(animation.name, animation);
});
GSONUtils.ifPresent(root, "mcmetas", element -> {
JsonObject elementData = element.getAsJsonObject();
for (Entry<String, JsonElement> entry : elementData.entrySet()) {
UUID uuid = UUID.fromString(entry.getKey());
BlockbenchModel.Texture texture = textureCache.get(uuid);
if (texture != null) {
texture.raw_mcmeta = entry.getValue().toString();
}
}
});
String animationPlaceholder = GSONUtils.get(root, "animation_variable_placeholders", JsonElement::getAsString, "");
return new BlockbenchModel(resolution, elements, outliner, textures, animations, animationPlaceholder).preprocess();
}
static class AnimationDeserializer implements JsonDeserializer<BlockbenchModel.Animation> {
public BlockbenchModel.Animation deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
BlockbenchModel.Animation animation = new BlockbenchModel.Animation();
animation.uuid = GSONUtils.get(jsonElement, "uuid", GSONUtils::getAsUUID);
animation.name = GSONUtils.get(jsonElement, "name", JsonElement::getAsString);
animation.loop = GSONUtils.get(jsonElement, "loop", JsonElement::getAsString);
animation.override = GSONUtils.get(jsonElement, "override", JsonElement::getAsBoolean);
animation.length = GSONUtils.get(jsonElement, "length", JsonElement::getAsFloat);
GSONUtils.ifPresent(
jsonElement,
"animators",
e -> {
if (e.isJsonObject()) {
JsonObject animators = e.getAsJsonObject();
for (String key : animators.keySet()) {
BlockbenchModel.Animator animator = (BlockbenchModel.Animator)LegacyDeserializer.gson
.fromJson(animators.getAsJsonObject(key), BlockbenchModel.Animator.class);
if (key.equals("effects")) {
animation.effects = animator;
} else {
try {
UUID uuid = UUID.fromString(key);
animator.uuid = uuid;
animation.animators.put(uuid, animator);
} catch (IllegalArgumentException var7) {
if (animation.unknown_animators == null) {
animation.unknown_animators = new HashMap<>();
}
animation.unknown_animators.put(key, animator);
}
}
}
}
}
);
return animation;
}
}
static class AnimatorDeserializer implements JsonDeserializer<BlockbenchModel.Animator> {
public BlockbenchModel.Animator deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
BlockbenchModel.Animator animator = new BlockbenchModel.Animator();
animator.name = GSONUtils.get(jsonElement, "name", JsonElement::getAsString);
animator.rotation_global = GSONUtils.get(jsonElement, "rotation_global", JsonElement::getAsBoolean);
GSONUtils.ifArray(jsonElement, "keyframes", e -> {
BlockbenchModel.Keyframe keyframe = (BlockbenchModel.Keyframe)LegacyDeserializer.gson.fromJson(e, BlockbenchModel.Keyframe.class);
animator.channels.computeIfAbsent(keyframe.channel, s -> new TreeMap<>()).put(keyframe.time, keyframe);
});
return animator;
}
}
static class ElementDeserializer implements JsonDeserializer<BlockbenchModel.Element> {
public BlockbenchModel.Element deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject root = jsonElement.getAsJsonObject();
String elementType = GSONUtils.get(root, "type", JsonElement::getAsString, "cube");
Gson var10000 = LegacyDeserializer.gson;
return (BlockbenchModel.Element)var10000.fromJson(jsonElement, switch (elementType) {
case "cube" -> BlockbenchModel.Cube.class;
case "null_object" -> BlockbenchModel.NullObject.class;
case "locator" -> BlockbenchModel.Locator.class;
case "camera" -> BlockbenchModel.Camera.class;
default -> BlockbenchModel.Unknown.class;
});
}
}
static class FaceDeserializer implements JsonDeserializer<BlockbenchModel.Face> {
public BlockbenchModel.Face deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
BlockbenchModel.Face face = new BlockbenchModel.Face();
face.uv = GSONUtils.get(jsonElement, "uv", e -> (Float[])LegacyDeserializer.gson.fromJson(e, Float[].class));
face.rotation = GSONUtils.get(jsonElement, "rotation", JsonElement::getAsInt);
face.texture = GSONUtils.get(jsonElement, "texture", JsonElement::getAsInt);
return face;
}
}
static class GroupDeserializer implements JsonDeserializer<BlockbenchModel.Group> {
public BlockbenchModel.Group deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
BlockbenchModel.Group group = new BlockbenchModel.Group();
group.name = GSONUtils.get(jsonElement, "name", JsonElement::getAsString);
group.origin = GSONUtils.get(jsonElement, "origin", GSONUtils::getAsFloatArray);
group.rotation = GSONUtils.get(jsonElement, "rotation", GSONUtils::getAsFloatArray);
group.uuid = GSONUtils.get(jsonElement, "uuid", GSONUtils::getAsUUID);
group.export = GSONUtils.get(jsonElement, "export", JsonElement::getAsBoolean, true);
GSONUtils.ifArray(jsonElement, "children", e -> {
if (e.isJsonPrimitive()) {
group.element.add(GSONUtils.getAsUUID(e));
} else if (e.isJsonObject()) {
BlockbenchModel.Group childGroup = (BlockbenchModel.Group)LegacyDeserializer.gson.fromJson(e, BlockbenchModel.Group.class);
group.childGroup.put(childGroup.uuid, childGroup);
childGroup.parentGroup = group.uuid;
}
});
return group;
}
}
}
@@ -0,0 +1,248 @@
package com.ticxo.modelengine.api.generator.parser.blockbench;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
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.utils.data.GSONUtils;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import java.util.Map.Entry;
import org.jetbrains.annotations.Nullable;
public class v5_0_Deserializer {
private static final Gson gson = new GsonBuilder()
.registerTypeAdapter(BlockbenchModel.Element.class, new v5_0_Deserializer.ElementDeserializer())
.registerTypeAdapter(BlockbenchModel.Group.class, new v5_0_Deserializer.GroupDeserializer())
.registerTypeAdapter(BlockbenchModel.Animation.class, new v5_0_Deserializer.AnimationDeserializer())
.registerTypeAdapter(BlockbenchModel.Animator.class, new v5_0_Deserializer.AnimatorDeserializer())
.registerTypeAdapter(BlockbenchModel.Face.class, new v5_0_Deserializer.FaceDeserializer())
.create();
protected static BlockbenchModel deserialize(JsonObject root) {
BlockbenchModel.Resolution resolution = (BlockbenchModel.Resolution)gson.fromJson(root.get("resolution"), BlockbenchModel.Resolution.class);
HashMap<UUID, BlockbenchModel.Element> elements = new HashMap<>();
GSONUtils.ifArray(root, "elements", e -> {
BlockbenchModel.Element element = (BlockbenchModel.Element)gson.fromJson(e, BlockbenchModel.Element.class);
elements.put(element.uuid, element);
});
HashMap<UUID, BlockbenchModel.Group> groups = new HashMap<>();
GSONUtils.ifArray(root, "groups", e -> {
if (e.isJsonObject()) {
BlockbenchModel.Group group = (BlockbenchModel.Group)gson.fromJson(e, BlockbenchModel.Group.class);
groups.put(group.uuid, group);
}
});
HashMap<UUID, BlockbenchModel.Group> outliner = new HashMap<>();
GSONUtils.ifArray(root, "outliner", e -> {
if (e.isJsonObject()) {
BlockbenchModel.Group g = nestGroups(e, groups);
if (g != null) {
outliner.put(g.uuid, g);
}
}
});
HashMap<Integer, BlockbenchModel.Texture> textures = new HashMap<>();
HashMap<UUID, BlockbenchModel.Texture> textureCache = new HashMap<>();
GSONUtils.ifArray(root, "textures", (index, e) -> {
BlockbenchModel.Texture texture = (BlockbenchModel.Texture)gson.fromJson(e, BlockbenchModel.Texture.class);
textures.put(index, texture);
textureCache.put(texture.uuid, texture);
});
LinkedHashMap<String, BlockbenchModel.Animation> animations = new LinkedHashMap<>();
GSONUtils.ifArray(root, "animations", e -> {
BlockbenchModel.Animation animation = (BlockbenchModel.Animation)gson.fromJson(e, BlockbenchModel.Animation.class);
animations.put(animation.name, animation);
});
GSONUtils.ifPresent(root, "mcmetas", element -> {
JsonObject elementData = element.getAsJsonObject();
for (Entry<String, JsonElement> entry : elementData.entrySet()) {
UUID uuid = UUID.fromString(entry.getKey());
BlockbenchModel.Texture texture = textureCache.get(uuid);
if (texture != null) {
texture.raw_mcmeta = entry.getValue().toString();
}
}
});
String animationPlaceholder = GSONUtils.get(root, "animation_variable_placeholders", JsonElement::getAsString, "");
return new BlockbenchModel(resolution, elements, outliner, textures, animations, animationPlaceholder).preprocess();
}
@Nullable
private static BlockbenchModel.Group nestGroups(JsonElement element, Map<UUID, BlockbenchModel.Group> flatGroups) {
JsonObject obj = element.getAsJsonObject();
UUID uuid = GSONUtils.getAsUUID(obj.get("uuid"));
BlockbenchModel.Group root = flatGroups.get(uuid);
if (root == null) {
return null;
} else {
GSONUtils.ifArray(element, "children", e -> {
if (e.isJsonPrimitive()) {
root.element.add(GSONUtils.getAsUUID(e));
} else if (e.isJsonObject()) {
BlockbenchModel.Group g = nestGroups(e, flatGroups);
if (g != null) {
root.getChildGroup().put(g.uuid, g);
g.parentGroup = root.uuid;
}
}
});
return root;
}
}
static class AnimationDeserializer implements JsonDeserializer<BlockbenchModel.Animation> {
public BlockbenchModel.Animation deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
BlockbenchModel.Animation animation = new BlockbenchModel.Animation();
animation.uuid = GSONUtils.get(jsonElement, "uuid", GSONUtils::getAsUUID);
animation.name = GSONUtils.get(jsonElement, "name", JsonElement::getAsString);
animation.loop = GSONUtils.get(jsonElement, "loop", JsonElement::getAsString);
animation.override = GSONUtils.get(jsonElement, "override", JsonElement::getAsBoolean);
animation.length = GSONUtils.get(jsonElement, "length", JsonElement::getAsFloat);
GSONUtils.ifPresent(
jsonElement,
"animators",
e -> {
if (e.isJsonObject()) {
JsonObject animators = e.getAsJsonObject();
for (String key : animators.keySet()) {
BlockbenchModel.Animator animator = (BlockbenchModel.Animator)v5_0_Deserializer.gson
.fromJson(animators.getAsJsonObject(key), BlockbenchModel.Animator.class);
if (key.equals("effects")) {
animation.effects = animator;
} else {
try {
UUID uuid = UUID.fromString(key);
animator.uuid = uuid;
animation.animators.put(uuid, animator);
} catch (IllegalArgumentException var7) {
if (animation.unknown_animators == null) {
animation.unknown_animators = new HashMap<>();
}
animation.unknown_animators.put(key, animator);
}
}
}
}
}
);
return animation;
}
}
static class AnimatorDeserializer implements JsonDeserializer<BlockbenchModel.Animator> {
public BlockbenchModel.Animator deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
BlockbenchModel.Animator animator = new BlockbenchModel.Animator();
animator.name = GSONUtils.get(jsonElement, "name", JsonElement::getAsString);
animator.rotation_global = GSONUtils.get(jsonElement, "rotation_global", JsonElement::getAsBoolean);
GSONUtils.ifArray(jsonElement, "keyframes", e -> {
BlockbenchModel.Keyframe keyframe = (BlockbenchModel.Keyframe)v5_0_Deserializer.gson.fromJson(e, BlockbenchModel.Keyframe.class);
String var4x = keyframe.channel.toUpperCase(Locale.ENGLISH);
switch (var4x) {
case "POSITION":
keyframe.getData_points().forEach(map -> this.tryFlipSign((Map<String, String>)map, "x"));
this.flipBezierValues(keyframe, 0);
break;
case "ROTATION":
keyframe.getData_points().forEach(map -> {
this.tryFlipSign((Map<String, String>)map, "x");
this.tryFlipSign((Map<String, String>)map, "y");
});
this.flipBezierValues(keyframe, 0, 1);
}
animator.channels.computeIfAbsent(keyframe.channel, s -> new TreeMap<>()).put(keyframe.time, keyframe);
});
return animator;
}
private void tryFlipSign(Map<String, String> map, String axis) {
String val = map.get(axis);
if (val != null) {
map.put(axis, this.flipSign(val));
}
}
private String flipSign(String val) {
try {
double d = Double.parseDouble(val);
return Double.toString(-d);
} catch (IllegalArgumentException var4) {
return "-(" + val + ")";
}
}
private void flipBezierValues(BlockbenchModel.Keyframe keyframe, int... axes) {
this.flipBezierValue(keyframe.getBezier_left_value(), axes);
this.flipBezierValue(keyframe.getBezier_right_value(), axes);
}
private void flipBezierValue(Float[] values, int... axes) {
if (values != null) {
for (int axis : axes) {
if (axis < values.length && values[axis] != null) {
values[axis] = -values[axis];
}
}
}
}
}
static class ElementDeserializer implements JsonDeserializer<BlockbenchModel.Element> {
public BlockbenchModel.Element deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject root = jsonElement.getAsJsonObject();
String elementType = GSONUtils.get(root, "type", JsonElement::getAsString, "cube");
Gson var10000 = v5_0_Deserializer.gson;
return (BlockbenchModel.Element)var10000.fromJson(jsonElement, switch (elementType) {
case "cube" -> BlockbenchModel.Cube.class;
case "null_object" -> BlockbenchModel.NullObject.class;
case "locator" -> BlockbenchModel.Locator.class;
case "camera" -> BlockbenchModel.Camera.class;
default -> BlockbenchModel.Unknown.class;
});
}
}
static class FaceDeserializer implements JsonDeserializer<BlockbenchModel.Face> {
public BlockbenchModel.Face deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
BlockbenchModel.Face face = new BlockbenchModel.Face();
face.uv = GSONUtils.get(jsonElement, "uv", e -> (Float[])v5_0_Deserializer.gson.fromJson(e, Float[].class));
face.rotation = GSONUtils.get(jsonElement, "rotation", JsonElement::getAsInt);
face.texture = GSONUtils.get(jsonElement, "texture", JsonElement::getAsInt);
return face;
}
}
static class GroupDeserializer implements JsonDeserializer<BlockbenchModel.Group> {
public BlockbenchModel.Group deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
BlockbenchModel.Group group = new BlockbenchModel.Group();
group.name = GSONUtils.get(jsonElement, "name", JsonElement::getAsString);
group.origin = GSONUtils.get(jsonElement, "origin", GSONUtils::getAsFloatArray);
group.rotation = GSONUtils.get(jsonElement, "rotation", GSONUtils::getAsFloatArray);
group.uuid = GSONUtils.get(jsonElement, "uuid", GSONUtils::getAsUUID);
group.export = GSONUtils.get(jsonElement, "export", JsonElement::getAsBoolean, true);
GSONUtils.ifArray(jsonElement, "children", e -> {
if (e.isJsonPrimitive()) {
group.element.add(GSONUtils.getAsUUID(e));
} else if (e.isJsonObject()) {
BlockbenchModel.Group childGroup = (BlockbenchModel.Group)v5_0_Deserializer.gson.fromJson(e, BlockbenchModel.Group.class);
group.childGroup.put(childGroup.uuid, childGroup);
childGroup.parentGroup = group.uuid;
}
});
return group;
}
}
}
Loaded 100 of 1072 files, more files were not shown because too many files have changed in this diff. Show more